In the code shown below, what does the "average /=5.0" mean? - c

In the code shown below, what does average /= 5.0 mean? What is it implying? This is for C language. I am using this code to find out the average marks obtained in 2 subjects denoted as i and j.
#include <stdio.h>
int main()
{
int grades[2][5];
float average;
int i;
int j;
grades[0][0]=98;
grades[0][1]=98;
grades[0][2]=98;
grades[0][3]=88;
grades[0][4]=98;
grades[1][0]=98;
grades[1][1]=98;
grades[1][2]=98;
grades[1][3]=98;
grades[1][4]=98;
for (i = 0; i < 2; i ++)
{
average = 0;
for (j = 0; j < 5; j ++)
{
average += grades[i][j];
}
average /= 5.0;
printf("The average of subject %d is: %.2f\n", i, average);
}
}

This is a shortcut for average = average / 5.0;.
You can do the same for many operations:
average += 5.0; is the same as average = average + 5.0;
average -= 5.0; is the same as average = average - 5.0;
average *= 5.0; is the same as average = average * 5.0;
These are called compound assignment operators.

Related

Average for each three consecutive numbers in an array

How can I calculate the average for each three consecutive numbers in an array and then to print each result? (in C)
I tried to do this.
#include <stdio.h>
int main() {
int n,v[100],i;
float average;
int sum=0;
scanf("%d",&n);
for (i = 0; i < n; ++i) {
scanf("%d",&v[i]);
}
for(i=0;i<n;i+=3) {
sum=v[i]+v[i+1]+v[i+3];
average=sum/3;
printf("%.2f ", average);
}
return 0;
}
sum/3 is an int division with an int quotient.
To also have a fractional part, use floating point division.
// average=sum/3;
average = sum / 3.0f;
for(i=0;i<n;i+=3) { sum=v[i]+v[i+1]+v[i+3]; risks accessing data out of v[] bounds. v[i]+v[i+1]+v[i+3] are not consecutive. I'd expect v[i]+v[i+1]+v[i+2]
for (i = 0; i + 2 < n; i += 3) {
sum = v[i] + v[i+1] + v[i+2];
No good reason to use float. Use double unless float is needed for space/ maybe speed, etc.
Also avoid overflow and precision loss.
for(int i = 0; i+2 < n; i += 3) {
double sum = 0.0 + v[i] + v[i+1] + v[i+2]; // Addition here uses FP math.
double average = sum/3.0;
printf("%.2f ", average);
}
Better code writes a '\n' at the end and does not end with a dangling " ".
const char *separator = "";
for(int i = 0; i+2 < n; i += 3) {
...
printf("%s%.2f ", separator, average);
separator = " ";
}
printf("\n");

The precision of a large floating point sum

I am trying to sum a sorted array of positive decreasing floating points. I have seen that the best way to sum them is to start adding up numbers from lowest to highest. I wrote this code to have an example of that, however, the sum that starts on the highest number is more precise. Why? (of course, the sum 1/k^2 should be f=1.644934066848226).
#include <stdio.h>
#include <math.h>
int main() {
double sum = 0;
int n;
int e = 0;
double r = 0;
double f = 1.644934066848226;
double x, y, c, b;
double sum2 = 0;
printf("introduce n\n");
scanf("%d", &n);
double terms[n];
y = 1;
while (e < n) {
x = 1 / ((y) * (y));
terms[e] = x;
sum = sum + x;
y++;
e++;
}
y = y - 1;
e = e - 1;
while (e != -1) {
b = 1 / ((y) * (y));
sum2 = sum2 + b;
e--;
y--;
}
printf("sum from biggest to smallest is %.16f\n", sum);
printf("and its error %.16f\n", f - sum);
printf("sum from smallest to biggest is %.16f\n", sum2);
printf("and its error %.16f\n", f - sum2);
return 0;
}
Your code creates an array double terms[n]; on the stack, and this puts a hard limit on the number of iterations that can be performed before your program crashes.
But you don't even fetch anything from this array, so there's no reason to have it there at all. I altered your code to get rid of terms[]:
#include <stdio.h>
int main() {
double pi2over6 = 1.644934066848226;
double sum = 0.0, sum2 = 0.0;
double y;
int i, n;
printf("Enter number of iterations:\n");
scanf("%d", &n);
y = 1.0;
for (i = 0; i < n; i++) {
sum += 1.0 / (y * y);
y += 1.0;
}
for (i = 0; i < n; i++) {
y -= 1.0;
sum2 += 1.0 / (y * y);
}
printf("sum from biggest to smallest is %.16f\n", sum);
printf("and its error %.16f\n", pi2over6 - sum);
printf("sum from smallest to biggest is %.16f\n", sum2);
printf("and its error %.16f\n", pi2over6 - sum2);
return 0;
}
When this is run with, say, a billion iterations, the smallest-first approach is considerably more accurate:
Enter number of iterations:
1000000000
sum from biggest to smallest is 1.6449340578345750
and its error 0.0000000090136509
sum from smallest to biggest is 1.6449340658482263
and its error 0.0000000009999996
When you add two floating-point numbers with different orders of magnitude, the lower order bits of the smallest number are lost.
When you sum from smallest to largest, the partial sums grow like Σ1/k² for k from N to n, i.e. approximately 1/n-1/N (in blue), to be compared to 1/n².
When you sum from largest to smallest, the partial sums grow like Σ1/k² for k from n to N, which is about π²/6-1/n (in green) to be compared to 1/n².
It is clear that the second case results in many more bit losses.

Finding the average of an array using c [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am new to coding in C and I am trying to get the average of the array but for some reason it is not calculating, it is giving me a result of 0.0.
How can I fix this. Thanks
#include <stdio.h>
float grades_average(float grades[7]);
int main() {
float grades[7]={98.8, 97.9, 99.3, 99.8, 99.6, 99.4, 99.9};
float average;
average = grades_average(grades);
printf("Average is: %.2f",average);
return 1;
}
float grades_average(float grades[7]){
int i;
float sum = 0;
float average = 0.0;
/* calculate the sum of grades using for loop*/
for(i = 0; i <= 7; i++){
sum = sum + grades[7];
}
average = sum/7;
return average;
}
The output is:
Average is: 0.00
Minimum change solution:
float grades_average(float grades[7]){
int i;
float sum = 0;
float average = 0.0;
/* calculate the sum of grades using for loop*/
for(i = 0; i < 7; i++){
sum = sum + grades[i];
}
average = sum/7.f;
return average;
}
Change for(i = 0; i <= 7; i++){ to for(i = 0; i < 7; i++){. Valid indicies for grades are only 0-6. 7 is out of bounds.
Change sum = sum + grades[7]; to sum = sum + grades[i]; You need to check each element, not the (beyond) last one over and over.
Change average = sum/7; to average = sum/7.f; The .f ensures no integer division. That preserves the decimal during division.
I hope that helps!
Here is full code. with 2 changes, Line 20 and Line 23
#include <stdio.h>
float grades_average(float grades[7]);
int main() {
float grades[7]={98.8, 97.9, 99.3, 99.8, 99.6, 99.4, 99.9};
float average;
average = grades_average(grades);
printf("Average is: %.2f",average);
return 1;
}
float grades_average(float grades[7]){
int i;
float sum = 0;
float average = 0.0;
/* calculate the sum of grades using for loop*/
/*Changed here to <7 because i takes 0,1,2,3,4,5,6 which are 7 elements, your code is <=7 which takes 0.......7 which are 8 elements */
for(i = 0; i < 7; i++){
/*Changed here to i from 7, your code everytime sums out of bound element, Garbage value since grades[7] does not exist*/
sum = sum + grades[i];
}
average = sum/7;
return average;
}
Change for(i = 0; i <= 7; i++){} to for(i = 0; i < 7; i++){}, because
totally you have 7 elements, starting from 0to6.
Change sum = sum + grades[7]; to sum = sum + grades[i];, as grades[7] will only have the last value of the array, but you want to add all the values present in the array.
include
float grades_average(float grades[7]);
int main() {
float grades[7]={98.8, 97.9, 99.3, 99.8, 99.6, 99.4, 99.9};
float average;
average = grades_average(grades);
printf("Average is: %.2f",average);
return 1;
}
float grades_average(float grades[7]){
int i;
float sum = 0;
float average = 0.0;
/* calculate the sum of grades using for loop*/
for(i = 0; i < 7; i++){
sum = sum + grades[i];
}
average = sum/7.f;
return average;
}
Hope that helps..
Try by putting i in place of 7,
sum = sum + grades[7];
like
sum = sum + grades[i];
and your loop from 0 to 6
In place of using this
sum = sum + grades[7];
Use
sum = sum + grades[i];
Then it will work.

Array additions and averages

So this weeks homework is to: 'Write a program that inputs 6 integers and puts them into an Array. The program
then prints out the following: A list of all Array elements, from 0 to 5 and the sum and
mean value of all elements. NB The mean value of the array elements will not
necessarily be an integer. In order to convert an integer into a real (float) use
casting:
To turn the integer ‘x’ into a float use float(x)
E.g.:
Average = float(sum)/number of elements ;
(In this case the number of elements is 6)'
Not quite sure what I am doing wrong here but my code seems to give back incorrect answers and I can't figure out why.
Any suggestions would be greatly appreciated. I feel like I am going to fail this module as I have struggled with it since the introduction of functions, etc.
Anyway, here is my code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main() {
int numArr[5];
int i, sum = 0;
float avg;
printf("\nEnter 6 elements : \n");
for (i = 0; i < 6; i++)
scanf("%d", &numArr[i]);
for (i = 0; i < 6; i++) {
sum = sum + i;
}
avg = sum /6;
printf("The sum is : %d", sum);
printf("The mean value is : %f", avg);
return 0;
}
'Write a program that inputs 6 integers
int numArr[5];
^^^^^
Change this loop
for (i = 0; i < 6; i++) {
sum = sum + i;
}
like
for (i = 0; i < 6; i++) {
sum = sum + numArr[I];
}
And change this statement
avg = sum /6;
the following way
avg = ( float )sum /6;
And you forgot to output all elements of the array.
Take into account that according to the C Standard the function main without parameters shall be declared like
int main( void )
and you may remove header <math.h> because neither declaration is used from this header in your program.
Your array isn't large enough to hold 6 numbers.
Change
int numArr[5];
to
int numArr[6];
Currently, you are accessing the array out-of-bunds, resulting in undefined behaviour.
There are couple other problems too:
1) You are not summing the array elements
2) You are doing integer division
Fix it, it'd look like:
#include<stdio.h>
#include<math.h>
int main(void) {
int numArr[6];
int i, sum = 0;
float avg;
printf("\nEnter 6 elements : \n");
for (i = 0; i < 6; i++)
scanf("%d", &numArr[i]);
for (i = 0; i < 6; i++) {
sum = sum + numArr[i]; /* was summing `i` instead of numArr[i] */
}
avg = sum /6.0; /* was doing integer division */
printf("The sum is : %d", sum);
printf("The mean value is : %f", avg);
return 0;
}
sum = sum + i;
should be
sum = sum + numArr[i];
Array elements should be added.
Later
avg = sum/6.0
for (i = 0; i < 6; i++) {
sum = sum + numArr[i];
}
avg = (float)sum /6;
Notice numArr[i]
int numArr[5];
should be
int numArr[6];
and
for (i = 0; i < 6; i++) {
sum = sum + i;
}
should be
for (i = 0; i < 6; i++) {
sum = sum + numArr[i];
}
and
avg = sum /6;
should be
avg = sum/6.0 //because division of integer by an integer results by integer value. So we divide integer with a float (6.0) value

Why is my product cost average coming out at 0?

//Program Written By: Andre Chitsaz-zadeh
//Program Written On: 10/7/12
//Program calculates book cost for multiple book orders.
//Program written using multiple functions.
#include <stdio.h>
#define SIZE 5
void inputData();
void processingData(float costs[]);
float costs[5];
float sortedCosts[5];
int main()
{
inputData();
processingData(costs);
}
void inputData()
{
int i = 0;
printf("\nPlease enter five products costs.\n");
while (i < 5)
{
scanf("%d", &costs[i]);
i = i + 1;
}
}
void processingData(float costs[])
{
int i;
int j;
float sum = 0.00f;
float average = 0.00f;
for (i = 0; i < 4; ++i)
{
int j, min, temp;
min = i;
for (j = i + 1; j < 5; ++j)
if (costs[j] < costs[min])
min = j;
temp = costs[i];
costs[i] = costs[min];
costs[min] = temp;
}
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
sortedCosts[i] = costs[i];
for (i = 0; i < 5; ++i)
sum += costs[i];
average = sum / 5;
printf("Product Cost Average = %.2f\n", average);
}
Why is my product cost average coming out as zero? As far as I can see all of my variables are declared as float? I have tried all sorts of combinations and I cant seem to get it to work. I really appreciate your help!
scanf("%d", &costs[i]);
cost[i] is of type float in your program not int.
Use %f conversion specification to read a float.
Also:
temp = costs[i];
Your temp value is of type int but costs[i] is of type float. I don't think it is deliberate.
Use the "%f" modifier in scanf to get a float, rather than "%d".
Also, you
#define SIZE 5
but you use 5's throughout your code rather than SIZE. Use SIZE to reduce the possibility of bugs.
There's nothing wrong with
i = i + 1;
but that is much more commonly written as
i++;

Resources