Saturday, December 12, 2009

4.2 THE while STATEMENT

Suppose that we want to display hello on output screen five times in five different lines,we might think of writing either five printf statements or one printf statements or one printf statement consisting of constant string "hello\n" five times.What if we want to print 500 times .Should we write 500 printf statements or equivalent?obviously not.It means that we need some programming facility to repeat certain works.

The while statement is used to carry out looping operations,in which a group of statements is executed repeatedly,until some condition has been satisfied.

The general form of the while statement is

while(expression) statement

The statement will be executed repeatedly,as long as the expression is true.

Let us write a program to convert a line of lowercase text to uppercase with the help of while loop

/*convert a line of lowercase text to uppercase*/

# include stdio.h
# include ctype.h

#define EOL '\n'

main()

{
char letter[80];
int fla,count=0;

/*read in the lowercase text*/

while((letter[count]=getchar())!=EOL) ++count;
fla=count;

/*display the uppercase text*/

count=0;
while ( count < fla ){
putchar(toupper(letter[count]));
++count;
}

}

The first while loop i.e.

while((letter[count]=getchar())!=EOL) ++count;

is written very concisely.This single statement loop is equivalent to the following:

letter[count]=getchar();
while(letter[count]!=EOL)
{
count=count+1;
letter[count]=getchar();
}

when the program is executed,any line of text entered into the computer will be displayed in the uppercase.Suppose ,for example,that the following line of text had been entered:

fourscore and seven yeas ago our fathers brought forth....

The computer will respond by printing

FOURSCORE AND SEVEN YEARS AGO OUR FATHERS BROUGHT FORTH...

No comments:

Post a Comment