Sample Program 2
|
![]() |
|||
Problem statement:
Calculate the sum of even numbers for a given
upper limit of integers. Solution:
We analyze the problem and know that while
statement will be used. We need to sum even numbers only. How can we decide
that a number is even or not? We know that the number that is divisible by 2
is an even number. How can we do this in C language? We can say that if a
number is divisible by 2, it means its remainder is zero, when divided by 2.
To get a remainder we can use C’s modulus operator i.e. %. We can say that
for a number if the expression (number % 2) results in zero, the number is
even. Putting this in a conditional statement: If ( ( number % 2) == 0 ) The above conditional statement becomes true, when the number is even and false when the number is
odd (A number is either even or odd). |
||||
|
|
Previous |
TOC |
Next |
|