2069 Shares

Why is this an infinte loop in C++ ? Topic: Why is this an infinte loop in C++ ?
June 18, 2019 / By Florence
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 " < Best Answers: Why is this an infinte loop in C++ ? Darrin | 10 days ago
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? Why is this an infinte loop in C++ ? Share with your friends Bailey
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 Winnie
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.