Spiral Matrix

tqit's Avatar, Join Date: May 2013
Newbie Member
Hi guys.Although it may sound like a noob question ,how can i make a function that generates a spiral matrix but it MUST have this prototype void f(int *a,int m,int n).My program works fine but like i said i have no idea how to make it with that prototype.Here is my code
Code:
#include<stdio.h>
#include<iostream.h>
int a[10][10],n,m;
void f(int a[10][10],int m,int n)
		 {int i,j,p,q,k=0;
cout<<"m,n"<<endl;
cin>>m>>n;
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
    {cout<<"a["<<i<<"]["<<j<<"]=";
    cin>>a[i][j];
    }

p=m;
q=n;
i=j=1;

while(k<p*q)
{
    for(;j<=n&&k<p*q;j++)
    {
	cout<<a[i][j];
        k++;
    }
    j--;  
    i++;
    for(;i<=m && k<p*q;i++)
    {
        cout<<a[i][j];
        k++;
    }
    i--;
    j--;    
    for(;j>=i-m+1 && k<p*q;j--)
    {
        cout<<a[i][j];
        k++;
    }    
    j++;
    i--;
    for(;i>1 && k<p*q;i--)
    {
        cout<<a[i][j];
        k++;
    }
    if(k<p*q)
    {
        j++;
        i++;
        n--;
        m--;
    }
}
       }



main()
{
 f(a,m,n);
system("pause");
}

Last edited by shabbir; 23May2013 at 20:43.. Reason: Code blocks
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
You are anyway taking global variables and so it does not matter if you pass those variables as parameters or anything.

Move your variables in main and then pass your variables to that function..
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
A 2D array with dimensions [m][n] can be represented as a 1D array with dimension [m*n]. So that is probably what the tutor wants you to do.

So what you need to do is to work out how to convert references like a[i][j] to a[f(i,j)], where f() is some kind of function, perhaps an expression, that converts i and j into a unique reference into a one-dimensional array. If m=n=10 for example, then a[i][j] might become a[i*10+j], or a[i+10*j] depending which way you do the conversion (and on whether arr[x][y] is x rows of y columns or the other way round. I can never remember which it is).
shabbir like this