Subscribe to Martyr2's Programming Underground        RSS Feed
-----

Simple Multiplication Table in C++

Icon 2 Comments
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. <Said_under_breath>Then we can go play Halo and melt someone's face off</Said_under_breath>.... so anyways sit back and get ready for another superb episode of the Programming Underground!

<Master Chief sings the blues theme song, but then it is interrupted by laser fire>

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

Posted Image

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 <iomanip>. 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! :)

If you want more blog entries like this, check out the official blog over on The Coders Lexicon. There you will find more code, more guides and more resources for programmers of all skill levels!

2 Comments On This Entry

Page 1 of 1

wartech Icon

23 March 2009 - 10:24 AM
Nice. Thanks for putting this together.
0

Martyr2 Icon

27 March 2009 - 09:02 PM
Glad this helped someone. I am hoping it will help many more. :)
0
Page 1 of 1

August 2014

S M T W T F S
     12
3456789
10111213141516
1718192021 22 23
24252627282930
31