Difference Between for
and while loops
for | while |
---|---|
Syntax of
for loop:for(initialization; condition; iteration)
The initialization is an assignment statement that is used to set the loop control variable. The condition is a relational expression that determines when the loop exits. The incrementdefines how the loop control variable changes each time the loop is repeated. The body of loop can either be empty or a single statement or a block of statements.
The
for(initialization; condition; iteration)
is equivalent to
initialization; |
Syntax of
while loop:while(condition)
The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line of code immediately following the loop.
|
Pragmatic use of
for loop: the for is preferable when there is a simple initialization and increment; since it keeps the loop control statements close together and visible at the top of the loop. This is most obvious infor (i = 0; i < n; i++) { which is most often seen while processing array elements. |
Pragmatic use of
while loop: on the other hand while is preferable when the initialization is not just a simple assignment operation and so like increment. For example, in while ((c = getchar()) == ' ' || c == '\n' || c = '\t'); there is no initialization or re-initialization, so the while is most natural. |
No comments:
Post a Comment