Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Spiral Matrix (http://www.go4expert.com/forums/spiral-matrix-t29674/)

tqit 23May2013 20:06

Spiral Matrix
 
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");
}


shabbir 23May2013 21:16

Re: spiral matrix
 
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 25May2013 19:54

Re: Spiral Matrix
 
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).


All times are GMT +5.5. The time now is 07:09.