C++ Program to Generate Multiplication Table


In this tutorial we make a program to generate the multiplication table of a number (entered by the user) using for loop.


 

Well, printing the table is as simple as using a nested for loop structure. That is one loop is inside the other. While the “outer loop” loops through the number of rows the “inner loop” loops through the columns. Inside this inner loop we find out the row number we are on and the column number we are on then multiply them together. We then move onto the next column. When the columns are exhausted, we go to the next row and then loop through all the columns again.

So the code below collects these two numbers and uses them to construct our table. Since the number of rows and the columns are going to be the same (the table is thus going to be a square) we can use the start and end values in both the outer and inner loops. If we wanted to make a table that was more of a rectangle instead of a square, we would have to adjust the start and end values for the inner loop compared to the outer loop.

To make the table a little more readable, we are also going to take some extra effort to print the row number and the column number so that someone looking at our program’s result can easily look up multiplication values. Lets take a look at the code and see how it works…..

Example 1: Display Multiplication table up to 10

#include <iostream>
using namespace std;

int main()
{
    int n;

    cout << "Enter a positive integer: ";
    cin >> n;

    for (int i = 1; i <= 10; ++i) {
        cout << n << " * " << i << " = " << n * i << endl;
    }
    
    return 0;
}

 

Output

Enter an integer: 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

 

This program above computes the multiplication table up to 10 only.

 

Example 2: Display multiplication table up to a given range

#include <iostream>
using namespace std;

int main()
{
    int n, range;

    cout << "Enter an integer: ";
    cin >> n;

    cout << "Enter range: ";
    cin >> range;
    
    for (int i = 1; i <= range; ++i) {
        cout << n << " * " << i << " = " << n * i << endl;
    }
    
    return 0;
}

 

Output

Enter an integer: 8
Enter range: 12
8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80
8 * 11 = 88
8 * 12 = 96

 

Leave a Comment