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

The while Loop

The while Loop

The while statement is also used for looping. Unlike the situation with the for statement, there is only one expression field in the while statement.

The general form of the while statement is

while (expression) {

Exercises : Answer the following Question

To help you solidify your understanding of this hour's lesson, you are encouraged to try to answer the quiz questions and finish the exercises provided in the Workshop before you move to the next lesson.

 

Working with the Cast Operator

Playing with the Cast Operator

In C, you can convert one data type to a different one by prefixing the cast operator to the operand.

The general form of the cast operator is

(data-type)x

Question and Answer

Question and Answer

    Q What is the difference between the pre-increment operator and the post-increment operator?

Using the Precision Specifier

Using the Precision Specifier