Exercise:
Write a C++ program to create multiplication table.
Method 1: Compile a program to create multiplication tables for numbers up till 10.
Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Please insert a positive number: ";
cin >> num;
cout << "Table of " << num << " up to 10:" << endl;
for (int i = 1; i <= 10; ++i)
{
cout << num << " x " << i << " = " << num * i << endl;
}
return 0;
}
Click Here to View the Output:
Please insert a positive number: 12 Table of 12 up to 10: 12 x 1 = 12 12 x 2 = 24 12 x 3 = 36 12 x 4 = 48 12 x 5 = 60 12 x 6 = 72 12 x 7 = 84 12 x 8 = 96 12 x 9 = 108 12 x 10 = 120
Click Here to View the Explanation:
- The user is asked to enter a number
Please insert a positive number:
. - The compiler runs the number through a
for
loop and displays the table of the numbernum
entered by the user. - 1 integer
i
is declared equal to 1 before thefor
loop begins. It checks for the condition if the value ofi
is smaller than 10, it enters the loop and multipliesnum
byi
. - The value of
i
is incremented by 1 every time the number re-enters the loop. - The output is displayed on the screen.
Method 2: Compile a program to create multiplication tables up to a range entered by the user:
Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
int num, ran;
cout << "Please insert a positive number: ";
cin >> num;
cout << "Please specify your range: ";
cin >> ran;
cout << "table of "<< num << " up to " << ran << " is:"< <endl;
for (int i = 1; i <= ran; ++i)
cout << num << " * " << i << " = " << num * i << endl;
return 0;
}
Click Here to View the Output:
Please Insert a positive number: 9 Please specify your range: 14 table of 9 up to 14 is: 9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81 9 * 10 = 90 9 * 11 = 99 9 * 12 = 108 9 * 13 = 117 9 * 14 = 126
Click Here to View the Explanation:
- For method 2, the user is requested to enter the
num
and the rangeran
up to which the user wishes to see the table. - This method is very similar to method 1, except that the condition to enter the
for
loop has been changed. - The limit to enter the loop was changed from a restricted 10 to the number provided by the user.
- The output is displayed on the screen.