C Program to print to print the following series. 1 2 2 3 3 3 4 4 4 4
Objective
Write a C program to print the grouping series: 1 2 2 3 3 3 4 4 4 4.
Algorithm / Approach
- Run an outer loop
ifrom 1 to 4. - Run an inner loop
jfrom 1 toi. - Inside the inner loop, print the value of
ifollowed by a space. - Notice that we do NOT print a newline after the inner loop finishes.
main.c
#include<stdio.h>
int main( ) {
int i,j;
for(i=1; i<=4; i++) {
for(j=1; j<=i; j++) {
printf("%d ",i);
}
}
printf("\n");
return 0;
}
Expected Output
1 2 2 3 3 3 4 4 4 4
Explanation of the Program
- This program uses the standard logic for building a number pyramid, but it prints everything on a single straight line.
- Because the inner loop runs
itimes, the number 1 is printed once, the number 2 is printed twice, the number 3 is printed three times, and so on.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)