I'm trying to make a program which asks user to enter the number of pancakes eaten by ten people. Then it is supposed to tell "The maximum and minimum" amount of pancakes eaten.
I can't seem to figure out a way to find the max and min.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <stdio.h>
int main(void)
{
int pancakes;
int person=1;
int i;
for(i=1; i<=10; i++)
{
printf("Enter the number of pancakes eaten by person %d: ", person);
scanf("%d", &pancakes);
person++;
}
getch();
}
Easiest way I can think of is to have 3 variables, a current_pancakes (or just what you have, pancakes), a pancakes_max, and a pancakes_min, initialized at -1 or something. Every time in your for loop, you need to have something like
1 2 3 4 5
//after getting value for (current) pancake
if (current_pancake > pancakes_max)
pancakes_max = current_pancake;
if (current_pancake < pancakes_min)
pancakes_min = current_pancake;
In English, "if the current person ate more than what was already the known max, the amount that person ate is now the new max".
Also, not sure what the point if your person variable is, so maybe I'm misunderstanding what you're trying to do.
#include <stddef.h> // for typedef size_t
#include <stdint.h> // for macro SIZE_MAX
// ...
size_t min = SIZE_MAX;
size_t max = 0;
for (/* ... */)
{
size_t nop; // Number Of Pancakes
scanf("%zu", &nop);
if (nop < min) // we found a new minimum
min = nop;
if (nop > max) // we found a new maximum
max = nop;
}
#include <stdio.h>
int main(void)
{
int pancakes_current;
int pancakes_max;
int pancakes_min;
int person=1;
int max=0;
int min=0;
int i;
for(i=1; i<=10; i++)
{
printf("Enter the number of pancakes eaten by person %d: ", person);
scanf("%d", &pancakes_current);
person++;
if (pancakes_current > pancakes_max)
{
pancakes_max = pancakes_current;
}
if (pancakes_current < pancakes_min)
{
pancakes_min = pancakes_current;
}
}
printf("The maximum number of pancakes eaten are %d.\n", pancakes_max);
printf("The minimum number of pancakes eaten are %d.\n", pancakes_min);
getch();
}
Your current code has a flaw: the pancakes_max/min are uninitialized. If the *_max happens to be larger than any input, it will not be corrent in the end. Same with the *_min.
When you have to update the max or min, you know who that current person is. Store that info on separate variables.