Tuesday 18 December 2012

To display the elements in a spiral way c++ program









Here middle element  is 1 and the numbers after 1 are displayed in spiral way

#include<iostream>
#include<iomanip>   // for setw(int)  space generating
using namespace std;
#include<conio.h>

int main()
{
int num,r,s=1,i,c,j,k,ord;

cout<<"Enter mid element of square matrix and get the elements in a spiral way  :";
cin>>num;
cout<<"enter odd order of square matrix";
cin>>ord;
int a[ord][ord];r=ord/2;c=ord/2;a[r][c]=num;   //r  row  c  column
for(i=1;i<=ord;i++)
{if(i%2==0)
           {for(j=0;j<s;j++) // i =even control left side
           a[r][--c]=++num;
           for(k=0;k<s;k++)
           a[--r][c]=++num;
           }
         
           else
           {for(j=0;j<s;j++)  //i =odd control right side
           a[r][++c]=++num;
           for(k=0;k<s;k++)
           a[++r][c]=++num;
           }
           s++;
}cout<<setw(ord);
for(r=0;r<ord;r++)
{  for(c=0;c<ord;c++)
  cout<<a[r][c]<<setw(ord);
  cout<<endl;
}
getch();
}

No comments:

Post a Comment