C Program to print Pattern 1 * * * * * * * * * * * * * * *
Objective
Write a C program to print a left-aligned right triangle of stars.
Algorithm / Approach
- Use two nested loops: an outer loop for rows (
i) and an inner loop for columns (j). - Run the outer loop from
i = 1to5. - Run the inner loop from
j = 1toi. - Inside the inner loop, print a star
*. - After the inner loop finishes, print a newline
\nto move to the next row.
main.c
#include<stdio.h>
int main( ) {
int i ,j;
for(i=1;i<=5;i++) {
for(j=1;j<=i;j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Expected Output
* * * * * * * * * * * * * * *
Explanation of the Program
- Pattern programs are the best way to understand Nested Loops.
- The outer loop controls how many rows the pattern will have. The inner loop controls what is printed on each individual row.
- Because the inner loop condition is
j <= i, the 1st row prints 1 star, the 2nd row prints 2 stars, and so on.
Complexity
Time Complexity
O(n^2) - Where n is the number of rows.
Space Complexity
O(1)