I'm fairly new to Objective C and have got an assignment that requires me to accept a series of integers from the user and give 5 pieces of information from it:
- Number of inputs
- Sum of the inputs
- Average of the inputs
- Smallest of the inputs
- Largest of the inputs
I've figured out the first 3 parts, but cannot think of a way to get the min/max numbers. The only way I know how to get min/max is with "if" statements, but not sure how to incorporate them into my code. Any help would be appreciated!
#include <stdio.h>
int main(int argc, const char * argv[])
{
//variables
int input;
int count = -1;
int sum = 0;
float average = 0;
do
{
printf("Enter a number.\n");
scanf("%i", &input);
count++;
sum += input;
average = sum / count;
} while (input != 0);
printf("You entered %i numbers.\n", count);
printf("The sum of your numbers are %i.\n", sum);
printf("The average of your numbers is %f.\n", average);
return 0;
}
Edit: Created a new variable "prevnum" at the front of the "do...while" loop to equal the preceeding input. Used the "prevnum" variable to compare against new inputs and saved min/max values using "if...else" statements. Not sure if it's the most efficient or 'correct' way to do it, but it's functional and gives the right output. Code is as follows:
include
int main(int argc, const char * argv[]) {
//variables
int input = 0;
int count = -1;
int sum = 0;
int average = 0;
int max = 0;
int min = 0;
int prevnum;
do
{
prevnum = input;
printf("Enter a number.\n");
scanf("%i", &input);
count++;
sum += input;
average = sum / count;
if(input >= prevnum && input >= max)
max = input;
else if(input < max)
max = max;
if(input <= min && input <= max)
min = input;
else if(input > min)
min = min;
} while (input != 0);
printf("You entered %i numbers.\n", count);
printf("The sum of your numbers are %i.\n", sum);
printf("The average of your numbers is %i.\n", average);
printf("The largest number entered was %i.\n", max);
printf("The smallest number entered was %i.\n", min);
return 0;
}