Pattern:
*
**
***
****
*****
Solution:
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d", &rows);
for(i=1; i<=rows; i++)
{
for(j=1; j<=i; j++)
{
printf("* ");
}
printf("\n");
}
return 0;
}
Explanation of how FOR loops are working internally:
i is for the number of Rows
j is for the number of Columns
We have declared “Rows” name variable for that value t is
taken from the user.
Suppose User Enters 4 that means
Rows=4;
Value of i | For loop i Condition i<=4 | increment i++ | value of j | For Loop j condition j<=i | increment j++ | Output |
---|---|---|---|---|---|---|
1 | 1<=4 (TRUE) | Incremented the value of i by 1 now i=2 | 1 | 1<=1 (TRUE) | Incremented the value of J by 1 now j=2 | * |
2 | 2<=1 (FALSE) | Comes out of j for loop and reset the value of j to 1 now j=1 | * | |||
2 | 2<=4 (TRUE) | Incremented the value of i by 1 now i=3 | 1 | 1<=2 (TRUE) | Incremented the value of J by 1 now j=2 | * |
* | ||||||
2 | 2<=2 (TRUE) | Incremented the value of J by 1 now j=3 | * | |||
** | ||||||
3 | 3<=2 (FALSE) | Comes out of j for loop and reset the value of j to 1 now j=1 | * | |||
** | ||||||
3 | 3<=4 (TRUE) | Incremented the value of i by 1 now i=4 | 1 | 1<=3 (TRUE) | Incremented the value of J by 1 now j=2 | * |
** | ||||||
* | ||||||
2 | 2<=3 (TRUE) | Incremented the value of J by 1 now j=3 | * | |||
** | ||||||
** | ||||||
3 | 3<=3 (TRUE) | Incremented the value of J by 1 now j=3 | * | |||
** | ||||||
*** | ||||||
4 | 4<=3 (FALSE) | Comes out of j for loop and reset the value of j to 1 now j=1 | * | |||
** | ||||||
*** | ||||||
4 | 4<=4 (TRUE) | Incremented the value of i by 1 now i=5 | 1 | 1<=4 (TRUE) | Incremented the value of J by 1 now j=2 | * |
** | ||||||
*** | ||||||
* | ||||||
2 | 2<=4 (TRUE) | Incremented the value of J by 1 now j=3 | * | |||
** | ||||||
*** | ||||||
** | ||||||
3 | 3<=4 (TRUE) | Incremented the value of J by 1 now j=4 | * | |||
** | ||||||
*** | ||||||
*** | ||||||
4 | 4<=4 (TRUE) | Incremented the value of J by 1 now j=5 | * | |||
** | ||||||
*** | ||||||
**** | ||||||
5 | 5<=4 (FALSE) | Comes out of j for loop and reset the value of j to 1 now j=1 | * | |||
** | ||||||
*** | ||||||
**** | ||||||
5 | 5<=4 (FALESE) | Comes out of i for loop |
Write a C Program to display pattern with execution Explanation for Beginners.
Reviewed by
on
September 04, 2019
Rating:
No comments: