Simple Multiplication Table in C++

The board has its ebbs and flows when it comes to programming topics. One day it could be a flood of Java questions regarding an inventory system and the next it could be how to write to a file in C#. A recent question on the board has been popping up over the last couple days with regard to creating a multiplication table in C++. So lets talk a little bit about it and provide some code that you can use to understand and hammer out this question. Then we can go play Halo and melt someone’s face off…. so anyways sit back and get ready for another superb episode of the Programming Underground!

The idea behind the multiplication table is pretty simple. We have all been exposed to them in grade school mathematics. It is simply a matter of finding a numbered row and numbered column to find the value that represents those two numbers multiplied. Simple enough, but how do we get our program to do this?

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.

This assignment is typically assigned to beginners because it teaches many programming fundamentals. One is looping. How to repeat a series of steps over and over again given a range of values or until something is true/false. In our case we are looping from a start value to an end value and printing the range of values for that part of a multiplication table. Second it can help newbies understand how to print something formatted.

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…..

#include <iostream>
#include <iomanip>
using namespace std;

// This function prints the first and second rows
// That is the heading across the top
void printHeader(int start, int end) {

	// Print lead space and then numbers from start to end
	cout << setw(4) << " ";
	for (int firstrow = start; firstrow <= end; firstrow++) { 
		cout << setw(3) << firstrow << " ";
	}
	cout << endl;

	// Second line, lead space then proper number of dashes
	cout << setw(4) << " ";
	for (int secondrow = start; secondrow <= end; secondrow++) { 
		cout << "----";
	}
	cout << endl;
}

int main() {
	int start;
	int end;

	// Collect start and end of listing
	cout << "Enter a start index (integer): " << endl;
	cin >> start;

	cout << "Enter an end index (integer): " << endl;
	cin >> end;

	// Nested loop will loop through rows and for each
	// row we loop through columns
	for (int i = start; i <= end; i++) {
		// Executes once to print header
		if (i == start) {
			printHeader(start, end);
		}

		// Now loop through columns
		for (int j = start; j <= end; j++) {
			// Once per row create first column heading
			if (j == start) {
				cout << setw(3)<<  i << "|";
			}

			// Multiply row and column
			cout << setw(3) << (i * j) << " ";
		}

		// End row
		cout << endl;
	}

	return 0;
}

This program is a bit more complex than the standard nested loop, but simple enough to see what is going on. To help you out, just follow the in code comments.

We have added a little formatting in the way of using the setw function (which requires us to include the include) and tacked in a few spaces here in there to separate out the numbers into nice columns.

In addition to the main program function, we created a simple void function called printHeader() which does nothing more than print the column numbers (with the appropriate lead spaces) and a line of dashes.

The program begins by asking for a start index and an end index and then uses those values to loop through the range. To keep things simplistic in nature, I have opted out of providing error checking on if those two values entered are numbers and if the end index is after the start index in series. But for your assignments I would recommend you put in some kind of error checking. I will leave that part up to you. 😉

For our little test run of the program, we are going to create the standard 1 – 12 multiplication table that you may have seen in math books or on the wall of your classrooms (elementary classrooms that is). If we start the program and enter these two values, we will see an output similar to the image below…

Simple Multiplication Table

As you can see we have a table which goes from 1 to 12 across the top and 1 to 12 on the left hand side. If we pick a row and follow it over to the appropriate column, we would find out the multiplication value of the two numbers. For instance the 12th row and the 12th column is equal to saying 12 x 12 or 144.

If you are curious as to how I got the columns to line up so well, look up that setw function I mentioned earlier from . This function (and many others like it) manipulate the output stream. Here we are telling it to set a specific width of our output. setw(3) for instance states to use a width of 3 for each number even if the number is only 1 or 2 numbers long. In addition to this, I tack on a space after each number to separate the columns out. If I was to select an integer range that featured numbers with 4 digits in it, like 1000 – 1005, the setw would have to be adjusted to 4 digits otherwise the numbers would print but not be so nicely lined up. Again, look up the use of setw for more information.

One thing to take away from this is the idea of the nested for loops. If we take away all the nice formatting and boil it down the idea of …

for (int i = start; i <= end; i++) {
	 for (int j = start2; j <= end2; j++) {
		  // Here print i * j
	 }
	 cout << endl; // End row
}

… then you will find the whole assignment much easier to implement and understand. The trick will be to know what is your start and what is your end. As with all loops, a common mistake is an off by one error. That is an error where you either loop one too many times or one too few times. So keep an eye out for that.

Now that we have that hashed out and out of the way, melt those faces like a barbie doll on an open fire! We will talk again later. Thanks for reading! 🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 25 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.