Multiplication Table Generator in C++
Learn how to use loops to automate repetitive tasks by creating a program that generates a complete multiplication table for any number provided by the user.
Logic and Iteration
The for Loop
A for loop is ideal for this task as we know exactly how many times the code should run (usually from 1 to 10).
Dynamic Output
By combining the user's input with the loop counter, we can display a formatted table: number * i = result.
Key Concepts Learned:
- Iteration: Controlling program flow with
forloops. - Arithmetic: Performing calculations inside a loop.
- Formatting: Organizing
coutfor readable output.
Course:
Introduction to C++
Step-by-Step Objective
- Declare an integer variable to store the user's number.
- Use
cinto read the number from the keyboard. - Implement a
forloop that iterates from 1 to 10. - Calculate and display the result of each multiplication in each row.
C++ Solution
multiplication_table.cpp
C++ Beginners
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number to generate its table: ";
cin >> num;
cout << "Multiplication Table of " << num << ":" << endl;
// Loop from 1 to 10
for (int i = 1; i <= 10; i++) {
cout << num << " x " << i << " = " << num * i << endl;
}
return 0;
}
Console Output:
Enter a number to generate its table: 5
Multiplication Table of 5:
5 x 1 = 5
5 x 2 = 10
...
5 x 10 = 50
Control Flow & Loops