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
- Run an outer loop
ifrom 1 ton. - Run an inner loop
jfrom 1 toi. - Inside the inner loop, print
2 * i - 1(or2 * i + 1depending on starting index). - 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
jor an independent counterk. - We must generate the number using the outer loop counter
i, which remains constant for the duration of the entire row. The formula2 * i - 1guarantees an odd number based on the row index.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)