Issue
#include <stdio.h>
#define MAX_SIZE 1000 // Maximum array size
int main() {
int arr[MAX_SIZE], size, i;
int max1, max2;
scanf("%d", &size);
max1 = max2 = -99999;
/* Input array elements */
for (i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
/*
* Check for first largest and second
*/
for (i = 0; i < size; i++) {
if (arr[i] > max1) {
max2 = max1;
max1 = arr[i];
} else
if (arr[i] > max2 && arr[i] < max1) {
max2 = arr[i];
}
}
printf("%d", max2);
return 0;
}
when I used test case 20 10 40 4 100
output is correct 40
,
but when I use 1 2 3 4 5
then output is max2 = -99999
.
Can anyone please explain to me why I am not getting this? I traced but did not get why?
Solution
The output is somewhat consistent with the input, assuming the input comes from a text file:
- the first number read is the number of entries to handle.
- for the first case,
size
is read as20
and the program tries to read 20 numbers intoarr[0]
througharr[19]
. As you do not test the return value ofscanf()
, you do not detect the invalid or missing input past the last one in the file100
.scanf()
fails and leavesarr[i]
unchanged from index4
on.arr
is unintiialized, so the contents is undefined and so is the behavior of the program. It so happens that there are no numbers inarr[4]
througharr[19]
that are larger than 40. So the second largest number is printed as40
. - for the second case,
size
is read as1
and only a single number is read intoarr[0]
, the remaining input being ignored. The loop setsmax1 = 2
andmax2 = max1
, whose initial value is-99999
. Hence the output.
You should provide 5 20 10 40 4 100
and 5 1 2 3 4 5
as input to get the expected behavior consistently.
You should also be more defensive with user input and report unexpected cases:
#include <limits.h>
#include <stdio.h>
#define MAX_SIZE 1000 // Maximum array size
int main() {
int arr[MAX_SIZE], size, i;
int max1, max2, has_max;
if (scanf("%d", &size) != 1) {
printf("missing count of numbers\n");
return 1;
}
if (size < 0 || size > MAX_SIZE) {
printf("invalid count of numbers: %i\n", size);
return 1;
}
/* Input array elements */
for (i = 0; i < size; i++) {
if (scanf("%d", &arr[i]) != 1) {
printf("invalid input: got %i numbers instead of %i\n", i, size);
size = i;
break;
}
}
/*
* Check for first largest and second
*/
max1 = max2 = INT_MIN;
has_max = 0;
for (i = 0; i < size; i++) {
if (arr[i] > max1) {
max2 = max1;
max1 = arr[i];
has_max++;
} else
if (arr[i] > max2 && arr[i] < max1) {
max2 = arr[i];
has_max++;
}
}
if (has_max < 2) {
printf("no second highest value\n");
} else {
printf("%d\n", max2);
}
return 0;
}
Note the method to track if there are at least 2 different values in the array. Try and see if this improvement is sufficient for all cases...
Answered By - chqrlie Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.