Example:
Input N: 5
Output:
Required knowledge
Basic C programming, LoopLogic to print number pattern 1
The above number pattern is a result of combination of two patterns together. Where the two parts individually look asThe above two patterns are explained in one of my previous number pattern post. Please go through the link to get the detailed explanation about these two patterns individually as combination of these two yields the final pattern.
For getting the final resultant pattern we need two separate loop that will print the first and second half of the pattern individually. For print the first upper half of the pattern here goes the logic.
- It consists of N rows (where N is the total number of rows to be printed). Hence the loop formation to iterate through rows will be for(i=1; i<=N; i++).
- Each row contains exactly i * 2 - 1 columns (where i is the current row number). Loop formation to iterate through each column will be for(j=1; j<=(i * 2 - 1); j++). For each column the current value of j is printed.
- The second half pattern consists of N - 1 rows. Since the pattern goes in descending order hence the loop formation to iterate through rows will also go in descending order for(i=N-1; i>=1; i--).
- Here each row exactly contains i * 2 - 1 columns. Hence, the loop formation for iterating over columns is for(j=1; j<=(i * 2 - 1); j++). Inside the inner loop print the value of j.
Program to print number pattern 1
/** * C program to print the given number pattern */ #include <stdio.h> int main() { int i, j, N; printf("Enter N: "); scanf("%d", &N); // Iterate through upper half triangle of the pattern for(i=1; i<=N; i++) { for(j=1; j<=(i * 2 - 1); j++) { printf("%d", j); } printf("\n"); } // Iterate through lower half triangle of the pattern for(i=N-1; i>=1; i--) { for(j=1; j<=(i * 2 - 1); j++) { printf("%d", j); } printf("\n"); } return 0; }
Output
Enter N: 5
1
123
12345
1234567
123456789
1234567
12345
123
1
1
123
12345
1234567
123456789
1234567
12345
123
1
Screenshot 1
Logic to print the number pattern 2
Once you printed the above pattern you can easily print the second number pattern. It is exactly similar to the first pattern we just printed. The only thing we need to add here is the trailing spaces. To print trailing spaces you need the following loop formation for(j=(i * 2); j<(N * 2); j++).Program to print the given number pattern 1
/** * C program to print the given number pattern */ #include <stdio.h> int main() { int i, j, N; printf("Enter N: "); scanf("%d", &N); // Iterate through upper half triangle of the pattern for(i=1; i<=N; i++) { // Print trailing spaces for(j=(i * 2); j<(N * 2); j++) { printf(" "); } for(j=1; j<=(i * 2 - 1); j++) { printf("%d", j); } printf("\n"); } // Iterate through lower half triangle of the pattern for(i=N-1; i>=1; i--) { // Print trailing spaces for(j=(i * 2); j<(N * 2); j++) { printf(" "); } for(j=1; j<=(i * 2 - 1); j++) { printf("%d", j); } printf("\n"); } return 0; }
Screenshot
Happy coding ;)