tomJO - 9 months ago 62

C Question

I need to make a simple program which will count the max number of each row.

`#include <stdio.h>`

void main(){

int lentele[50][50],x,y,n;

int maxx[50], maxy[50], max_value[50];

printf("Enter one number which will determine how many rows and columns your table will have:");

scanf("%d", &n);

for (y=1; y<=n; y++){

for (x=1; x<=n; x++){

scanf("%d", &lentele[y][x]);

if (max_value[y] < lentele[y][x]){

max_value[y]=lentele[y][x];

maxx[y]=x;

maxy[y]=y;

}

}

}

for (y=1; y<=n; y++){

for (x=1; x<=n; x++){

printf("%d\t", lentele[y][x]);

}

printf("\n");

}

for (x=1; x<=n; x++){

printf("Max in %d row: %d (%d,%d)", x, max_value[x], maxx[x], maxy[x]);

printf("\n");

}

}

The problem is, few rows are calculated correctly, and the others display strange big numbers like 23123.

Here are some of the input & output examples:

I enter number:

`2`

It means that it will have 2 rows and 2 columns.

Now I will enter 4 different numbers:

I enter:

`1`

2

3

4

The output is: (first it displays how the table looks like and then the results)

1 2

3 4

Max in 1 row: 2 (2,1)

Max in 2 row: 4 (2,2)

Now if I try the same thing one more time:

I enter:

`1`

2

3

4

The output is: (first it displays how the table looks like and then the results)

1 2

3 4

Max in 1 row: 2 (2,1)

Max in 2 row: 1537186176 (1539574368,8)

Could you tell me what's wrong? I don't want a simplified code, I would like to know what is not right here.

Answer

The code does not initialise `max_value[50]`

to `0`

or even better to `INT_MIN`

if you plan to enter negative numbers too.

Simply add the initialiser to the declaration by doing:

```
#define VALUES_MAX (50)
int max_value[VALUES_MAX] = {0}; /* Default all array elements to zeros,
which is suffcient for comparing to positve numbers. */
/* If comparsion to negativ number hall be performed set all array elements to INT_MIN. */
for (size_t i = 0; i < VALUES_MAX; ++i)
{
max_value[i] = INT_MIN;
}
```

`INT_MIN`

is defined in `<limits.h>`

.

Source (Stackoverflow)