#include<stdio.h>
int n,i,j,k=1,l,mid;
int a[20][20];
printf("Enter number:\n");
scanf("%d",&n); /*the input element n is the Table size*/
mid=n/2;
for(l=0;l<mid+1;l++) /*this loop repeat the below loops until the last element of the table*/
{
for(i=l,j=l;j<n-l;j++) /*this loop controls elements which are in ascending order from left to right*/
{
a[i][j]=k;
k++;
}
for(j=n-l-1,i=1+l;i<n-l;i++)
{
a[i][j]=k; /*this loop controls elements which are in ascending order from top to bottom*/
k++;
}
for(i=n-l-1,j=n-2-l;j>=0+l;j--)
{
a[i][j]=k; /*this loop controls elements which are in ascending order from right to left*/
k++;
}
for(j=l,i=n-l-2;i>l;i--)
{
a[i][j]=k; /*this loop controls elements which are in ascending order from bottom to top*/
k++;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d",a[i][j]);
}
printf("\n");
}
}
Friends lets try this program in java,
main()
{int n,i,j,k=1,l,mid;
int a[20][20];
printf("Enter number:\n");
scanf("%d",&n); /*the input element n is the Table size*/
mid=n/2;
for(l=0;l<mid+1;l++) /*this loop repeat the below loops until the last element of the table*/
{
for(i=l,j=l;j<n-l;j++) /*this loop controls elements which are in ascending order from left to right*/
{
a[i][j]=k;
k++;
}
for(j=n-l-1,i=1+l;i<n-l;i++)
{
a[i][j]=k; /*this loop controls elements which are in ascending order from top to bottom*/
k++;
}
for(i=n-l-1,j=n-2-l;j>=0+l;j--)
{
a[i][j]=k; /*this loop controls elements which are in ascending order from right to left*/
k++;
}
for(j=l,i=n-l-2;i>l;i--)
{
a[i][j]=k; /*this loop controls elements which are in ascending order from bottom to top*/
k++;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d",a[i][j]);
}
printf("\n");
}
}
0 comments:
Post a Comment