Algorithm
From the pattern, we can observe that row zero has 1 element, row one has 3 elements, row two has 5 elements, and so on. Therefore, the nth row will have 2n+1 elements. Thus np is incremented by 2 in each iteration.
Therefore, a loop is needed to run from 0 to N to execute the code for N rows to implement the code.
For each row, first, the required number of spaces are printed within a for loop that runs from N-1 to row+1 for each iteration.
Then, the required number of numbers is printed within a for loop that runs from 0 to np for each row. The digit to be printed is given by np-row for that row in each iteration.
Code
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int N, row, space, number;
int np=1;
cin>>N;
for(row=0; row<N;row++)
{
for(space=N-1; space>row; space--) //prints the required number of spaces
{
cout<<" ";
}
for(number=0; number<np; number++) //prints the required number of digits
{
cout<<np-row;
}
np=np+2; //np is incremented by 2 in every iteration
cout<<"\n"; //newline
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
JAVA
import java.util.Scanner;
import java.util.*;
import java.lang.*;
import java.io.*;
class P31
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner cs=new Scanner(System.in);
int N, row, space, number;
int np=1;
N=cs.nextInt();
for(row=0; row<N;row++)
{
for(space=N-1; space>row; space--) //prints the required number of spaces
{System.out.print(" ");}
for(number=0; number<np; number++) //prints the required number of digits
{System.out.print(np-row);}
np+=2;
System.out.println();
}
cs.close();
}
}
Python
N = int(input())
np = 1
for row in range(0,N):
# decrements by -1 in each iteration
for space in range(N-1,row,-1):
print(" ", end="")
for number in range(0, np):
print(np-row,end="")
np+=2
print("\r")
Frequently Asked Questions
What is the time complexity of the above code?
The time complexity for the above code is O(n2) as it contains a for loop within a for loop.
What is the space complexity of the above code?
The space complexity of the above code is O(1) as it does not require any extra space.
Can the code be optimized further?
No, as we require at least two loops, one for printing the required number of digits and another for changing the row.
Conclusion
This article extensively discussed the Full Pyramid Pattern problem and the algorithm to solve it in the time complexity of O(N2) and space complexity of O(N). We hope that this blog has helped you enhance your knowledge regarding using nested for loops. You can check out more problems on Coding_Ninjas_Problems, CodingNinjas_TestSeries, and CodingNinjas_Puzzles.
If you would like to learn more, check out our articles on Code studio. Do upvote our blog to help other ninjas grow.
“Happy Coding!”