I copied this code from C++ Primer as an example for while loops, and it doesn't output anything. I'm using g++.
#include <iostream>
int main()
{
int sum = 0, val = 1;
// keep executing the while as long val is less than or equal to 10
while (val <= 10) {
sum += val; // assigns sum+ val to sum\
++val; // add 1 to val
}
std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;
return 0;
}
Infinite while loop refers to a while loop where the while condition never becomes false. When a condition never becomes false, the program enters the loop and keeps repeating that same block of code over and over again, and the loop never ends.
Basically, the infinite loop happens when the condition in the while loop always evaluates to true. This can happen when the variables within the loop aren't updated correctly, or aren't updated at all.
To break out of a while loop, you can use the endloop, continue, resume, or return statement. endwhile; If the name is empty, the other statements are not executed in that pass through the loop, and the entire loop is closed.
The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop. To exit a function, use return .
sum += val; // assigns sum+ val to sum\
Get rid of the backslash at the end of the line. That's a line continuation character. It causes the next line to be concatenated to this line; in other words, ++val
becomes part of the "assigns sum+ val to sum" comment.
sum += val; // assigns sum+ val to sum\ <-- typo
++val; // add 1 to val
You got a typo at that sum += val;
line. The "\" at the end make the following line a comment, thus making the while
an infinite loop as val
was never increased. Remove "\", then it would work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With