Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to print to print the following series. 1 2 2 3 3 3 4 4 4 4

C Code Example — Series Programs

ADVERTISEMENT

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

  1. Run an outer loop i from 1 to 4.
  2. Run an inner loop j from 1 to i.
  3. Inside the inner loop, print the value of i followed by a space.
  4. 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 i times, 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)
ADVERTISEMENT