Program that calculates the largest and smallest number, and the average

Hello world! I need help with this program, I barely understand something of C++, so, I only got the largest number and the average.. I don't know how to get the smallest number... Help!


#include <stdio.h>

int main() {
int i=0;
float num,largest=0,smallest=0,add=0,average=0;

printf("Get numbers\n");

while (scanf("%f",&num)) {
if (num > largest)
largest = num;

add = add + num;
i++;
}
average = add / (float)i;

printf("Largest = %.2f\n",largest);
printf("Average = %.2f",average);

return 0;
}


It would be awesome if somebody could help me! :)
Hello Yeyk,

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

Is this supposed to a C program or a C++ program?

You have an if statement to find the largest that works. Logic would dictate that a similar if statement for the smallest number would be appropriate. I also find that when you define the variable smallest you set this to a large number that you are not likely to use like: 1000 or 100000. The first time through the if statement this will change.

Hope that helps,

Andy
To get the average is just simple math add all the variables up and divide by the amount of variables

To get the biggest number you could just test that in a for loop create a variable called biggest set it equal to the first number in your array(outside the loop) then use a test condition if array[i] > biggest set biggest equal to the number in array[i]

do the same for smallest but use the less than < operator

Hey!! I just did that, but now I need that when it writes a letter or symbol it prints "Error"... besides I don't know how to stop the program when you put the numbers (bc you have to put another character so it can start)
Hello Yeyk,

If I understand what you said you would have to rewrite the while loop and I might consider a do/while loop in its place.

Inside the do/while loop you could use a while loop, I think, to to check the state of "scanf". It it is in a failed state you print an error message, clear the state bits and ask and get new input. when the input and "scanf" is left in a good state the while loop will be exited.

I have not used C in a while, so it will take me some time to convert what I do in C++ to C.

Hope that helps,

Andy
Topic archived. No new replies allowed.