Now we need to generate next integer and add it to the sum. How can we get the next integer? Just by adding 1 to the integer, we will get the next integer. In ‘C’, we will write it as:

 

                  number = number + 1;

Similarly in the above statement, we get the original contents of number (i.e. 1). Add 1 to them and then store the result (i.e. 2) into the number. Now we need to add this new number into sum:

                 sum = sum + number;

We add the contents of sum (i.e. 1) to the contents of number (i.e. 1) and then store the result (i.e. 2) to the sum. Again we need to get the next integer which can be obtained by adding 1 to the number. In other words, our action consists of only two statements i.e. add the number to the sum and get the next integer. So our action statements will be:

                       sum = sum + number;

                      number = number + 1;

Putting the action statements in while construct:

                      while ( number  <= 1000 ) {

                             sum = sum + number;

                            number = number + 1;

                      }

Let's analyze the above while loop. Initially the contents of number is 1. The condition in while loop (i.e. number <= 1000) will be evaluated as true, contents of sum and contents of number will be added and the result will be stored into sum. Now 1 will be added to the contents of number and number becomes 2. Again the condition in while loop will be evaluated as true and the contents of sum will be added to the contents of number .The result will be stored into sum. Next 1 will be added to the contents of number and number becomes 3 and so on. When number becomes 1000, the condition in while loop evaluates to be true, as we have used <= (less than or equal to) in the condition. The contents of sum will be added to the contents of number (i.e. 1000) and the result will be stored into the sum. Next 1 will be added to the contents of number and number becomes 1001. Now the condition in while loop is evaluated to false, as number is no more less than or equal to 1000 (i.e. number has become 1001). When the condition of while loop becomes false, loop is terminated. The control of the program will go to the next statement following the ending brace of the while construct. After the while construct, we can display the result using the cout statement.

cout << “ The sum of first 1000 integers starting from 1 is “ << sum;

 

 

Previous

 

TOC

 

Next