Getting the min, max, and ave of the five numbers inputted - c

I'm trying to work on a program in C that gets 5 input numbers and then store these in an array. After getting the the 5 numbers, I must be getting the min, max and the average of the MINIMUN AND MAXIMUM numbers inputted and not all of the five. So here's the code that I made. When I get the maximum number, it seems to be working fine. But when it come's to the min, it's still same as the maximum and so I'll be getting a different average.
#include <stdio.h>
#include <conio.h>
int main()
{
int num[5];
int counter, min, max=0;
float average, total;
min=num;
for(counter=1; counter<=5; counter++)
{
printf("Enter a number: ");
scanf("%d", &num[5]);
if(num[5]>max)
{
max = num[5];
}
if (num[5]<min)
{
min = num[5];
}
}
total = min + max;
average = total/2;
printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min);
printf("The average is: %d", average);
getch();
return 0;
}

Since this is a learning exercise, I wouldn't correct your code, but point out what needs to be fixed:
Arrays in C are indexed from zero, not from one, so the counter should go from 0 to 4, inclusive
min is an int, while num is an array, so the assignment min=num is invalid
scanf should put the data into &num[count], not &num[5]
In the way that you coded your loop you do not need an array at all: you need the last number entered.
total cannot be computed as min+max; you need to keep a running total, updating it on each iteration.

Related

While loop will not print the smallest number entered

I am creating a program that uses a while loop to provide multiple pieces of information from input given by the user. One of these pieces is the smallest number entered. I can't get it to print anything but 0. Any idea why?
#include <stdio.h>
#include <stdlib.h>
int main()
{
float num, sum = 0, sm, lg = 0, count = 0, avg = 0;
printf("Please enter a series of numbers (-1 to terminate): ");
scanf("%f", &num);
while(num > -1){
sum += num;
if(lg < num)
lg = num;
if(sm > num)
sm = num;
scanf("%f", &num);
count++;
avg = sum / count;
}
printf("The sum of your numbers is: %.4f\n", sum);
printf("You entered %.4f numbers\n", count);
printf("The average of the numbers you entered is: %.4f\n", avg);
printf("The smallest number you entered is: %.4f\n", sm);
printf("The Largest number you entered is: %.4f", lg);
return 0;
}
ex entry- 15
43
22.5
57.6
-1
Output-
sum:138.1000
4 numbers entered
average: 34.5250
smallest: 0.0000
Largest: 57.6000
In your code, sm has an undefined value because you aren't initializing it. You can initialize it to something like a very large number (or, even better, INFINITY) so it can be properly compared. The same goes for lg: if you want it to work for negative values too, you should initialize it with a very small value (-INFINITY). You can use INFINITY by including math.h.
the posted code does not compile!
first, because it is missing the needed #include statements for the needed header files. Specifically:
#include <stdio.h>
Then regarding this code block:
if(sm > num)
sm = num;
on the first pass through the while() loop, the variable sm is not initialized so accessing its' contents is undefined behavior.
Also, if using visual studio in debug mode, then all the stack is cleared to 0, so no other value will ever be assigned to it. This is why the algorithm always returns 0
Here's what I regard as a workable program. It uses double rather than float; if you insist, you can change the types and (input) formats to suit your desires. It has no particular limit on the number of rows it will accept. It doesn't output anything if there were no inputs. There is absolutely no need to use an array for the calculations. It uses use +∞ and -∞ to initialize the smallest (min) and largest (max) values respectively. Even if the only input is +∞ or -∞ (spelled +Inf or -Inf, or +Infinity or -Infinity, optionally without the + sign, and with upper-case, lower-case or mixed-case spelling) the correct values are produced.
#include <stdio.h>
#include <math.h>
int main(void)
{
double min = +INFINITY;
double max = -INFINITY;
double sum = 0.0;
size_t cnt = 0;
double value;
while (scanf("%lf", &value) == 1)
{
sum += value;
cnt++;
if (value > max)
max = value;
if (value < min)
min = value;
}
if (cnt > 0)
{
printf("Count = %zu\n", cnt);
printf("Sum = %g\n", sum);
printf("Min = %g\n", min);
printf("Max = %g\n", max);
printf("Average = %g\n", sum / cnt);
}
return 0;
}
Given ten random values between -1E6 and +1E6:
989375.672
-826955.668
224850.463
-401605.702
-45457.787
259618.099
821069.496
-268408.724
-512449.113
-46404.246
the program produces the output:
Count = 10
Sum = 193632
Min = -826956
Max = 989376
Average = 19363.2
I should probably put a bit more control on the output formatting, but the %g option is quite useful for numbers with wide ranges. Given the input data, using %11.3f would work well (it was used to format the output from the random number generator I used).

