Tuesday, February 17, 2009

Another Loop Sample

You want to display only even numbers between 1 - 100. You can try this program in C.

[+/-] show/hide

#include stdio.h /* enclose the stdio.h in between <> */
int x;
clrscr(); /* this is used to clear the screen */
printf("The even numbers are :\n");

for (x=1;x<=100;x++)
if (x % 2 ==0)
printf(" %d ",x);
getche(); } /* the % is a MOD operator or gets the remainder. If the operation results to zero, it means the number is divisible by two, thus, it is an even number */ In Bloodshed C++, it can be like this:

#include iostream /* enclose the iostream in between <> */
#include iomanip /*enclose the iomanip in between <> */
using namespace std;
int x;

cout<<"The even numbers are :"<

for (x=1;x<=100;x++) if (x % 2 ==0) cout<<\ /* the slash means to concatenate the statements*/ setw(2)<<\ x;


In C++, the setw() is used to set spaces supported by the library iomanip.