Multiplication table till N rows where every Kth row is table of K upto Kth term
Last Updated :
08 Dec, 2022
Given a number N, the task is to print N rows where every Kth row consists of the multiplication table of K up to Kth term.
Examples:
Input: N = 3
Output:
1
2 4
3 6 9
Explanation:
In the above series, in every Kth row, multiplication table of K upto K terms is printed.
Input: N = 5
Output:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
Approach: The idea is to use two for loops to print the multiplication table. The outer loop in ‘i’ serves as the value of ‘K’ and the inner loop in ‘j’ serves as the terms of the multiplication table of every ‘i’. Each term in the table of ‘i’ can be obtained with the formula ‘i * j’.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void printMultiples( int N)
{
for ( int i = 1; i <= N; i++)
{
for ( int j = 1; j <= i; j++)
{
cout << (i * j) << " " ;
}
cout << endl;
}
}
int main()
{
int N = 5;
printMultiples(N);
return 0;
}
|
Java
class GFG {
public static void printMultiples( int N)
{
for ( int i = 1 ; i <= N; i++) {
for ( int j = 1 ; j <= i; j++) {
System.out.print((i * j) + " " );
}
System.out.println();
}
}
public static void main(String args[])
{
int N = 5 ;
printMultiples(N);
}
}
|
Python3
def prMultiples(N):
for i in range ( 1 , N + 1 ):
for j in range ( 1 , i + 1 ):
print ((i * j), end = " " )
print ()
if __name__ = = '__main__' :
N = 5
prMultiples(N)
|
C#
using System;
class GFG
{
public static void printMultiples( int N)
{
for ( int i = 1; i <= N; i++) {
for ( int j = 1; j <= i; j++) {
Console.Write((i * j) + " " );
}
Console.WriteLine();
}
}
public static void Main(String []args)
{
int N = 5;
printMultiples(N);
}
}
|
Javascript
<script>
function printMultiples( N)
{
for (let i = 1; i <= N; i++)
{
for (let j = 1; j <= i; j++)
{
document.write((i * j) + " " );
}
document.write( "<br/>" );
}
}
let N = 5;
printMultiples(N);
</script>
|
Output:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
Time Complexity: O(N2), here there are two loops with one running from 1 to N and another from 1 to i which means it is also running N times so it is a N*N complexity
Auxiliary Space: O(1), no extra array is being used so the space required is constant
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...