# while statement in C++

The second type of loop, the `while`

loop, is used when we are not certain that the loop will be executed. After checking whether the initial condition is true or false and finding it to be true, then only `while`

loop will enter into the loop operations.

The general form of the `while`

loop for a single statement is:

while(expression) statement;

The general form of the `while`

loop for a block of statements is:

while(expression) { statement 1; statement 2; .... .... }

The **expression** can be any valid C++ language expression including the value of a variable, an unary or a binary expression, or the value returned by a function. The **statement** can be single or compount statement.

The **statement** will be executed repeatedly, as long as the **expression** is true (i.e., as long as **expression** has a non zero value). **statement** must include some features that eventually alters the value of the **expression**, thus providing a stopping condition for the loop.

**Program to compute a sum of consecutive integers, i.e., the program to compute the sum 1 + 2 + 3 + .. + n, for an integer input n**

#include int main() { int n, i=1; cout << "Enter a positive integer: "; cin >> n; long sum = 0; while(i<=n) { sum = sum + 1; i = i + 1; } cout << "Sum of first " << n << " integers is: " << sum; }

I’m not that much of a internet reader to be honest but your sites really nice, keep it up!

I’ll go ahead and bookmark your website to come back in the future.

All the best

the final program will run forever. You aren’t incrementing variable ‘i’ inside the while loop so ‘i’ will never be <= 'n'.

* ‘i’ will never be > ‘n’

Thanks a lot for pointing it. We have rectified it.

Thanks again,

LearnCPPOnline Team