Recursive Program to print multiplication table of a number
Given a number N, the task is to print its multiplication table using recursion.
Examples
Input: N = 5
Output:
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
Input: N = 8
Output:
8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80
Recursive approach to print multiplication table of a number
Approach:
- Get the number for which multiplication table is to print.
- Recursively iterate from value 1 to 10:
- Base case: If the value called recursively is greater than 10, exit from the function.
if(i > N)
return ;
- Recursive call: If the base case is not met, then print its multiplication table for that value and then call the function for next iteration.
print("N*i = ", N*i)
recursive_function(N, i+1);
- Return statement: At each recursive call(except the base case), return the recursive function for next iteration.
return recursive_function(N, i+1);
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void mul_table( int N, int i)
{
if (i > 10)
return ;
cout << N << " * " << i
<< " = " << N * i
<< endl;
return mul_table(N, i + 1);
}
int main()
{
int N = 8;
mul_table(N, 1);
return 0;
}
|
Java
class GFG {
static void mul_table( int N, int i)
{
if (i > 10 )
return ;
System.out.println(N + " * " + i + " = " + N * i);
mul_table(N, i + 1 );
}
public static void main (String[] args)
{
int N = 8 ;
mul_table(N, 1 );
}
}
|
Python3
def mul_table(N, i):
if (i > 10 ):
return
print (N, "*" ,i, "=" ,N * i)
return mul_table(N, i + 1 )
N = 8
mul_table(N, 1 )
|
C#
using System;
class GFG{
static void mul_table( int N, int i)
{
if (i > 10)
return ;
Console.WriteLine(N + " * " + i + " = " + N * i);
mul_table(N, i + 1);
}
public static void Main()
{
int N = 8;
mul_table(N, 1);
}
}
|
Javascript
<script>
function mul_table(N, i)
{
if (i > 10)
return ;
document.write(N + " * " + i
+ " = " + N * i
+ "<br>" );
return mul_table(N, i + 1);
}
var N = 8;
mul_table(N, 1);
</script>
|
Output:
8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80
Time Complexity: O(1)
Auxiliary Space: O(N) where n is recursion stack space.
Last Updated :
28 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...