Submitted by tushar pramanick on Tue, 03/05/2013 - 19:42

Question and Answer

    Q How does a for loop work?

    A There are three expression fields in the for statement. The first field contains an initializer that is evaluated first and only once before the iteration. The second field keeps the conditional expression that must be tested before the statements controlled by the for statement are executed. If the conditional expression returns a nonzero value, which means the specified condition is met, one iteration of the for loop is carried out. After each iteration, the expression in the third field is evaluated, and then the expression in the second field is reevaluated. The process (that is, looping) is repeated until the conditional expression returns 0.

    Q What is the difference between the while and do-while statements?

    A The main difference is that in the while statement, the conditional expression is evaluated at the top of the loop, while in the do-while statement, the conditional expression is evaluated at the bottom of the loop. Therefore, the statements controlled by the do-while statement are executed at least once.

    Q Can the while statement end with a semicolon?

    A By definition, the while statement does not end with a semicolon. However, it's legal in C to put a semicolon right after the while statement like this: while(expression);, which means there is a null statement controlled by the while statement. Remember that the result will be quite different from what you expect if you accidentally put a semicolon at the end of the while statement.

    Q If two loops are nested together, which one must finish first, the inner loop or the outer loop?

    A The inner loop must finish first. Then the outer loop will start another iteration if the specified condition is still met.

Related Items

Adding More Expressions into for

Adding More Expressions into for

The C language allows you to put more expressions into the three expression fields in the for statement. Expressions in a single expression field are separated by commas.

The Null Statement

The Null Statement

Looping Under the for Statement

Looping Under the for Statement

The general form of the for statement is

for (expression1; expression2; expression3) {
   statement1;
   statement2;
   .
   .
   .
}

Using Nested Loops

Using Nested Loops

You can put a loop inside another one to make nested loops. The computer will run the inner loop first before it resumes the looping for the outer loop.

Listing 7.7 is an example of how nested loops work.

 

The do-while Loop

The do-while Loop

You may note that in the for and while statements, the expressions are set at the top of the loop. However, in this section, you're going to see another statement used for looping,