Error reading and comparing matrix numbers

Asked

Viewed 119 times

1

The program must read a number and compare with the numbers of any 3x3 matrix if the number belongs to a column of the matrix it must print the position, when type 1 it prints two positions, but 1 is only in one position.

#include <stdio.h>

main () 
{
    int matriz[3][3];
    matriz[1][1] = 1;
    matriz[1][2] = 2;
    matriz[1][3] = 3;
    matriz[2][1] = 4;
    matriz[2][2] = 5;
    matriz[2][3] = 6;
    matriz[3][1] = 7;
    matriz[3][2] = 8;
    matriz[3][3] = 9;
    int coluna, linha, numero;

    printf("Digite um numero: ");
    scanf("%d", &numero);
    fflush(stdin);

    for (linha = 1; linha < 4; linha ++){
        for (coluna = 1; coluna < 4; coluna ++) {
            if(numero == matriz[linha][coluna]){
                printf ("\nA posicao do numero eh linha: %d e coluna: %d", linha, coluna);
            }
        }
    }
    if (numero < 1 || numero > 9){
        printf ("Nao encontrado!");
    }
}
  • 2

    And it’s very simple. When you create an array of 3x3 for example, in fact you can only vary from 0 to 2, ie if you create an array [N] , will be accessible from 0 to N-1

  • Thank you, simple even hahaha ;)

  • @Karensantos Did the answer solve the problem? Do you think you can accept one of them? See the [tour] how to do this. You’d be helping the community by identifying the best solution. You can only accept one of them, but you can vote for anything on the entire site.

1 answer

4

Vectors in almost all programming languages start from scratch and not from 1. So for 3 elements it must vary between 0 and 2, thus:

#include <stdio.h>

int main() {
    int matriz[3][3];
    matriz[0][0] = 1;
    matriz[0][1] = 2;
    matriz[0][2] = 3;
    matriz[1][0] = 4;
    matriz[1][1] = 5;
    matriz[1][2] = 6;
    matriz[2][0] = 7;
    matriz[2][1] = 8;
    matriz[2][2] = 9;
    int coluna, linha, numero;
    printf("Digite um numero: ");
    scanf("%d", &numero);
    for (linha = 0; linha < 3; linha++) {
        for (coluna = 0; coluna < 3; coluna++) {
            if (numero == matriz[linha][coluna]) printf("\nA posicao do numero eh linha: %d e coluna: %d", linha, coluna);
        }
    }
    if (numero < 1 || numero > 9) printf("Nao encontrado!");
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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