1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Spiral Matrix

Discussion in 'C++' started by tqit, May 23, 2013.

  1. tqit

    tqit New Member

    Joined:
    May 23, 2013
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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 a moderator: May 23, 2013
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,285
    Likes Received:
    364
    Trophy Points:
    83
    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..
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    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[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[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 likes this.

Share This Page