# Thread: producing a matrix of 1's and 0's

1. ## producing a matrix of 1's and 0's

I am trying to produce a random matrix filled only with 1's and 0's but am struggling. I woudl appreciate anyones advice!

This is my code so far:
insert
Code:
```#include <stdio.h>
#include <stdlib.h>
main(){
int a[10][10]={0};
int n,p, noofelements, randomno, rowpos, colpos;
int i,j,k;
srand(k);

printf("Enter the seed: ");
scanf("%d", &k);
printf("Enter the number of rows: ");
scanf("%d", &p);
printf("Enter the number columns: ");
scanf("%d", &n);
noofelements=n*p;
for (i=1; i<=noofelements; i++)
{
rowpos=rand()%n;
colpos=rand()%p;
a[rowpos][colpos]=i;
}
for (i=0; i<p; i++)
{
for (j=0; j<n; j++)
printf("%d\t", a[i][j]);
printf("\n");
}
}```
Emma

2. if you want only zeroes and 1 why do you insert something else?

a[rowpos][colpos]=i;

3. You also need to read in a value for k before doing
srand(k);

4. I am new to C programming and am finding it very difficult! I realise where I have gone wrong above, but still can't get a matrix with 0's and 1's in. now it just has weird numbers in. can anyone give me a hint?

Thanks Emma

insert
Code:
```#include <stdio.h>
#include <stdlib.h>
main(){
int n,p, rowpos, colpos;
int i,j;
int board[p][n];

printf("Enter the dimensions of the board , separate them with a comma:\n");
scanf("%d,%d", &p,&n);

for (i=0; i<p; i++)
{
for (j=0; j<n; j++)
printf("%d\t", board[i][j]);
printf("\n");
}
}```

5. You are not setting the board[i][j] to anything, are you?

--
Mats

6. You have three steps to your task:
1. Reading in the dimensions of the matrix.
2. Creating a matrix as a two dimensional array with the given dimensions.
3. Populating the matrix with 0's and 1's in random order.

It looks like you have step 1 done, but it wrote it such that it comes after step 2, and consequently you do not actually create your matrix with the desired size.

Furthermore, I must inform you that you are using a variable length array. Are you sure you are supposed to use that? Maybe you are supposed to use malloc() and free(), or maybe you are supposed to create a two dimensional array of the maximum size allowed, and then use only part of that array as necessary.

Either way, it would be a good idea to finish steps 1 and 2 before going on to step 3. (You can also do step 3 directly by "hard coding" the array size, but for now doing things step by step is probably better.)

Also, note that you should declare main() as returning an int, and then return 0 at the end (though that return is optional according to the 1999 edition of the C standard, which you are probably compiling against to use variable length arrays). You should also indent your code more consistently.

Popular pages Recent additions