Марко Лучић
Марко Лучић

Reputation: 91

Finding min and max value in C (while loop)

I am new at C. I am having problems with finding min and max value with while loop. Can somebody tell me how can I find MIN value without initializing min value with random number..

#include<stdio.h>
#define STOP 0
main()
{
int n, min, max;
printf("unesite niz cijelih brojeva [0 za kraj]: \n");

scanf("%d", &n);
max=0;
min=999999;
while(n!=STOP)
{
    if(n<min)
        min=n;
    if (n>max)
        max=n;
    scanf("%d", &n);
}
printf("max broj je: %d, a min broj je: %d.\n", max, min);
    system("pause");

}

Upvotes: 1

Views: 7067

Answers (2)

chux
chux

Reputation: 153338

As @Марко Лучић says min=n;

Code can also max=n;

Suggested modifications:

1- Initialize min, max

#include <limits.h>
min = INT_MAX;
max = INT_MIN;

2- Test scanf() results. Only 1 scanf() needed.

while (scanf("%d", &n) == 1 && n != STOP) {
  if(n < min)
    min = n;
  if (n > max)
    max = n;
}

Upvotes: 1

Марко Лучић
Марко Лучић

Reputation: 91

Problem was at line where i was initializing min value. The right code is:

#include<stdio.h>
#define STOP 0
main()
{
int n, min, max;
printf("unesite niz cijelih brojeva [0 za kraj]: \n");

scanf("%d", &n);
max=0;
min=n; //here was the problem
while(n!=STOP)
{
if(n<min)
    min=n;
if (n>max)
    max=n;
scanf("%d", &n);
}
printf("max broj je: %d, a min broj je: %d.\n", max, min);
system("pause");
}

Upvotes: 1

Related Questions