Introduction
In this blog, we will be discussing a simple loop problem. Loops are just used to iterate a part of a statement for a given specific time. Instead of writing the same thing repetitively, we bring the loop into the picture.
Problem Statement
In this problem, we are given a number and we just need to print the multiplication table of the given number.
Sample Example
Say the number given to us is 5.
So the compiler should print output as:
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50
Now let us see how we did it, its approach, algorithm implementation, and complexities.
Approach
Our strategy will be simple and straightforward. First, we'll just declare a for loop so that we can multiply the given number 10 times to print the multiplication table. Then we need the multiplication operator(asterisk) to actually multiply the given number.
Algorithm
Step 1: Declare a number whose multiplication table has to be printed.
Step 2: Declare a for loop for repetitive multiplication.
Step 3: Display the multiplication table.
Implementation in C++
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter the given number :" << endl;
cin >> number;
//declaring for loop for repetitive multiplication
for (int i = 1; i <= 10; i++)
{
cout << number << " * " << i << " = " << number * i << endl;
}
}
Output
Enter the given number :
5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Let us analyze the time and space complexity of this approach.
Complexity analysis
Time complexity: O(N)
This approach will take O(N), where N is the total number of times the loop has to be executed. Here it is 10.
Space complexity: O(1)
In this approach, no extra space is required.
Also Read - C++ Interview Questions