stevekai February 2016

C program works only a part

I need to make a program which says that I have to fill "1" in the odd rows and "0" in the even ones. I tried and wrote this code, but it seem like it works for only a part. Please, can you explain me the method?

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

main()
{
  int r, c;
  do {
  printf("Insert the number of the rows in the matrix: ");
  scanf("%d", &r);
  printf("Insert the number of the colums in the 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

Answers


nullpointer February 2016

You are messing up with the size of the matrix. You might want to change the sequence of these two and give it a try :

r--; c--;
int mat[r][c];

change this to

int mat[r][c];
r--; c--;

and the code should work as you expect.


M Oehm February 2016

You don't use the number of rows and columns correctly. It is true that in C, an array with N entries can access the indices 0 through N - 1 only and that the index N is one beyond the range of the array. But you still have to define the array with the actual size:

// Don't adjust c and r here

int mat[r][c];

When you use the dimension in a for loop, you can ensure that you never access mat[r][c] by using < instead of <= as condition:

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;
        }
    }
}

Post Status

Asked in February 2016
Viewed 3,300 times
Voted 11
Answered 2 times

Search




Leave an answer