Adding 3 basic features to my existing code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a gradebook program that I've been building, which works fine, but now I want to slot 3 new functions into the existing code. I can't wrap my brain around the logical path I need to take to make it work. I need a SIMPLE way to also get the highest, lowest, and average grades printed at the end. Here's my program...
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_GRADE_COUNT 200
int main() {
int grade[MAX_GRADE_COUNT];
int i;
int count = 0;
char continueResponse;
printf("Welcome to Gradebooker!\n\n");
for(i = 0; i < MAX_GRADE_COUNT; i++) {
printf("Please enter grade (0-100): ");
scanf(" %d", &grade[i]);
count++;
printf("Do you have more grades to enter?(Y/N): ");
scanf(" %c", &continueResponse);
if(toupper(continueResponse) != 'Y') {
printf("\n >> Thank you for using Gradebooker! <<\n");
break;
}
}
printf("\n\nCurrent Gradebooker listings: \n\n");
for(i = 0; i < count; i++) {
printf("\t%5d\n", grade[i]);
}
return 0;
}
The program would need to calculate the max, min and average in the second loop, like this:
int sum = 0;
int minimum = INT_MAX;
int maximum = 0;
for(i = 0; i < count; i++) {
printf("\t%5d\n", grade[i]);
sum += grade[i];
if(grade[i] < minimum) minimum = grade[i];
if(grade[i] > maximum) maximum = grade[i];
}
float average = (float)sum / count;
printf("min grade: %d\n", minimum);
printf("max grade: %d\n", maximum);
printf("average: %f\n", average);
The minimum starts with a value that is larger than all values in the list (INT_MAX for example is the largest possible value an int can take). Then, for each grade in the array, it replaces it with that grade, if it is smaller than the one currently in the minimum variable. That way minimum will in the end contain the smallest grade.
Same for maximum, but reversed.
For the average, it accumulates the sum of all grades (sum needs to be initialized to 0 at the beginning), and the divides it by the number of grades in the end. This gives an arithmetic mean in average.
Using float, it calculates the average as a floating point number (so the average can be non-integer). The (float)sum / count is needed so that it will first cast (convert) sum to a float, and so a floating point division on it. Otherwise, with sum / count is would do an integer division (which returns a rounded down integer), and store that as float in the average variable afterwards.
The idea for finding maximum value is: first declare a variable (lets say, MAXX) to store maximum value and initial it with as minimum value as possible and then iterate through the array and if any value in the array found greater then the current value of MAXX variable than update the value of MAXX with the value.
The idea for finding minimum value is: first declare a variable (lets say, MINN) to store minimum value and initial it with as maximum value as possible and then iterate through the array and if any value in the array found greater then the current value of MINN variable than update the value of MINN with the value.
Idea for finding avarage: Sum all the grade and then divide the sum with the number of grade.
See the implementation below for better understanding:
int max_grade = 0;//for storing maximum grade
/*
Minimum possible value should be initialize here.
Best option to write here is:
int max_grade = INT_MIN;
But to use INT_MIN <limits.h> file must be included.
*/
int min_grade = 10000000;//for storing maximum grade
/*
Maximum possible value should be initialize here.
Best option to write here is:
int min_grade = INT_MAX;
But to use INT_MAX <limits.h> file must be included.
*/
int total_grade = 0;//for counting all the grade
for(i = 0; i < count; i++) {
if(grade[i] > max_grade){
max_grade = grade[i];
}
if(grade[i] < min_grade){
min_grade = grade[i];
}
total_grade += grade[i];
}
printf("Max grade = %d\n" max_grade);
printf("Min grade = %d\n" min_grade);
printf("Avg grade = %d\n" total_grade/count);
I could not see all your code (it seemed to be cut off at the bottom), however the basically procedure to get an average, max and min in C is as follows:
int running_total = 0;
int count_grades = 0;
int max_so_far = 0;
int min_so_far = 999;
while( -1 ){ // infinite loop
// get input (a grade)
// if input is done, break
count_grades++;
running_total += iCurrentGrade; // (iCurrentGrade should be defined during input phase)
if( iCurrentGrade > max_so_far ) max_so_far = iCurrentGrade;
if( iCurrentGrade < min_so_far ) min_so_far = iCurrentGrade;
}
printf( "avg: %d min: %d max: %d\n", (int)(running_total / count_grades), min_so_far, max_so_far );

