Number Patterns
Number pattern 38 in C
Write a C program to print the given number pattern series. How to print the given number pattern series using for loop in C programming. Logic to print the given number pattern in C program.
Example
Input
Input N: 5
Output
1 32 4543 567654 67898765
Required knowledge
Basic C programming, Loop
Logic to print the given number pattern
1 3 2 4 5 4 3 5 6 7 6 5 4 6 7 8 9 8 7 6 5
If at first the pattern seems confusing. Take your time and have a closer look to the pattern for a minute. You might find below things about the pattern.
1.It contains of total N rows (where N is the total number of rows to be printed).
2.To make things easier you can divide the pattern in two parts.
4 56 6781 32 543 7654 98765
3.Now, when you look to the first part of the pattern, you will find that it starts from 3rd row and goes till 5th row. Hence the inner loop formation to print this part will be something like for(j=3; j<=i; j++).
4.The second pattern is an odd pattern, whose first column starts with an odd number. I have already explained the logic to print this pattern in one of my previous post.
It contains total N rows and each row contains exactly i columns (where i is the current row number. Each column start with a value (i * 2) - 1. Hence the second inner loop formation for this part will be for(j=(i * 2)-1; j>=i; j--).
Lets, code down the logic.
Program to print the given pattern
/** * C program to print the given number pattern */ #include <stdio.h> int main() { int i, j, value, N; printf("Enter rows: "); scanf("%d", &N); for(i=1; i<=N; i++) { value = i + 1; // Prints the first part of pattern for(j=3; j<=i; j++) { printf("%d ", value); value++; } // Prints the second part of pattern for(j=(i*2)-1; j>=i; j--) { printf("%d ", j); } printf("\n"); } return 0; }
Output
Enter rows: 5
1 3 2 4 5 4 3 5 6 7 6 5 4 6 7 8 9 8 7 6 5