\(\begin{array}{ccccc}3&3&3&3&3\\3&2&2&2&3\\3&2&1&2&3\\3&2&2&2&3\\3&3&3&3&3\end{array}\)
Write a program that reads a number and displays the above pattern.
In order to solve this pattern, you need to subdivide it into 2 parts i.e. an upper part and a lower part. Again each part should be subdivided into 3 parts i.e. a left part (red), a middle part (green) and a right part (blue).
\(\begin{array}{ccccccc}{\color{green} 4}&{\color{green} 4}&{\color{green} 4}&{\color{green} 4}&{\color{green} 4}&{\color{green} 4}&{\color{green} 4}\\{\color{red} 4}&{\color{green} 3}&{\color{green} 3}&{\color{green} 3}&{\color{green} 3}&{\color{green} 3}&{\color{blue} 4}\\{\color{red} 4}&{\color{red} 3}&{\color{green} 2}&{\color{green} 2}&{\color{green} 2}&{\color{blue} 3}&{\color{blue} 4}\\{\color{red} 4}&{\color{red} 3}&{\color{red} 2}&{\color{green} 1}&{\color{blue} 2}&{\color{blue} 3}&{\color{blue} 4}\\&&&&&&\\{\color{red} 4}&{\color{red} 3}&{\color{red} 2}&{\color{green} 2}&{\color{blue} 2}&{\color{blue} 3}&{\color{blue} 4}\\{\color{red} 4}&{\color{red} 3}&{\color{green} 3}&{\color{green} 3}&{\color{green} 3}&{\color{blue} 3}&{\color{blue} 4}\\{\color{red} 4}&{\color{green} 4}&{\color{green} 4}&{\color{green} 4}&{\color{green} 4}&{\color{green} 4}&{\color{blue} 4}\end{array}\)
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
void main()
{
int N, i, j;
do{
printf("Enter N: ");
scanf("%d",&N);
}while(N<=0);
// for the pper half
for(i=N; i>=1; i--)
{
// left part
for(j=N; j>i; j--)
printf("%d", j);
// middle part
for(j=1; j<=(i*2-1); j++)
printf("%d", i);
// right part
for(j=i+1; j<=N; j++)
printf("%d", j);
printf("\n");
}
// for the lower half
for(i=1; i<N; i++)
{
// left part
for(j=N; j>i; j--)
printf("%d", j);
// middle part
for(j=1; j<=(i*2-1); j++)
printf("%d", i+1);
// right part
for(j=i+1; j<=N; j++)
printf("%d", j);
printf("\n");
}
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Implementation of a deque using a doubly-linked list