Language C, matrix exercise

Asked

Viewed 93 times

1

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


int main()
{   

    int matriz[5][5];
    int i, j, posicao=0;

    int maior = matriz[0][0];
    int menor = matriz[0][0];
    int posicaoI=0, posicaoJ=0, posicaoi=0, posicaoj=0;

    srand(time(NULL));

    for(i=0; i < 5; i++){
        for(j=0; j < 5; j++){
            matriz[i][j]=rand()%101;
    }
    }

    for(i=0; i < 5; i++){
        for(j=0; j < 5; j++){
                if(matriz[i][j] > maior){
                    maior = matriz[i][j];
                    posicaoI = i;
                    posicaoJ = j;
                }
                if(matriz[i][j] < menor){
                    menor = matriz[i][j];
                    posicaoi = i;
                    posicaoj = j;
                }
            printf("(%d,%d) %d\n", i, j, matriz[i][j]);
    }
    }
            printf("Posicao (%d:%d), o maior valor é %d\n", posicaoI, posicaoJ, maior);
            printf("Posicao (%d:%d), o menor valor é %d\n", posicaoi, posicaoj, menor);
}

The highest value generated is working normal, but the lowest value ta giving 0, position (0:0).

  • Replace larger by matrix[poscaoI][posicaoJ] and smaller by matrix[posicaoi][posicaoj] and remove larger and smaller and their attributions.

1 answer

1


Man, from what I’ve seen, you’re doing:

int matriz[5][5];   
int maior = matriz[0][0];
int menor = matriz[0][0];

That is, you are assigning a higher and lower value that can be junk memory. Eventually, the garbage stored in the larger variable may be greater than the matrix values and the same for the minimum. Try switching to:

int maior = 0;
int menor = 99999999;

I think this will work.

  • Also I usually make use of the memset to set an array. It is a very useful and very fast function, excellent performance. In this case it would be memset(&matriz, 0, sizeof matriz);. Remembering that I use the sizeof matriz because it is not a pointer, that is, it will use the correct size.

Browser other questions tagged

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