random int 0 and 1

Hi all.
I'm kinda new in programming, actually I'm a student.

I just want to know how to randomize and obtain 0 or 1.
I DID THIS, BUT ALL I GET IS A 10x8 MATRIX 0's:

WHAT'S WRONG?

int _tmain(int argc, _TCHAR* argv[])
{
int matr[10][8];
for (int i = 0; i < 10; i++)
{
for (int k = 0; k < 8; k++)
matr[i][k]=rand() % +2;
}
for (int i = 0; i < 10; i++)
{
for (int k = 0; k < 8; k++)
cout << matr[10][8] << " ";
cout << endl;
}
system("pause");
return 0;
}
This is wrong:

matr[i][k]=rand() % +2;

Instead, it should be

matr[i][k]=rand() % 2;

Actually, you should also initialize the random number generator with

1
2
3
#include <ctime>
...
srand(time(NULL));     // this at the beginning of the main 
Last edited on
Still not working.

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
#include "stdafx.h"
#include "ctime"
#include "iostream"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	int matr[10][8];
	srand(time(NULL));
	for (int i = 0; i < 10; i++)
	{
		for (int k = 0; k < 8; k++){
			matr[i][k]=rand() % 2;
		}
	}
	for (int i = 0; i < 10; i++)
	{
		for (int k = 0; k < 8; k++)
			cout << matr[10][8] << " ";
		cout << endl;
	}
	system("pause");
	return 0;
}
 


Could it be a compiler bug?

I'm using VS2013.
No, there is another mistake when you print the matrix: this is wrong

cout << matr[10][8] << " ";

It should be

cout << matr[i][k] << " ";
Oh my god, I'm so stupid :D

TY, now is working.
BTW, matr[i][k]=rand() % +2; is legal, just awkward.
Topic archived. No new replies allowed.