Example:
Input N: 5
Output:
Required knowledge
Basic C programming, LoopLogic to print the given pattern
When you look to the pattern, it might look similar to the odd number pattern. Logic to the pattern would be very simple if you know how to print odd number pattern.Now, lets have a quick look on to the pattern. The following observations can be made about the pattern.
- It consists of N rows (where N is the total number of rows to be printed).
- To make things little easier you can internally divide the pattern in two parts.
- The first part is completely odd number pattern and the loop structure to print the given pattern is for(j=1; j<=(i*2) - 1; j++).
- The second part is also an odd pattern in decreasing order. The loop structure to print the second part will be for(j=(i-1)*2-1; j>=1; j--).
Program to print the given pattern
/** * C program to print the given number pattern */ #include <stdio.h> int main() { int i, j, N; printf("Enter rows: "); scanf("%d", &N); for(i=1; i<=N; i++) { // Prints the first part of pattern for(j=1; j<=(i*2)-1; j+=2) { printf("%d", j); } // Prints the second part of pattern for(j=(i-1)*2-1; j>=1; j-=2) { printf("%d", j); } printf("\n"); } return 0; }
Output
Enter rows: 5
1
131
13531
1357531
135797531
1
131
13531
1357531
135797531
Screenshot
Now, once you got the logic to print this pattern you can easily print the second pattern. You just need to add extra spaces at the beginning.
Program to print the above pattern
/** * C program to print the given number pattern */ #include <stdio.h> int main() { int i, j, N; printf("Enter rows: "); scanf("%d", &N); for(i=1; i<=N; i++) { // Prints space for(j=i; j<N; j++) { printf(" "); } // Prints first part of the pattern for(j=1; j<=(i*2)-1; j+=2) { printf("%d", j); } // Prints second part of the pattern for(j=(i-1)*2-1; j>=1; j-=2) { printf("%d", j); } printf("\n"); } scanf("%d", &i); return 0; }
Screenshot
Happy coding ;)