0

Seeing the solution to this online on Stackoverflow https://stackoverflow.com/a/19200031/3185410 I tried to come up with another solution by setting max to -infinity and min to +infinity. The code here by @haccks works pretty fine.

#include <stdio.h>

int main()
{
int num, max, min;

printf ("Enter four numbers: ");
scanf ("%d", &num);
max = min = num;

for (int i = 0; i < 3; i++)
{ 
    scanf ("%d", &num);
    if (max < num)
        max = num;
    else if (min > num)
        min = num;
}

printf ("\n%d %d", max, min);
return 0;
}

Here's the one I came up with:

#include <stdio.h>
#include <limits.h>
void main()
{
int max,min,num,i;
min=INT_MAX;
max=INT_MIN;
for (i=0;i<=3;)
{
    i++;
    printf("Enter number %d : ",i);
    scanf("%d",&num);
    if (num>max) max=num;
    else if (num<min) min=num;
}
printf("max is %d and min is %d",max,min);
}

What am I doing wrong with that?

Community
  • 1
  • 1
OsomePersan
  • 21
  • 1
  • 1
  • 4

2 Answers2

2

If the users input 5 then 6 you have :

for 5 : 5>-inf => max = 5

for 6 : 6>5 => max = 6 but then min has become 5 and yet it is still INT_MAX.

If you put if instead of else if, you loose in performance but have the right output I think (I cannot test right now).

Vulpo
  • 873
  • 1
  • 9
  • 25
0

Set first input as min and max value. And then add logic you wrote. Here you had 2 lines of extra code but you don't have to sacrifice performance.

#include <stdio.h>
#include <limits.h>
void main()
{
int max,min,num,i=0;
min=INT_MAX;
max=INT_MIN;
printf("Enter number %d : ",i+1);
scanf("%d",&num);
min=num;
max=num;
for (i=1;i<=3;)
{
    i++;
    printf("Enter number %d : ",i);
    scanf("%d",&num);
    if (num>max) max=num;
    else if (num<min) min=num;
}
printf("max is %d and min is %d",max,min);
}
Anirban Pal
  • 529
  • 4
  • 10