Largest array number, does not display

0

This code does not show how the largest element in the array should be positioned correctly. What is the error?

#include <stdio.h>
#include <stdlib.h>
#define lin 4
#define col 4
int main()
{
   int mat[lin][col], i, j, maior=mat[0][0], pos_i, pos_j;

   printf("Informe os elementos da matriz\n");
   for(i=0;i<lin;i++){
      for(j=0;j<col;j++){
         printf("[%d][%d] = ", i,j);
         scanf("%d", &mat[i][j]);
         if(mat[i][j] > maior) {
            maior=mat[i][j];
            pos_i=i;
            pos_j=j;
         }
        }
   }
   printf("O maior elemento da matriz: %d\n", maior);
   printf("Posicao: [%d][%d]\n", pos_i,pos_j);
   return 0;
}

So it displays: For smaller array value it displays correctly, but for larger no.

    
asked by anonymous 04.03.2016 / 20:36

3 answers

0
int main()
{
   int mat[lin][col], i, j, maior=mat[0][0], pos_i, pos_j;
   //                             ^^^^^^^^^ LIXO

When you assign to maior the content of mat[0][0] is garbage. You need to do this then assignment of assigning values to the array.

    
04.03.2016 / 21:08
0

You should always initialize the variables and initialize a variable with another one that was not initialized does not resolve, as done on the line:

maior=mat[0][0]

Variables in C and C ++ will come with values that were previously in memory to gain a small advantage ... that means they are not guaranteed to start with 0.

It was done so because at the time it was a significant performance advantage (if you were to assign a value to the variable later and use it). Nowadays it is no longer a great thing and should always boot, but this work is done today by the programmers of this language.

    
04.03.2016 / 21:07
0

You did not initialize your and array initialized larger with mat value [0] [0], which you do not know what it is.

Try this:

   int mat[lin][col];
   int i, j, pos_i, pos_j;

   /* inicializa a matriz */
   for(i = 0; i < lin; i++){
      for(j = 0; j < col; j++){
          mat[i][j] = 0;
      }
   }

   int maior;

   printf("Informe os elementos da matriz\n");
   for(i = 0; i < lin; i++){
      for(j = 0; j < col; j++){
         printf("[%d][%d] = ", i,j);
         scanf("%d", &mat[i][j]);

         /* atualiza maior se for a primeira interacao, */
         /* ou se o valor corrente for maior            */
         if( (i == 0 && j == 0) || (mat[i][j] > maior) ) {
            maior=mat[i][j];
            pos_i=i;
            pos_j=j;
         }
      }
   }
    
04.03.2016 / 21:06