Programming C - Swap matrix elements

Asked

Viewed 1,652 times

2

My code below should exchange the elements of the matrix, if it is 1 will exchange for 0 and if it is 0 will exchange for 1. However the printed matrix is with all 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;
}

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 makes the second if also between, and therefore, it returns to zero.

The solution is to use the 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];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.