C program to display multiplication table

In this example, you will learn how to print the table of a number given by the user. To understand this example you should have the knowledge of –

  • Operators in C.
  • Loops.

Program Using ‘while’ loop

#include <stdio.h>
int main()
{
    int num, i = 1, res;
    printf("Enter a number: ");
    scanf("%d", &num);

    while(i <= 10)
    {
        res = num * i;
        printf("%d * %d = %d \n", num, i, res);
        i++;
    }

    return 0;
}

Output

Enter a number: 12

12 * 1 = 12

12 * 2 = 24

12 * 3 = 36

12 * 4 = 48

12 * 5 = 60

12 * 6 = 72

12 * 7 = 84

12 * 8 = 96

12 * 9 = 108

12 * 10 = 120

Program Using ‘for’ loop

#include <stdio.h>
int main()
{
    int num, i, res;
    printf("Enter a number: ");
    scanf("%d", &num);

    for(i = 1; i <= 10; i++)
    {
        res = num * i;
        printf("%d * %d = %d \n", num, i, res);
    }

    return 0;
}

Output

Enter a number: 10

10 * 1 = 10

10 * 2 = 20

10 * 3 = 30

10 * 4 = 40

10 * 5 = 50

10 * 6 = 60

10 * 7 = 70

10 * 8 = 80

10 * 9 = 90

10 * 10 = 100

Explanation:

  • The first thing we are doing is storing the number given by the user inside the variable named num.
  • Next, we are running a loop that runs 10 times starting from 1 and ending at 10. The counter of the loop is represented by the variables ‘i’. The value of ‘i’ increments by 1 with every iteration. What this means is the value of i is 1 in the first iteration, 2 in the second iteration, 3 in the third iteration and so on.
  • Inside the loop, we are calculating the multiplication of num and the current value ‘i’ and storing it inside the variable ‘res’. Immediately after this, we are printing the current value of res.
  • So, in the first iteration of the loop, i = 1, num = 10(if the user enters 10). Therefore res = 1 * 10 i.e., 10
    In the second iteration of the loop, i = 2, num = 10. Therefore res = 2 * 10 i.e., 20
  • This process will continue till the value of ‘i’ becomes 10.
  • When the value of i is incremented to 11, the condition inside the loop becomes false and the program stops.