C language, matrix exercise [closed]

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 is giving result 0, position (0: 0).

    
asked by anonymous 06.12.2018 / 01:00

1 answer

1

Dude, from what I saw, you're doing:

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

That is, you are assigning a value to the largest and smallest that can be memory garbage. Eventually, the garbage stored in the larger variable may be larger than the array values and the same as the minimum. Try switching to:

int maior = 0;
int menor = 99999999;

I think that's how it works.

    
06.12.2018 / 01:14