Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this while loop end?

Tags:

c++

while-loop

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;
}
like image 793
NeoJuice Avatar asked Dec 04 '16 05:12

NeoJuice


People also ask

Why does the while loop never stop?

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.

Why is my while loop infinite?

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.

How do you force a while loop to end?

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.

How do you end a while loop program?

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 .


2 Answers

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.

like image 128
John Kugelman Avatar answered Nov 04 '22 03:11

John Kugelman


    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.

like image 44
artm Avatar answered Nov 04 '22 01:11

artm