Program to print the given number pattern
12345
21234
32123
43212
54321
C Programming Language / Loop control in C Language
4609Program:
/** * C program to print number pattern */ #include int main() { int N, i, j; printf("Enter N: "); scanf("%d", &N); for(i=1; i<=N; i++) { // Print first part for(j=i; j>1; j--) { printf("%d", j); } // Print second part for(j=1; j<= (N-i +1); j++) { printf("%d", j); } printf("\n"); } return 0; }
Output:
Enter N: 5 12345 21234 32123 43212 54321
Explanation:
Required knowledge
Basic C programming, Loop
Logic to print the given number pattern
Before learning the logic of this number pattern, you first must be acquainted with some basic number patterns.
Now, once you are acquainted with some basic logic to print number pattern. If you look to both the patterns you will find both similar to each other. Hence, if you get the logic of one you can easily print the second one. Now lets get into first pattern, take a minute and have a close eye to the below pattern.
12345 21234 32123 43212 54321
If you can notice, you can actually divide this in two parts to make things easier. Let me show.
----- 2---- 32--- 432-- 5432-
12345 -1234 --123 ---12 ----1
Now you can find that printing these patterns separately is relatively easier than the whole. Below is the logic to print this pattern as a whole.
- To iterate through the rows, run an outer loop from 1 to N.
- To print the first part of the pattern, run an inner loop from current_row to 1. Inside this loop print the current column number.
- To print the second part of the pattern, run another inner loop from 1 to N-i + 1. Inside this loop print the value of current column number.
And you are done. Lets implement this on code.
Note: I won't be explaining the logic of second pattern as both are similar in-fact second pattern is reverse of first.
This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.