Write a C program to Print Number Pattern 5 with example. For this, we are going to use For Loop and While Loop.
C program to Print Number Pattern 5 using For Loop
This program allows the user to enter the maximum number of rows he/she want to print as a right triangle. Next, compiler will print the required numbers pattern.
/* C program to Print Number Pattern 5 */ #include<stdio.h> int main() { int i, j, rows; printf(" \nPlease Enter the Number of Rows : "); scanf("%d", &rows); for(i = rows; i >= 1; i--) { for(j = i; j <= rows; j++) { printf("%d", j); } printf("\n"); } return 0; }
Let us see the Nested for loop
for(i = rows; i >= 1; i--) { for(j = i; j <= rows; j++) { printf("%d", j); } printf("\n"); }
Outer Loop – First Iteration
From the above C Programming screenshot you can observe that, The value of i is 7 and the condition (i <= 7) is True. So, it will enter into second for loop
Inner Loop – First Iteration
The j value is 1 and the condition (1 <= 1) is True. So, it will start executing the statements inside the loop.
printf("%d", j);
Next, we used the Increment Operator j++ to increment the J value by 1. This will happen until the condition inside the inner for loop fails. Next, iteration will start from beginning until both the Inner Loop and Outer loop conditions fails.
Program to Print Number Pattern 5 using while Loop
In this program we just replaced the For Loop with the While Loop. I suggest you to refer While Loop article to understand the logic.
/* C program to Print Number Pattern 5 */ #include<stdio.h> int main() { int i, j, rows; printf(" \nPlease Enter the Number of Rows : "); scanf("%d", &rows); i = rows; while(i >= 1) { j = i; while(j <= rows) { printf("%d", j); j++; } i--; printf("\n"); } return 0; }
Please Enter the Number of Rows : 9
9
89
789
6789
56789
456789
3456789
23456789
123456789