Write a C program to print the given number pattern using loop. How to print the given number pattern of m rows and n columns using for loop in C programming. Logic to print the given number pattern using for loop in C program.
Required knowledge
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.
If you can notice, you can actually divide this in two parts to make things easier. Let me show.
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.
Program to print the given number pattern 1
/**
* C program to print number pattern
*/
#include <stdio.h>
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
Program to print the given number pattern 2
/**
* C program to print number pattern
*/
#include <stdio.h>
int main()
{
int N, i, j;
printf("Enter N: ");
scanf("%d", &N);
for(i=1; i<=N; i++)
{
// Print first part
for(j=(N-i +1); j>1; j--)
{
printf("%d", j);
}
// Print second part
for(j=1; j<=i; j++)
{
printf("%d", j);
}
printf("\n");
}
return 0;
}
Happy coding 😉
Recommended posts
- Number pattern programming exercises index.
- Star patterns programming exercises index.
- Loop programming exercises index.
- Recommended patterns –
12345 23451 34521 45321 54321
1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9
55555 54444 54333 54322 54321
12345 23455 34555 45555 55555
12345 12345 12345 12345 12345
12345 23456 34567 45678 56789
11111 22222 33333 44444 55555
11111 11111 11111 11111 11111
11111 22222 33333 44444 55555