Even printing program in C


Advertisements

This program is very simple and a good example of using conditional statement (if-else) in an iteration (i.e. for loop). We shall initiate a for loop having some finite iterations and check every value of it. Using if conditional statements we shall determine and print if the value is even.

We can use % (mode) operator to find if the value is completely divisible by 2. If the value is completely divisible by 2 it is even, otherwise it is odd.

Algorithm

Let's first see what should be the step-by-step procedure to write this program −

START
   Step 1 → Iterate value from 1 to 10
   Step 2 → Check if value is divisible by 2
   Step 3 → If true then display value
STOP

Pseudocode

Let's now see the pseudocode of this algorithm −

procedure even_printing(A, B)

   FOR value 1 to 10 DO
      IF value%2 EQUAL TO 0 THEN 
         DISPLAY value as even
      END IF
   END FOR

end procedure

Implementation

Now, we shall see the actual implementation of the program −

#include <stdio.h>

int main() {
   int i;

   for(i = 1; i <= 10; i++) {
      if(i%2 == 0)
         printf(" %2d\n", i);
   }
   return 0;
}

Output

Output of this program should be −

  2
  4
  6
  8
 10
loop_examples_in_c.htm
Advertisements