Next: Example while loop: Table
Up: The while statement
Previous: Example while loop: Printing
The following portion of C++ uses a while
statement to produce
the sum 1+2+3+
...+n
, where a value for n
is
entered by the user. It assumes that integer variables i
,
n
and sum
have been declared:
cout << "Enter a value for n: "; cin >> n; sum = 0; i = 1; while (i <= n) { sum += i; i++; } cout << "The sum of the first " << n << " numbers is " << sum << endl;
Download program.There are several important points to note here:
i <= n
requires that i
and n
must have
values before the while
loop is executed.
Hence the initialisation of i
to 1 and
the entry of a value for n
before the while
statement.while
loop may not be executed at all. For
example if the user entered a value 0 for n
then the condition
i <= n
would be false initially and the statement part of the
while
loop would never be entered.n
that was less than 1 then the initialisation of sum
would
mean that the program would return zero as the accumulated total --
if n
is zero this is certainly a sensible value.while
statement for a particular loop.
For example the loop in this example could have been written as
follows:i = 0; while (i < n) { i = i + 1; sum = sum + i; }without changing the result.