Incorrect output for a particular code. (Maximum, minimum, grade_scanner)

I've been trying to figure this out the last few days, but no luck. The objective is to find the sum, average, minimum, and maximum grades and display them.
Here is my code, everything except minimum, maximum and grade input seem to work
// Includes printf and scanf functions
#include <stdio.h>
int main(void) {
unsigned int counter; // number of grade to be entered next
int grade; // grade value
int total; // sum of grades entered by user
float average; // average of grades
int maxi; // Max grade
int mini; // min grade
int i;
int max;
int min;
maxi = 1;
mini = 1;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
//scanf("%d%d", &min, &max);
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
//scanf("%d",&counter);
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
break;
}
else {
total = total + grade;
average = (float)total / counter; // NOTE: integer division, not decimal
}
}
max = (grade < maxi) ? maxi : grade;
min = (grade > mini) ? mini : grade;
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
Output:
Enter number of grades: 2
5
7
Enter grade 1: 4
Enter grade 2: 3
Class average is: 3.500
Your maximum grade is 3
Your minimum grade is 1
Sum: 7
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade" then from there it calculates everything. Also, it seems that the Maximum is always the last grade that I enter and shows 1 as the minimum when no where in the input is 1. I am supposed to use a conditional operator for the max/min, I tried looking it up and reading the book, but they just use letters like a,b,c, etc. Which just confused me so I'm not sure if I did it wrong.
Could that be what is messing everything up? If it isn't what am I doing wrong?
Another thing is I'm thinking I need a While loop if I want to make the counter have an input from 1-100, is that right?
Edit: just realized I had to remove the scanf for max and min. Taht's why I had to inptu 2 nubmers first
There are two major problems, as I see it
The variable total is not initialized, so the first occurrence of total = total + grade; would invoke undefined behaviour.
You have to initialize it explicitly to 0.
The same variable grade is used for holding the repeated input. After the loop, grade will only hold the last input value.
You need to either use an array for storing inputs and comparison, or, compare and update the min and max as you go, inside the loop.
For future references, please seperate your code in different functions or add comments, since analyzing an unfamiliar code always takes much time.
min: Your problem here lies, that you're initializing your min value with 1. That value is most of the time below your input grades. If you want to initialize it, you should use a high number.
For example:
#include <limits.h>
int min = INT_MAX;
max: Your "grade" will be always the last typed grade, which you scanned. That's not what you want. It would be good, to save all values, which you get as input in an array or a list.
Also your codesnippet at the end
max = (grade<maxi) ? maxi : grade;
min = (grade>mini) ? mini : grade;
will just compare one grade. You need to compare all values, which you entered.
You could just put them in the for-loop.
gradeinput: You need to temporarily save your inputs in a datastructure like an array/list to use them in your program.
int x[counter];
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i);
x[i]=scanf("%d", &grade);
}
.. have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
This happens because OP's stdout is buffered and not one character at a time.
To insure output is seen before the scanf(), use fflush().
See What are the rules of automatic flushing stdout buffer in C?
printf("Enter number of grades: ");
fflush(stdout); // add
scanf("%d", &counter);
Rather than set the min = 1, set to a great value
maxi = 1;
mini = 1;
maxi = 0;
mini = 100;
// or
maxi = INT_MIN;
mini = INT_MAX;
Move the test for min/max in the loop to test each value and fold maxi, max into the same variable.
if (max > grade) max = grade;
if (min < grade) min = grade;
The first total + grade is a problem as total is uninitialized.
// int total; // sum of grades entered by user
int total = 0; // sum of grades entered by user
Unnecessary to calculate average each time though the loop. Sufficient to do so afterward.
Style: After the break; the else is not needed.
Good that code tests user input range. Yet the i-- is incorrect. If code is to break, just break. If code it to try again, the i-- makes sense, but then code should continue.
The comment // NOTE: integer division, not decimal is incorrect as (float) total / counter is FP division.
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n");
i--;
continue;
}
total = total + grade;
} // end for
average = (float) total / counter;
In general, casting should be avoided.
Advanced issue: Consider the situation if later on code was improved to handle a wider range of integers and used higher precision FP math.
The 1st form causes total to become a float (this could lose precision) and perhaps use float to calculate the quotient, even if average was a double. Of course the (float) cast could be edited to (double) as part of the upgrade, but that is a common failure about updates. Types may be changed, but their affected object uses are not fully vetted.
The 2nd form below causes total to become the same type as average and use the matching math for the type. Reduced changed needed as the types change. This form is also easier to review as one does not need to go back and check the FP type of average to see if a cast to float, double or even long double was needed.
average = (float) total / counter;
// or
average = total;
average /= counter;
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
You have two scanf before "Enter grade"
scanf("%d", &counter);
scanf("%d%d", &min, &max);
#include <stdio.h>
int main(void) {
int counter; // number of grade to be entered next
int grade; // grade value
int total=0; // sum of grades entered by user
float average; // average of grades
int i;
int max;
int min;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
} else {
if(i==1){
max = grade;
min = grade;
}
else{
max = (grade < max) ? max : grade;
min = (grade > min) ? min : grade;
}
total = total + grade;
average = (float) total / counter; // NOTE: integer division, not decimal
}
}
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
I've edited your Code as there were some mistakes. First, you were not initialising the total, which may make it take some garbage value. The second one is no need of using break as you are reducing the value of i.The third one is that you are updating the min and max outside the for loop, where the value of grade will be the last entered grade. And maxi and mini are not at all needed. The code was running perfectly without waiting for dummy values. Cheers!

