The for statement is the third and perhaps the most commonly used looping statement in C.This statement includes an expression that specifies an initial value for an index,another expression that determines whether or not the loop is to be continued,a third expression that allows the index to be modified at the end of each pass.
The general form of the for statement is
for(expression1;expresion2;expression3) statement
while expression1 is used to initialize some parameter(called an index) that controls the looping action,expresion2 represents a condition that must be true for the loop to continue execution,and expression3 is used to alter the value of the parameter initially assigned by expression1.
When the for statement is executed,expresion2 is evaluated and tested at the beginning of each pass through the loop,expression3 is evaluated at the end of each pass.Thus the for statement is equivalent to
expression1;
while(expresion2){
statement
expression3;
}
The looping action will continue as long as the value of expresion2 is not zero,that is as long as the logical condition represented by expresion2 is true.
Now let us rewrite the the program shown in section 4.2 and 4.3,which converts lowercase text to uppercase.Now, however, we make use of a for loop rather than while loop or do-while loop.
/*convert a lie of lowercase text to uppercase*/
#include stdio.h
#include ctype.h
#define EOL '\n'
main()
{
char letter[80];
int fla,count;
/*read in the lowercase text*/
for(count=0;(letter[count]=getchar())!=EOL;++count);
fla=count;
/*display the uppercase text*/
for(count=0;count < flag ;++count)
putchar(toupper(letter[count]));
}
comparing this program with the corresponding programs given in section 4.2 and 4.3 we see that loops can be written more concisely using the for statement than with while or do-while statements.
Sunday, December 13, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment