0

I have a program, where I want to fill a matrix nxn with zeroes only in the main diagonal and with 1s everywhere else. However, I faced two major problems: 1) I do not know how to correctly pass the 2D array, and how to invoke the function. 2) If I write all the code in the main() method (without functions), the program compiles but does not work as expected - it fills the matrix with 1s everywhere.

I would like to ask how could I fix that problems?

#include <iostream>
#define MAX 100
using namespace std;
int a[MAX][MAX];
void fillMatrix(unsigned a[][MAX],unsigned n)
{
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {
            if(i==j)
            {
                a[i][j]=0;
            }
            a[i][j]=1;
        }
    }
}



int n;
int main()
{
    cin>>n;
    fillMatrix(a[][n], n);


//Print the matrix
    for(int i=0; i<n; i++)
    {

        for(int j=0; j<n; j++)
        {
            cout<<a[i][j]<<' ';
        }
        cout<<endl;
    }
    return 0;
}
A.Petrov
  • 33
  • 4

1 Answers1

1

However, I faced two major problems: 1) I do not know how to correctly pass the 2D array, and how to invoke the function.

In order to pass any array (1D, 2D or 3D) you need to use following call

fillMatrix(a, n);

If I write all the code in the main() method (without functions), the program >compiles but does not work as expected - it fills the matrix with 1s everywhere.

You are not using else after the if code block, which is overwriting 1 on 0.

       if(i==j)
        {
            a[i][j]=0;
        }
        else
        a[i][j]=1;

edit: removed some text because that was specific to C and question was asked for c++.

Nitin
  • 135
  • 9
  • 2
    The question has the tag `c++`. Besides, arrays in C (since standard C99) can have a variable size. – Xam Jan 27 '18 at 05:19