I'm trying to add the elements in an array. It's just a simple program to calculate the average of student grades. I know this is probably a rudimentary way to code this, I'm looking to do it more efficiently. However my code is not returning the average. I would greatly appreciate any help. I did try this with a for loop but got the same incorrect answer.
#include <stdio.h>
int main()
{
int grades[6];
int average;
int sum = 0;
printf("Please enter your five test scores:\n");
scanf("%d", &grades[0]);
scanf("%d", &grades[1]);
scanf("%d", &grades[2]);
scanf("%d", &grades[3]);
scanf("%d", &grades[4]);
scanf("%d", &grades[5]);
sum = sum + grades[6];
average = sum / 5;
printf("The average of the students test scores is %d:\n", average);
return 0;
}
You should sum all grades and then divide by their amount (in your case it is 6 not 5, because grades array has 6 elements). Here is a code sample:
#include <stdio.h>
int main()
{
int grades[6];
int average;
int sum = 0;
printf("Please enter your six test scores:\n");
scanf("%d", &grades[0]);
scanf("%d", &grades[1]);
scanf("%d", &grades[2]);
scanf("%d", &grades[3]);
scanf("%d", &grades[4]);
scanf("%d", &grades[5]);
for (int i = 0; i < 6; i++)
sum = sum + grades[i];
average = sum / 6;
printf("The average of the students test scores is %d:\n", average);
return 0;
}
I'm trying to add the elements in an array.
This is maybe already a wrong track regarding the title (and the code) where it is about averaging elements in an array.
How you build the array is up to you; I choose the simplest way. An important decisions is: is size of array and number of values the same? That is what n_grades does. The four zeroes in the array initialization illustrate the difference.
An average most likely should be a floating point number.
A nasty problem with averages is the lurking overflow. Very unlikely in this setting, but there is a more robust (and elegant) algorithm. The (double) cast is the un-elegant part, but is needed because the division is between two integers. Still this is the compact core:
for (i = 0; i < n_grades; i++)
aver += (double) grades[i] / n_grades;
corresponding to the math formula:
i<n
A = Sum G_i/n
i=0
("Sum" is the big Sigma)
#include <stdio.h>
int main()
{
int grades[] = {10,10,9,10,11,11,0,0,0,0};
int n_grades = sizeof grades / sizeof*grades; // use all elements
//n_grades = 6; // use only first n elements
double aver = 0;
for (int i = 0; i < n_grades; i++)
aver += (double) grades[i] / n_grades;
printf("The average of the students test scores is %f (n= %d):\n",
aver, n_grades);
return 0;
}
Now it prints:
The average of the students test scores is 6.100000 (n= 10):
or, uncommented, i.e. limited to 6 grades::
The average of the students test scores is 10.166667 (n= 6):
You're assuming that grades[6] holds the sum of all the values in the grades array, which is wrong of course.
You need something like:
for (int i = 0; i < 6; i++)
sum = sum + grades[i];
Related
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 );
The for loop I wrote to calculate sum of numbers is not working properly.
The program finds the average of the given numbers using a dynamically allocated array.
#include<stdio.h>
main()
{
int no_of_nos;
printf("Enter the number of numbers yuo want to do average : ");
scanf("%d",&no_of_nos);
int x[no_of_nos+1];
int i;
for(i=0;i<no_of_nos;i+=1)
{
printf("Enter the values for the element of the array : ");
scanf("%d",&x[i]);
}
int sum=0,j;
for(j=0;j<no_of_nos;j++)
{
sum = x[j] + x[j+1];
}
printf("The sum of the given numbers = %d \n",sum);
float average = sum / no_of_nos;
printf("The average of the given numbers = %0.2f",average);
}
Your second loop is wrong, it should read:
for( i=0; i<no_of_nos; i++ ) {
sum += x[i];
}
No need for another integer, 'i' will do fine. You could optimise it further by moving the sum up before the first loop then totalise sum as you enter the values. Do you need the array?
int sum = 0;
for( int i=0; i<no_of_nos; i++ ) {
int x;
printf("Enter the values for the element of the array : ");
scanf("%d", x);
sum += x;
}
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
There is no sense to declare the array x with no_of_nos+1 elements instead of no_of_nos elements. So the declaration of the array should look like
int x[no_of_nos];
In fact an array is not required if you need only to calculate the average of entered numbers.
It is better initially to declare the variable sum as having type float or double. Otherwise this expression statement
float average = sum / no_of_nos;
does not make a great sense because the expression sum / no_of_nos evaluates as an integer expression that is in any case the result of the expression is an integer.
However if the variable sum declared like for example float then the expression sum / no_of_nos will have the type float.
For example
float sum = 0;
//...
float average = sum / no_of_nos;
Compare two outputs of the average in the following demonstrative program.
#include <stdio.h>
#define N 2
int main(void)
{
int a[N] = { 1, 2 };
int sum1 = 0;
for ( size_t i = 0; i < N; i++ ) sum1 += a[i];
float average = sum1 / N;
printf( "The first average is equal to %0.2f\n", average );
float sum2 = 0;
for ( size_t i = 0; i < N; i++ ) sum2 += a[i];
average = sum2 / N;
printf( "The second average is equal to %0.2f\n", average );
return 0;
}
The program ooutput is
The first average is equal to 1.00
The second average is equal to 1.50
This loop
for(j=0;j<no_of_nos;j++)
{
sum = x[j] + x[j+1];
}
also does not make sense. It is enough to write
for(j=0;j<no_of_nos;j++)
{
sum += x[j];
}
The program to calculate the Average of given numbers can be written without the use of arrays.
The following program finds the average of given numbers and gives the answer upto two decimal places:
#include<stdio.h>
main()
{
int n,i=0,j;
float sum=0;
printf("Enter the number of elements : ");
scanf("%d",&n);
for(;i<n;i++)
{
printf("Enter the number : ");
scanf("%d",&j);
sum = sum + j;
}
printf("The sum of the given numbers = %0.2f \n",sum);
float average = sum / n;
printf("The Average of the given numbers = %0.2f",average);
}
#include <stdio.h>
#include <conio.h>
int getn(int n, int i);
int main()
{
int n, i;
getn(n, i);
getch();
return 0;
}
int getn(int n, int i)
{
int even = 0;
int odd = 1;
int avg;
printf("Enter ten integers: \n");
for (i = 1 ; i <= 10 ; i++)
{
printf("Integer %d: ", i);
scanf("%d", &n);
if ( n % 2 == 0 )
{
even = even + n;
}
else
{
odd = odd * n;
}
}
avg = even / 10;
printf("\n\nAverage of even numbers: %d", avg);
printf("\nProduct of odd numbers: %d", odd);
}
It seems the even calculations worked but when it comes to odd it gives the wrong answer. Please help
Our instructor wants us to use looping or iterations. No arrays. Please help me
First, your C code needs some correction:
at least give the prototype of getn before using it
getn is defined to return an int and doesn't return anything. Either replace int with void or return a value.
Second,
Your code computes the product of ten numbers, if this product is too big, it cannot be store as-is in an int. For example, it works well if you enter ten times number 3, the result is 59049, but if you enter ten times number 23, it will answer 1551643729 which is wrong because 23^10=41426511213649 but that can't be stored in an int. This is known as arithmetic overflow.
Your average is bad, because you sum ints, but the average is (in general) a rational number (average(2,3)=2.5 isn't it ?). So double avg = out/10.0; (means compute a floating division) and printf("Average %f\n",avg); would be better.
disclaimer: I'm new to programming
I'm working on this problem
so far ive written this which takes user inputs and calculates an average based on them
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
I'd like the user to enter -1 to indicate that they are done entering data; I can't figure out how to do that. so if possible can someone explain or give me an idea as to how to do it
Thank you!
#include <stdio.h>
int main()
{
int i = 0;
float num[100], sum = 0.0, average;
float x = 0.0;
while(1) {
printf("%d. Enter number: ", i+1);
scanf("%f", &x);
if(x == -1)
break;
num[i] = x;
sum += num[i];
i++;
}
average = sum / i;
printf("\n Average = %.2f", average);
return 0;
}
There is no need for the array num[] if you don't want the data to be used later.
Hope this will help.!!
You just need the average. No need to store all the entered numbers for that.
You just need the number inputs before the -1 stored in a variable, say count which is incremented upon each iteration of the loop and a variable like sum to hold the sum of all numbers entered so far.
In your program, you have not initialised n before using it. n has only garbage whose value in indeterminate.
You don't even need the average variable for that. You can just print out sum/count while printing the average.
Do
int count=0;
float num, sum = 0;
while(scanf("%f", &num)==1 && num!=-1)
{
count++;
sum += num;
}
to stop reading at -1.
There is no need to declare an array to store entered numbers. All you need is to check whether next entered number is equal to -1 and if not then to add it to the sum.
Pay attention to that according to the assignment the user has to enter integer numbers. The average can be calculated as an integer number or as a float number.
The program can look the following way
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int sum = 0;
printf("Enter a sequence of positive numbers (-1 - exit): ");
for (unsigned int num; scanf("%u", &num) == 1 && num != -1; )
{
++n;
sum += num;
}
if (n)
{
printf("\nAverage = %llu\n", sum / n);
}
else
{
puts("You did not eneter a number. Try next time.");
}
return 0;
}
The program output might look like
Enter a sequence of positive numbers (-1 - exit): 1 2 3 4 5 6 7 8 9 10 -1
Average = 5
If you need to calculate the average as a float number then just declare the variable sum as having the type double and use the corresponding format specifier in the printf statement to output the average.
I am passing an array of exam grades to the examAverage function along with the size of the array. When I printf the array contents in the for loop they are correct, but when they are added together the sum is wrong. Even if I printf immediately after I set double sum = 0, it says sum = 2. By the time the function is complete I get an extremely large number. Any help is appreciated.
double examAverage(int arr[], int size){
int i;
double exAvg=0;
double sum =0;
printf("Sum = %d\n", sum);
for (i = 0; i < size; ++i)
{
printf("Sum = %d\n", sum);
sum = arr[i];
}
exAvg = sum / size;
return exAvg;
}
Main
double examAverage(int arr[], int size);
printf("How many exam grades would you like to enter?\n");
scanf("%d", &examGrad);
int exams[examGrad];
printf("Enter exam grades \n");
for(int i=0; i<sizeof(exams)/sizeof(exams[0]); i++){
scanf("%d", &exams[i]);
}
double exAvg;
exAvg= examAverage(exams, examGrad);
printf("Exam average = %d", exAvg);
Output
How many exam grades to enter?
2
Enter exam grades
100
50
Sum = 2
Sum = 10
Sum = 1079574528
Exam Average = 1081159680
Don't You mean sum += arr[i]; in the for loop in examAverage?
Also, Your code labeled Main is not really valid at all, first, there is no declaration of examGrad, second the function declaration at the top does whoever knows what, third, sizeofs in the for loop can be replaced by the examGrad, the %d was already mentioned.
If You ask questions about simple code just include all of it, If it is too much, cut out the unnecessary parts or ensure us that they are there, otherwise we don't know if the problem is the missing code or not.
Do not use %d to print a double; that is for integers. Use %f. The different way in which integers and floating point numbers are stored accounts for the problems that you are seeing.
You should have seen a warning about this when you compiled, along the lines of:
format specifies type 'int' but the argument has type 'double'