Functions and Matrices (Example 1)

Consepts:
Passage of a Matrix to a function (matrices in C are passed to a function by reference)

Text:
Realize a function that:

void change_sign(int matr[][C], int nr, int nc);

The calling function (main) must print the matrix before and after the transformation performed by the function change_sign.

Solution:

matrici_funzioni_1.c
/* Realize a function that receives as parameters a matrix and its dimension, i.e., the number of rows and columns.
   The function must change the sign of all the elements of the rows of the matrix that have an even row index
   (i.e, rows with indexes 0, 2, 4, 6,...). */
 
#include <stdio.h>
 
#define R 3
#define C 4
 
void change_sign(int matr[][C], int nr, int nc);
 
int main(){
  int m[R][C] = {{1, 2 , 3, 4}, {-1, -2, 3, 4}, {1, -2, 3, -4}};
  int i, j;
 
  printf("Initial matrix\n");
  for(i=0; i<R; i++){
    for(j=0; j<C; j++){
      printf("%3d", m[i][j]);
    }
    printf("\n");
  }
 
  change_sign(m, R, C);
 
  printf("Final matrix, with even index rows changed of sign\n");
  for(i=0; i<R; i++){
    for(j=0; j<C; j++){
      printf("%3d", m[i][j]);
    }
    printf("\n");
  }
 
  return 0;
}
 
 
void change_sign(int matr[][C], int nr, int nc){
  int r, c;
 
  for(r=0; r<nr; r++) {
    if(r%2==0) {
      for(c=0; c<nc; c++) {
        matr[r][c] = -1*matr[r][c];
      }
    }
  }
}