Saturday, December 11, 2010

Loops1

the for statement

the for statement has the form:
for(initial_value,test_condition,step){
   // code to execute inside loop
};

  • initial_value sets up the initial value of the loop counter.
  • test_condition this is the condition that is tested to see if the loop is executed again.
  • step this describes how the counter is changed on each execution of the 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:
  • initial_condition is int i=0;
  • test_condition is i < 11;
  • step is 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.

No comments:

Post a Comment