|
|
|
|
|||
|
As we have declared another variable of int data type, so the variables of same data type can be declared
in one line.
int sum, number; Going back to our problem, we need to sum up all
the integers from 1 to 1000. Our first integer is 1. The variable number is to be used to store integers, so we will initialize it by 1
as our first integer is 1:
number = 1; Now we have two variables- sum and number. That means we have two memory
locations labeled as sum and number which will be used to store sum of
integers and integers respectively. In the variable sum, we have to add all the integers from 1 to 1000. So we will add
the value of variable number into variable sum, till the time the value of number becomes 1000. So when the
value of number becomes 1000, we will stop adding integers into sum. It will become the condition of our while loop. We can say sum
the integers until integer becomes 1000. In C language, this condition can be
written as: while ( number <= 1000 ) { ………Action ……… } The above condition means, 'perform the action
until the number is 1000 or less than 1000'. What will be the Action? Add the
number, the value of number is 1 initially, into
sum. This is a very simple statement: sum = sum + number; Let’s analyze the above statement carefully.
We did not write sum = number; as this statement
will replace the contents of sum and the previous
value of sum will be wasted as
this is an assignment statement. What we did? We added the contents of sum and contents of number first (i.e. 0 + 1)
and then stored the result of this (i.e. 1) to the sum. |
|||||
|
|
Previous |
TOC |
Next |
||