![]() ![]() |
![]() ![]() ![]() ![]() |
![]() ![]() |
![]() | Section 4: Control Statements |
for(initial_value,test_condition,step){ // code to execute inside loop };
Here is an example:
// The following code adds together the numbers 1 through 10 // this variable keeps the running total int total=0; // this loop adds the numbers 1 through 10 to the variable total for (int i=1; i < 11; i++){ total = total + i; }
So in the preceding chunk of code we have:
int i=0;
i < 11;
i++;
So, upon initial execution of the loop, the integer
variable i
is set to 1. The statement
total = total + i;
is executed and the value of
the variable total
becomes 1. The
step code
is now executed and i
is incremented
by 1, so its new value is 2.
The test_condition is then checked, and since
i
is less than 11, the loop code is executed and
the variable total
gets the value 3 (since
total
was 1, and i
was 2.
i
is then incremented by 1 again.
The loop continues to execute until the condition
i<11
fails. At that point total
will have the value 1+2+3+4+5+6+7+8+9+10 = 55.
while(condition) { // code to execute };
while
statement
executes. If the condition is true then the
while
statement executes again. If the condition
is false, the while
statement does not execute again.
As an example, let's say that we wanted to write all the even numbers between 11 and 23 to the screen. The following is a full C++ program that does that.
// include this file for cout #include <iostream.h> int main(){ // this variable holds the present number int current_number = 12; // while loop that prints all even numbers between // 11 and 23 to the screen while (current_number < 23){ cerr << current_number << endl; current_number += 2; } cerr << "all done" << endl; }
The preceding example prints the value of
current_number
to the screen and then adds
2 to its value. As soon as the value of the variable
current_number
goes above 23, the while loop
exits and the next line is executed.
The output of the preceding program would be:
12 14 16 18 20 22 all done
![]() ![]() |
![]() ![]() ![]() ![]() |
![]() ![]() |