Friday, April 11, 2014

Printing even numbers using for loop in c programming


  • The below code shows how to directly print all even numbers from 2 to 20 without using the if....else conditional statement to check for the remainder as usually done and then decide whether even or not.

   #include<stdio.h>
   #include<conio.h>

   int main()
   {
      int i;
      clrscr();
    
      for (i=2;i<=20;i=i+2)
      {
          printf(" %d\n",i);
      }
    
      getch();
      return 0;

   }

The above code is not the perfect way to find and print even numbers but it will correctly find and print the even numbers because the range is starting from a static integer 2 and then incremented each time by 2 which will result only in even numbers. But this will not work when we will accept the range from user as you know user can enter any number for starting and ending values and in case if he enter 1 or any other odd number then this program will will print out all the odd numbers instead of even. But this code works perfectly if the programmer knows the range prior. To know the perfect way to find & print even numbers check out our article >> printing even numbers from a user provided range.

We hope you liked our post for more articles keep browsing and keep visiting and do comment.

Happy Programming !

No comments :

Post a Comment