im trying to create a 2D array using a random generator but the compiler keeps giving me compiling error no matter how i modify the calling function

#include <iostream>
#include <ctime>

using namespace std;

const int MAX = 4;

void constructArray (int a [][MAX], int);


int main()
{
	int a [MAX];
	
	srand (time (NULL));
	
	constructArray (a [][MAX], MAX);

	
	
}

void constructArray (int a [][], int size)
{
	for (int i = 0; i < size; i++)
		a [i][size] = rand () % 10;
}

As it is only 3 lines of code do you need a function?

const int MAXROW = 4;
const int MAXCOL = 10;

int main()
{
  int a [MAXROW][MAXCOL];
  for (int row = 0; row < MAXROW; row++)
    for (int col = 0; col < MAXCOL; col++)
      a[row][col] = rand () % 10;
}

And array cannot contain 2 empty dimensions in a function. You must fill in at least the left dimension.

oh i used a function coz the array would be part of a larger program....

so...if i wanna print the array on screen now...i added in a few more lines....but the compiler gives me an error msg at line 21....
whats wrong there? i filled up both dimensions of the array, why cant it work?

#include <iostream>
using namespace std;

const int MAXROW = 4;
const int MAXCOL = 10;



int main()
{
  srand(time(NULL));
  
  int a [MAXROW][MAXCOL];
  
  for (int row = 0; row < MAXROW; row++)
  {  
    for (int col = 0; col < MAXCOL; col++)
      {
             a[row][col] = rand () % 10;
      }
  cout << a[row][col] << "\t";
  cout << endl;
  }    
  

}

gives me an error msg at line 21....

You've declared 'col' inside the inner for loop. That means that when the loop is done, col is outside of scope.
To solve this problem you would have declare 'int col' in the same scope as where you use it. So right after this line : int a [MAXROW][MAXCOL]; for example. Just put a int col = 0; after it, and remove the 'int' delcaration from the for loop
:

#include <iostream>
#include <time.h>
using namespace std;

const int MAXROW = 4;
const int MAXCOL = 10;



int main()
{
	srand(time(NULL));

	int a [MAXROW][MAXCOL];
	int col=0 ,row =0;

	for (row = 0; row < MAXROW; row++)
	{ 
		for (col = 0; col < MAXCOL; col++)
		{
			a[row][col] = rand () % 10;
		}
		cout << a[row][col] << "\t";
		cout << endl;
	} 

        return 0;
}

Please note the return 0; at the end of the program.
I didn't check your logic, so the program may not give you the correct output.

Edited 6 Years Ago by Nick Evan: n/a

If you want to display the entire 'matrix' you might want to move line 23: cout << a[row][col] << "\t"; inside thee 'for'loop. (on line 21)

Edited 6 Years Ago by Nick Evan: n/a

This article has been dead for over six months. Start a new discussion instead.