How to refine this code and sort the data being read into the array?

I want to write a C program to read an array, calculate the sum of all individual entries, the average, the minimum grade, the maximum grade, and print all of those values. Is this an effective method of sorting? I'm attempting to sort the data values by min and max comparing it as they are input. My compiler also throws a declaration error with all of the float values.
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
float main()
int i;
float grades[10];
float grade;
float sum;
float avg;
float count;
float max;
float min;
{
max =0;
min=0;
printf("Enter your grades (Type <0 and >100 to quit): ");
scanf("%f", &grade);
sum=0;
i=0;
while(grades>0 && i<10)
{grades[i]= grade;
i++;
if(i<10)
{printf("Enter grade, (Type <0 or >100 to quit): ");
scanf("%f", &grade); }}
for (i=0; i < 10; i++)
{if (grades[i] > max)
{
max=grades[i];
}
else if (grades[i] < min)
{
min = grades[i];
}}
count=i;
for(i=0; i<count; i++)
{printf("Grade %d is %f \n", i+1, grades[i]);}
grade=0;
for(i=0;i<count; i++)
{sum= sum + grades[i];}
if(count>0)
{avg=sum/count;}
else
{avg=0;}
printf("The average of the %f grades is %f \n",count, avg);
printf("The Minimum Grade is %f",min);
printf("The Maximum Grade is %f", max);
printf("Count is %f ", count);
printf("Sum is %f", sum);
printf("Average is %f", avg);
}
The very refided code for solving your problem is
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#define GRADE_ARRAY_LEN 10
int main()
{
int i = 0;
double grades[GRADE_ARRAY_LEN];
double grade;
double max;
double min;
while(i<GRADE_ARRAY_LEN)
{
printf("Enter grade, (Type <0 or >100 to quit): ");
if(scanf("%lf", &grade) != 1)
{
printf("The value entered could not be converted to double. Please enter another value.\n");
scanf("%s");
continue;
}
if(grade < 0.0 || grade > 100.0)
{
return 1;
}
else
{
if(i == 0)
{
max = grade;
min = grade;
}
else
{
if(grade > max)
{
max = grade;
}
if(grade < min)
{
min = grade;
}
}
grades[i]= grade;
i++;
}
}
double sum = 0;
for(i=0; i<GRADE_ARRAY_LEN; i++)
{
printf("Grade %d is %lg \n", i+1, grades[i]);
sum+=grades[i];
}
double avg = sum/GRADE_ARRAY_LEN;
printf("The average of the %d grades is %g \n", GRADE_ARRAY_LEN, avg);
printf("The Minimum Grade is %lg\n",min);
printf("The Maximum Grade is %lg\n", max);
printf("Number of grades is %d\n", GRADE_ARRAY_LEN);
printf("Sum is %lg\n", sum);
printf("Average is %lg\n", avg);
return 0;
}
I may have missed something, but i checked it and it works.
The - How it works is a bit long.
First of all the amount of grades you want to enter is fixed and defined in #define GRADE_ARRAY_LEN 10 which lets you easily change the number of grades you want to enter.
Then the programm reads input and checks if the input is double or can be converted to double. This check is simple if(scanf("%lf", &grade) != 1). scanf() returns the number of arguments successfully filled, the format "%lf" means that you want your input argument to be filled as double. So scanf("%lf", &grade) will return only return a value which equals to 1, if you entered a value that can be converted to double.
Now if the input IS NOT double or double or can be converted to double the program askes you to enter an input which is double or can be converted to double. scanf("%s"); is actully needed because when scanf("%lf", &grade) fails there is a newline char left in the input stream, which you have to actually read. If you don't, next scanf("%lf", &grade) will actually take it as an input, and fail again, thus creating an infinite loop.
After the input is successfully filled, it means you have your value of grade. The program checks what value was entered, and exits if the value is smaller than 0 or greater than 100. I did this because printf actually outputs, that the program will exit if the value is smaller than 0 or greater than 100.
If the value of grade is between 0 and 100, then the program checks if it is the first value that was scanned with this if(i == 0). Where i is the number of successfully scanned values. If i == 0 than no values were scanned yet, so max and min must be initialized with this value for max and min to work correctly., because all other values have to be checked against the first value. If i != 0, then the value is checked against max an min, and they are modified in case of need.
After min and max are checked the value is FINALLY added to our array of values and the number of successfully scanned values is increased.
i++;grades[i]= grade;
i++;
NOTE!!!: all the operations above are commited in one single loop, while(i<GRADE_ARRAY_LEN). This ensures that you enter the correct amount of values and get the correct max and min values. You do not actually need extra loops to get correct min and max values.
After the loop, the sum of grades is counted. After that, the avg of grades is counted.
NOTE!!!: You do not need any checks here because the loop ensures that you enter correct amount of elemets.
In the end the results are printed to a command line.
I'll try to point out the main parts that i edited.
First: variable declarations must be inside the brakets of main() and main must return an int, which means your code had this:
float main()
int i;
float grades[10];
float grade;
float sum;
float avg;
float count;
float max;
float min;
{
but it must be like this
int main()
{
int i = 0;
double grades[GRADE_ARRAY_LEN];
double grade;
double max;
double min;
Second: Your code did not check if scanf("%lf", &grade) successfully filled grade. That is wrong because you can actually enter any combination of characters and numbers in command line, but the only correct input is when you enter a number, that can be converted to double. That means you have to check what scanf returns.
Third: max = 0; and min = 0; is not the correct way to initialize max and min values. min=0; is incorrect, because in case of only positive grades, grade will never be smaller than min, thus min will be always 0. The correct way is to initialize min value is with the first correctly read grade from input, so if there is a smaller value is entered, then min can be changed accordinly. The max=0; is incorrect because in case of only negative grades, grade will never be greater than max, thus max will be always 0. The correct way is to initialize max value is with the first correctly read grade from input, so if there is a greater value is entered, then max can be changed accordinly.
Third: As i said above, you do not actually need a separate loop to find max and min values. It can be done inside the loop where data is read. It is not really nececcary, but it's a good practice to do everything you can inside one loop.
Fourth: It is a good practice to define lenght of arrays with fixed length before main function using #define. Quote: "The #define creates a macro, which is the association of an identifier or parameterized identifier with a token string. After the macro is defined, the compiler can substitute the token string for each occurrence of the identifier in the source file.". That basically means that you add #define GRADE_ARRAY_LEN 10, as shown in code above, before main, and then instead of using 10 as the number of iterations, and number of array elements like double grades[10]; while(i<10); for(i=0;i<10;i++)
you actually use double grades[GRADE_ARRAY_LEN]; while(i<GRADE_ARRAY_LEN); for(i=0;i<GRADE_ARRAY_LEN;i++). The compiler will automaticly substitute GRADE_ARRAY_LEN for 10; Thsi enables you to change 10 for any other number you want (positive of course) only in one place, instead of changing it in several places;
Fifth: printf("Enter grade, (Type <0 or >100 to quit): ") outputs that if you type a value <0 or >100 the program should exit. Considering the input values were not checked at all, this is not happening.
Sixth: while(grades>0 && i<10) is wrong, because grades is an Array, and you can not compare an array to a single number.
Now on to what i actually did to the code to make it work:
1) Moved the var declarations and changed the return value of main
2) Implemented a check for successfull filling of grade by scanf("%lf", &grade).
3) Implemented a program exit in case if input is <0 or >100;. This means the program will actuallly exit if you enter a number smaller than 0 and greater than 100
4) Implemented a #define GRADE_ARRAY_LEN 10 to use as a length of grade array
5) Re-made the loop so it will ask to enter correct input data GRADE_ARRAY_LEN times. Now the program won't continue unless you enter correct input data exactly GRADE_ARRAY_LEN times.
6) Moved the finding of min and max values to the while loop. As said above, you do not actually need a separate loop to find them. Also modified the initialization of min and max
7) Due to changes above, made some changes in the end.
7.1) Changed a little the way sum is counted
Was:
for(i=0;i<count; i++)
{sum= sum + grades[i];}
Now:
double sum = 0;
for(i=0; i<GRADE_ARRAY_LEN; i++)
{
printf("Grade %d is %lg \n", i+1, grades[i]);
sum+=grades[i];
}
7.2) Removed unnecessary check upon calculating avg
Was:
if(count>0)
{avg=sum/count;}
else
{avg=0;}
Now:
double avg = sum/GRADE_ARRAY_LEN;
8) Changed all float values to double. The amount of bytes float allocates for a var is actually dependant on system architecture, where double is actually an Quote: "IEEE 754 double-precision binary floating-point format: binary64".
9) Due to changes above, changed format of the input data from %f to %lf, Changed format of output data from %f to %lg. Now both can work with double.
Replacing this:
double min;
while(i<GRADE_ARRAY_LEN)
{
.......
printf("The value entered could not be converted to double. Please enter another value.\n");
scanf("%s");
With this:
double min;
char c;
while(i<GRADE_ARRAY_LEN)
{
.......
printf("The value entered could not be converted to double. Please enter another value.\n");
scanf("%s", &c);
Should fix the scanf error. The second error is probably because you forgot to copy the closing braket - "}" of main at the very end. What i mean is that you probably have this at the very end:
printf("Average is %lg\n", avg);
return 0;
But!!! it shold be like this
printf("Average is %lg\n", avg);
return 0;
} // !!!!

Minmax numbers array

This program gets 5 numbers only from the user then
Store them in an array. Get the min, max, and the average of the numbers inputted. Here's the code I made:
#include <stdio.h>
#include <conio.h>
int main()
{
int num[5];
int min, max=0;
int counter;
float average, total;
max = num[0];
min = num[2];
for(counter=0; counter<=4; counter++)
{
printf("Enter a number: ");
scanf("%d", &num[counter]);
if(num[counter]>max)
{
max = num[counter];
}
if (num[counter]<min)
{
min = num[counter];
}
}
total = max+min;
average = total/2;
printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min);
printf("The average is: %d", average);
getch();
return 0;
}
FInally fixed my error with the min and max and now I'm having trouble with the average. I should only get the average of the min and max numbers but it keeps on showing an average of zero. Can someone help? Thankkyouuu.
//get memory address and store value in it.
void getValue(int *ptr)
{
printf("Enter a number: ");
scanf("%d", ptr);
}
int main()
{
//initialized n=5 as per your requirement. You can even get the value at run time.
int min, max, counter,n=5;
int num[n];
float average,total;
getValue(num); //get num[0]
min=max=total=num[0]; //Initialize min,max,total with num[0]
for(counter=1; counter<n; counter++)
{
getValue(num+counter); //get num[counter]
num[counter]>max?max = num[counter]:max; //find max
num[counter]<min?min = num[counter]:min; //find min
total+=num[counter]; // total = total + num[counter]
}
average = total/n;
printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min);
printf("The total is: %f\n", total);
printf("The average is: %f\n", average);
return 0;
}
Your calculation of average is wrong; you need to use total/num (remember use float):
total += num[counter];
max and min were incorrectly initialized: num[0], num[2] may be anything when you initialize them.
Aside from your calculation of average being wrong (it's not just total/2), you need to use the correct format specifier in the printf:
printf("The average is: %g", average);
You are using %d which tells printf to expect an integer, but you're giving it a float.
1 Min and max should be initialized
int min = INT_MAX;
int max = INT_MIN;
2 You need to keep a running total of your numbers
int total = 0;
...
// inside loop
scanf("%d", &num[counter]);
total += num[counter];
3 At the end print the average, recommend going to floating point.
printf("The average is: %.1f", (double)total/counter);

Resources