Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to print Pattern 9 1 3 3 5 5 5 7 7 7 7

C Code Example — Pattern Programs

ADVERTISEMENT

C Program to print Pattern 9 1 3 3 5 5 5 7 7 7 7

Objective

Write a C program to print a triangle where each row contains repeated odd numbers.

Algorithm / Approach

  1. Run an outer loop i from 1 to n.
  2. Run an inner loop j from 1 to i.
  3. Inside the inner loop, print 2 * i - 1 (or 2 * i + 1 depending on starting index).
  4. Print a newline.
main.c
#include<stdio.h>
int main( ) {
 int i, j,n;
 printf("Enter the Number of row : ");
 scanf("%d",&n);
 for(i=1; i<=n; i++) {
  for(j=1; j<=i; j++) {
   printf("%d",(2*i+1));
  }
 }
 return 0;
}

Expected Output

1
3 3
5 5 5
7 7 7 7

Explanation of the Program

  • Because the number is identical across the entire row (e.g., 3 3 3), we do not want to use the inner loop counter j or an independent counter k.
  • We must generate the number using the outer loop counter i, which remains constant for the duration of the entire row. The formula 2 * i - 1 guarantees an odd number based on the row index.

Complexity

Time Complexity O(n^2)
Space Complexity O(1)
ADVERTISEMENT