Recently I was learning about arrays passing to functions (by passing their base address to a pointer defined as parameter in function and then using pointer arithmetic for extracting the whole array subsequently)
For practice I was asked to calculate the average marks of a class of 70 students with their marks listed in an array named "marks" and was asked to define a variable with parameter as a pointer and calculate average from there.
The data given to me was that student 1 scored 40 , student 2 scored 41, student 3 scored 42....and so on.
Here is my attempt at it:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
float average(int *b)
{
int sum = 0;
for (int i = 1; i <= 70; i++)
{
sum = sum + *b;
b = b + 1;
}
printf("the value of sum is %d\n", sum); // this value is changing every time I run the program
return (((float)sum) / 70);
}
int main()
{
int marks[70];
marks[0] = 40;
for (int i = 0; i < 68; i++)
{
marks[i + 1] = marks[i] + 1;
}
printf("the value of marks of 10th child is %d\n", marks[9]); // Just for checking if I am correct!(yes! the ans does come out to be 49!)
printf("the value of average marks of the class is %f\n", average(&marks[0]));
return 0;
}
to my surprise the value kept changing every time I ran it. Can anyone give a hint where am I wrong?