Simple Analogy
Imagine a staircase where each step becomes shorter than the previous one. Similarly, each new row prints one less number.
/**
* C program to print number pattern
* www.rummanansari.com
*/
#include <stdio.h>
int main()
{
int i, j, N;
printf("Enter N: ");
scanf("%d", &N);
for(i=1; i<=N; i++)
{
// Logic to print numbers
for(j=1; j<=N-i+1; j++)
{
printf("%d", j);
}
printf("\n");
}
return 0;
}
Enter N: 5
12345
1234
123
12
1
Learn how to use nested loops in C programming to generate a decreasing number pattern such as 12345, 1234, 123, 12, and 1.
In this program, the user enters a number N. The program prints numbers from 1 to N on the first line and decreases one number on each subsequent line. This example helps beginners understand nested loops and pattern generation techniques.
#include
int main()
{
int i, j, N;
printf("Enter N: ");
scanf("%d", &N);
for(i=1; i<=N; i++)
{
for(j=1; j<=N-i+1; j++)
{
printf("%d", j);
}
printf("\n");
}
return 0;
}
Enter N: 5
12345
1234
123
12
1
The user enters the number of rows to print.
The value entered by the user is stored in the variable N.
One iteration represents one row.
The outer loop runs from 1 to N and determines how many rows are displayed.
Creates the actual pattern.
The inner loop prints numbers from 1 to (N − i + 1). Therefore each row contains one less number than the previous row.
End of row processing.
The statement printf("\n"); moves the cursor to the next line after a row is completed.
Here:
| Row (i) | N - i + 1 | Numbers Printed |
|---|---|---|
| 1 | 5 | 12345 |
| 2 | 4 | 1234 |
| 3 | 3 | 123 |
| 4 | 2 | 12 |
| 5 | 1 | 1 |
Row 1 -> 12345
Row 2 -> 1234
Row 3 -> 123
Row 4 -> 12
Row 5 -> 1
Imagine a staircase where each step becomes shorter than the previous one. Similarly, each new row prints one less number.
| Metric | Complexity |
|---|---|
| Time Complexity | O(N²) |
| Space Complexity | O(1) |
Pattern programs help developers build strong loop logic. This program demonstrates how an inner loop can dynamically reduce the number of values printed in each row using the formula N - i + 1.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.
Sign in to save your progress and continue exactly where you left off.