
Introduction
The pattern codes serve as crucial interview questions in many companies to date. Pyramid patterns are one of those important questions. In this tutorial, we will discuss the concept of C programming language using which we will print half pyramid number patterns. We will take user input through the scanf( ) statement and print the pattern accordingly.
Pattern
For Number of Rows = 5, the pattern is as follows
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Approach
From the above pattern, it is clear, in the first row, we print 1 once, for the 2nd row, we print 2 twice, for the 3rd row, we print 3 thrice and so on. We can achieve the following pattern using nested loops. One loop to maintain the row number and the second loop to print the number multiple times according to the condition.
Code using For Loop
#include<stdio.h>
void main(){
int n=6,i,j;
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
printf("%d ",i);
}
printf("\n");
}
}
Output
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
Code using While Loop
#include<stdio.h>
void main(){
int n=5,i,j;
i=1;
while(i<=n){
j=1;
while(j<=i){
printf("%d ",i);
j++;
}
printf("\n");
i++;
}
}
Output
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Complexity Analysis
Time Complexity: O(N2)
Space Complexity: O(1)