C program to print a pattern of right triangle using star
This C program is to print a pattern of right triangle using star(*).
*
* *
* * *
* * * *
* * * * *
Logic
We use a nested for loop which counts till the ith value and keeps printing a star till that val
Dry Run of the Program
Take input rows=3(where rows= no of rows)
1st iteration outer for loop
for(i=1;i<=row;i++) i.e for(i=1;1<=3;i++)
1st iteration inner for loop
for(j=1;j<=i;j++) i.e for(j=1;1<=1;j++)
printf(“* “) i.e output *
2nd iteration outer for loop
for(i=1;i<=row;i++) i.e for(i=2;2<=3;i++)
1st iteration inner for loop
for(j=1;j<=i;j++) i.e for(j=1;1<=2;j++)
printf(“* “) i.e output *
2nd iteration inner for loop
for(j=2;j<=i;j++) i.e for(j=2;2<=2;j++)
printf(“* “) i.e output * *
3rd iteration outer for loop
for(i=1;i<=row;i++) i.e for(i=3;3<=3;i++)
1st iteration inner for loop
for(j=1;j<=i;j++) i.e for(j=1;1<=3;j++)
printf(“* “) i.e output *
2nd iteration inner for loop
for(j=2;j<=i;j++) i.e for(j=2;2<=3;j++)
printf(“* “) i.e output * *
3rd iteration inner for loop
for(j=3;j<=i;j++) i.e for(j=3;3<=3;j++)
printf(“* “) i.e output * * *
Now, we will break out of the outer for loop as now i=4 which is greater than 3.
Final output will be :-
*
* *
* * *
Program
#include<stdio.h> void main() { int i,j,rows; printf("Enter the number of rows\n"); scanf("%d",&rows); printf("\n"); for(i=1;i<=rows;i++) { for(j=1;j<=i;j++) { printf("* "); } printf("\n"); } }