Number pattern program print in down up approach

Number pattern program print in down up approach
Logic:
- Get the row size from the user.
- The below steps are executed for (2*n)-1 times.
- Determine the starting position to store the count value.
- Then decrement row value and increment column value.
- At last, print the array to display patterns.
Explanation:
- a=>stores the pattern value, n=>number of rows, k=>determines the row, l=>determines the column and cnt=>value to store
- Let’s consider input n=4 and cnt=1
- By using n we can find how many times the loop going to execute which is (2*n)-1 times ie, 7 times
- Store the cnt=1 value into the array a into the position a[k][l] now k=0, m=0,l=0, and cnt=1 and m is used only for upper loop count to execute
- For the next row k=1, l=0, m=1 and cnt=2. Now inner loop executes for two times and then l increments and k value decrements now k=0 and l=1, cnt=3 value stores into the array
- This process continues for the upper half of the pattern and cnt=11
- Then moves to the lower half where we increment both row and column
- Now l=1, k=3, m=3, cnt=11, and the same thing going on loop executes for 3 times, and count store into the array
- Then l=2, k=3, m=3, cnt=14, and the same thing going on loop executes for 2 times, and count store into the array
- Then l=3, k=3, m=3, cnt=16, and the same thing going on loop executes for 1 time, and count store into the array
- And exits from the outer loop then prints the pattern
Program:
[code lang=”c”]
#include<stdio.h>
void main()
{
/* a->stores the pattern value
n->number of rows
k->determines the row
l->determines the column
cnt->value to store
*/
int a[10][10],n,i,j,k,cnt=1,l,m;
printf("Enter the number:");
scanf("%d",&n);
for(i=0;i<(2*n)-1;i++) //loops executes for (2*n)-1 times
{
k=i,m=i;
l=0;
if(i>=n) //applies only for lower half
{
l=(i+1)%n;
k=n-1;
m=n-1;
}
for(j=l;j<=m;j++)
{
a[k][j]=cnt++; //store the count into array
k–;
}
}
for(i=0;i<n;i++) //prints the pattern
{
for(j=0;j<n;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
}
[/code]