6136 Shares

Topic: Why is this an infinte loop in C++ ?**Question:**
I' trying to calculate the number of steps required to get to 1 from a number by using the floor function and sqrt function. I have to get to 1 by calculating the floor of square root of number.
for example for number 4 the output should be 2 because
sqrt 4 = 2
sqrt 2 = 1.4
and floor of 1.4 = 1
my code is like:
int n ;
cout << "Please enter a number"<< endl;
cin >> n;
int counter = 0;
double val = n; //
int steps = floor (sqrt (val));
while (steps >= 1)
{
steps = floor (sqrt (val));
counter++;
}
cout << "It takes " <

April 19, 2019 / By Florence

Steps is always equal to floor(sqrt(val)) so it never falls to 1. Even if you had val = 1, the square root would still be 1 so the while loop would never exit. I think what you intended was steps = floor(sqrt(steps)); inside the while loop. then change the while test to just greater than 1. You may want to change how steps is initialized as well. Shadow Wolf

👍 228 | 👎 10

Did you like the answer? Because the loop's condition is that steps >= 1, and the value of steps never changes. In the loop, you set steps equal to floor(sqrt(val)), but since val never changes, steps never changes.

👍 90 | 👎 1

1st: while (steps>=1),if steps reachs 1 while loop is still continued so your loop will not have exit way. 2nd: steps=floor(sqrt(val)); But the value of val is never change so your loop will be never exit. Fix: while (steps>1) { val=sqrt(val); steps=floor(val); counter++; }

👍 81 | 👎 -8

If you have your own answer to the question Why is this an infinte loop in C++ ?, then you can write your own version, using the form below for an extended answer.
/**
* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://help-rspaper.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
Please enable JavaScript to view the comments powered by Disqus.

Copyright 2019. All rights reserved | Read and Answer the Questions 2019