Sunday, December 13, 2009

4.3 THE do-while STATEMENT

When a loop is constructed using the while statement the test for continuation of the loop is carried out at the beginning of each pass.Sometimes, however, it is desirable to have a loop with the test for continuation at the end of each pass.This can be accomplished by means of the do-while statement.

The general form of the do-while statement is

do statement while(expression);

The statement will be repeated,as long as the value of the expression is true.Notice the statement will be executed at least once,since the test for repetition does not occur until the end of the first pass through the loop.

Now let us rewrite the the program shown in section 4.2,which converts lowercase text to uppercase,so that the two while loops are replaced by do-while loops.

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

#include stdio.h
#include ctype.h

#define EOL '\n'

main()

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

/*read in the lowercase text*/

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

/*display the uppercase text*/

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

}

No comments:

Post a Comment