Working code of Spiral Pattern using 2D Array in Turbo C++.
//Working code of Spiral Pattern using 2D Array in Turbo C++.
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<stdio.h>
void main()
{
int a[10][10],i,j,n;
clrscr();
cout<<"Enter Number :";
cin>>n;
int count=1;
int round=ceil((double)n/2);
for(i=0;i<round;i++)
{
for(j=i;j<=n-i-1;j++)
{
a[i][j]=count++;
}
for(j=i+1;j<=n-i-1;j++)
{
a[j][n-i-1]=count++;
}
for(j=n-i-2;j>=i;j--)
{
a[n-i-1][j]=count++;
}
for(j=n-i-2;j>i;j--)
{
a[j][i]=count++;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==0||j==0||i==n-1||j==n-1)
textcolor(10);
cprintf("%3d ",a[i][j]);
textcolor(7);
}
cout<<endl;
}
getch();
}
/*
Output:
Enter Number :10
1 2 3 4 5 6 7 8 9 10
36 37 38 39 40 41 42 43 44 11
35 64 65 66 67 68 69 70 45 12
34 63 84 85 86 87 88 71 46 13
33 62 83 96 97 98 89 72 47 14
32 61 82 95 100 99 90 73 48 15
31 60 81 94 93 92 91 74 49 16
30 59 80 79 78 77 76 75 50 17
29 58 57 56 55 54 53 52 51 18
28 27 26 25 24 23 22 21 20 19
*/
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<stdio.h>
void main()
{
int a[10][10],i,j,n;
clrscr();
cout<<"Enter Number :";
cin>>n;
int count=1;
int round=ceil((double)n/2);
for(i=0;i<round;i++)
{
for(j=i;j<=n-i-1;j++)
{
a[i][j]=count++;
}
for(j=i+1;j<=n-i-1;j++)
{
a[j][n-i-1]=count++;
}
for(j=n-i-2;j>=i;j--)
{
a[n-i-1][j]=count++;
}
for(j=n-i-2;j>i;j--)
{
a[j][i]=count++;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==0||j==0||i==n-1||j==n-1)
textcolor(10);
cprintf("%3d ",a[i][j]);
textcolor(7);
}
cout<<endl;
}
getch();
}
/*
Output:
Enter Number :10
1 2 3 4 5 6 7 8 9 10
36 37 38 39 40 41 42 43 44 11
35 64 65 66 67 68 69 70 45 12
34 63 84 85 86 87 88 71 46 13
33 62 83 96 97 98 89 72 47 14
32 61 82 95 100 99 90 73 48 15
31 60 81 94 93 92 91 74 49 16
30 59 80 79 78 77 76 75 50 17
29 58 57 56 55 54 53 52 51 18
28 27 26 25 24 23 22 21 20 19
*/
No comments
Post your comments