Course Content
Programming in C
About Lesson

Another way to write the program to print multiplication table discussed in previous section is by using the “for” statement, instead of the “while” statement.

#include <stdio.h>

main()
{
    int num, times, prod;
    for (num = 1; num <= 10; num++) {
        printf("Table of %d\n", num);
        for (times = 1; times <= 10; times++) {
            prod = num * times;
            printf("%2d x %2d = %3d\n", num, times, prod);
        }   
    }   
}

This produces the same output, but certainly looks different.
The for statement is a loop, a generalisation of the while statement. Within the parenthesis of a for statement, there are three parts, separated by semicolons. The first part, the initialisation

num = 1

is done once, before the loop is entered. The second part is the condition that controls the loop:

num <= 10

The condition is evaluated; if it is true, the body of the loop is executed. Then we have the increment step

num++

which gets executed at the end of the loop and then the condition is re-evaluated and the process repeats itself until the conditional check fails.
The initialisation, condition and increment can be any expressions.
The choice between while and for is arbitrary, based on which seems clearer. The for statement is usually appropriate for loops in which the initialisation and increment are single statements and logically related, since it is more compact than while and it keeps the loop control statements together in one place.

Scroll to Top