Multiplication Table in C++
Print the multiplication table of any number from 1 to 10 in C++ using a for loop. Shows how the loop counter changes and why <= 10 differs from < 10.
1#include <iostream>2using namespace std;34int main() {5 int num;67 cout << "Enter a number: ";8 cin >> num;910 cout << "Multiplication table of " << num << ":" << endl;11 for (int i = 1; i <= 10; i++) {12 cout << num << " x " << i << " = " << (num * i) << endl;13 }1415 return 0;16}
Sample Output
Multiplication table of 5:
Heading printed once before the loop.
5 x 1 = 5
First iteration, i = 1.
5 x 10 = 50
Last iteration, i = 10.
In this one
- The three parts of a for loop: start, condition, update
- How the counter i is used inside the loop body
- Why <= 10 prints ten rows and < 10 prints nine
- How to change the table range
How it works
- 1
Read num (5).
- 2
Print the heading line.
- 3
i starts at 1; the condition i <= 10 is true.
- 4
Print num x i = num*i, then i++.
- 5
When i becomes 11 the condition fails and the loop ends.
Edge cases
Negative number
Enter -3.
The loop still runs ten times and prints -3 x 1 = -3 up to -30. Multiplication works the same for negatives.
Huge number
Enter 300000000.
300000000 × 10 = 3 billion, which overflows a 32-bit int. The last rows print wrong negative values. Use long long for big inputs.
What's going on
This C++ program prints a multiplication table for a number from 1 to 10.
int num;
cin >> num;
Sample: 5.
cout << "Multiplication table of " << num << ":" << endl;
Header line, then the rows.
for (int i = 1; i <= 10; i++)
<= 10, not < 10. < 10 prints 1 through 9 and looks almost right.
cout << num << " x " << i << " = " << (num * i) << endl;
Sample first and last rows: 5 x 1 = 5, 5 x 10 = 50.
Letters in cin leave num junk and you get a table of garbage. Check the stream if you're being nice.
Want 1 to 12? Change 10 in the loop. The rest stays.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
How many rows does for (int i = 1; i < 10; i++) print?
Pick an answer to check it.
Question 2
What is the value of i right after the loop ends?
Pick an answer to check it.
Questions people ask
How do I print up to 20?
Change the condition to i <= 20.
Can I use a while loop instead?
Yes. int i = 1; while (i <= 10) { ...; i++; } does the same job. for just keeps the three parts on one line.
Why is (num * i) in parentheses?
It is not required here, but it makes clear that the product is printed as one value.