Programming C - Exchanging matrix elements

2

My code below should change the elements of the array, if it is 1 it will change by 0 and if it is 0 it will change by 1. However, the printed matrix has all the elements 0:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
//entrada: m n (matriz com m linhas e n colunas)
//         ex.: 3 4
//              0 1 1 0
//              1 0 1 0
//              0 1 0 1. Digitar em sequencia
//saída: 1 0 0 1
//       0 1 0 1
//       1 0 1 0. Trocar os valores.
int main(){
    int matriz[3][4];
    int i, j;
    //digitar/ler valores da matriz
    for (i = 0; i < 3; i++){
        for (j = 0; j < 4; j++){
        scanf("%d", &matriz[i][j]);
        }
    }
    printf("\n");
    //trocar/ler os valores da matriz
    for (i = 0; i < 3; i++){
        for (j = 0; j < 4; j++){
            if (matriz[i][j] == 0){
                matriz[i][j] = 1;
            }
            if(matriz[i][j] == 1){
                matriz[i][j] = 0;
            }
        }
    }
    //escrever a nova matriz com valores trocados
    for (i = 0; i < 3; i++){
        for (j = 0; j < 4; j++){
        printf("%d ", matriz[i][j]);
        }
    printf("\n");
    }
    return 0;
}
    
asked by anonymous 30.06.2018 / 22:14

1 answer

5

The problem is here:

            if (matriz[i][j] == 0){
                matriz[i][j] = 1;
            }
            if(matriz[i][j] == 1){
                matriz[i][j] = 0;
            }

The first if enters when it is zero, and it changes to one. This causes the second if to also enter, so it returns to zero.

The solution is to use else :

            if (matriz[i][j] == 0){
                matriz[i][j] = 1;
            } else {
                matriz[i][j] = 0;
            }

Or better yet, you can eliminate if completely:

            matriz[i][j] = !matriz[i][j];
    
30.06.2018 / 22:40