Making an 3x3 array with random numbers

I wrote the code for 3x3 array to get random numbers as a its elements but, I am
getting all row elements same. can anybody tell me what is wrong with this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  
#include <iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

int main()
{
    srand((int)time(0));
    int i=0;
    int x=0,y=0;
    int matrix[x][y];

    for (x=0;x<3;x++)
    {
        for (y=0;y<3;y++)
        {
            while(i++<8)
    {
        matrix[x][y]=(rand() %8 )+1;

       break;
    }
       
        }
    }

    for (x=0;x<3;x++)
    {
        for (y=0;y<3;y++)
        {
           cout<< matrix[x][y];
        }
        cout<<" "<<endl;
    }
}


If yo want an 3x3 array why do you declare it with 0x0 ???????
1
2
int x=0,y=0;
int matrix[x][y];

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
	int matrix[3][3];

	for (int x = 0; x < 3; x++)
		for (int y = 0; y < 3; y++)
			matrix[x][y] = rand()%8;

	for (int x = 0; x < 3; x++)
	{
		for (int y = 0; y < 3; y++)
			cout << matrix[x][y] << ' ';
		cout << endl;
	}

	system("pause"); //Ignore this if you're using Code::blocks
}


Try running that and tell me if it's what you were going for.
Last edited on
Topic archived. No new replies allowed.