C program works only a part -
i need make program says have fill "1" in odd rows , "0" in ones. tried , wrote code, seem works part. please, can explain me method?
#include <stdlib.h> #include <stdio.h> #include <math.h> main() { int r, c; { printf("insert number of rows in matrix: "); scanf("%d", &r); printf("insert number of colums in matrix: "); scanf("%d", &c); } while(r<=0||c<=0); r--; c--; int mat[r][c]; int a, b; for(a=0; a<=r; a++) { for(b=0; b<=c; b++) { if(a%2==0) {mat[a][b]=0;} else {mat[a][b]=1;} } } printf("\noutput:\n\n"); for(a=0; a<=r; a++){ for(b=0; b<=c; b++){ printf("%d", mat[a][b]); } printf("\n"); } return 0; }
input: 2, 3
output: 001 111
you don't use number of rows , columns correctly. true in c, array n
entries can access indices 0 through n - 1
, index n
1 beyond range of array. still have define array actual size:
// don't adjust c , r here int mat[r][c];
when use dimension in for
loop, can ensure never access mat[r][c]
using <
instead of <=
condition:
for (a = 0; < r; a++) { (b = 0; b < c; b++) { if (a % 2 == 0) { mat[a][b] = 0; } else { mat[a][b] = 1; } } }
Comments
Post a Comment