Reputation: 55
The code below is from a c programming tutorial book. The purpose is to find the average of 10 floating-point value.
#include <stdio.h>
void avg(double *d, int num);
int main(void)
{
double nums[]={1.0,2.0,3.0,4.0,5.0,
6.0,7.0,8.0,9.0,10.0}
avg(nums,10);
return 0;
}
void avg(double *d, int num)
{
double sum;
int temp;
temp=num-1;
for(sum=0;temp>=0;temp--)
sum=sum+d[temp];
printf("Average is %f", sum/(double)num);
}
What happens when d[temp] is used in line 23.
Upvotes: 0
Views: 179
Reputation: 3870
sum=sum+d[temp]
Where you are accessing every temp
th element of double array d
.
If you are having 3 numbers
temp=num-1; // temp =2
for(sum=0;temp>=0;temp--)
sum=sum+d[temp];
will expand to-
sum=0+d[2]; then temp becomes 1 // you are adding 2nd element with sum
sum=sum+d[1]; then temp becomes 0 // here you are adding with previous result // First element + sum
sum=sum+d[0]; then temp becomes -1 // condition fails // 0th element + sum
It is simply-
sum=d[2]+d[1]+d[0];
Upvotes: 1
Reputation: 27210
In line 23
d[temp]
will get the float data of the index with
temp
in nums
array,
In another term d[temp]
will replace with the temp + 1
th element of nums
array.
Upvotes: 0
Reputation: 316
You iterate over your nums[]-Array and on this line, you add all values to your some variable. d[temp] access the value of the item on index temp.
Upvotes: 0
Reputation: 6578
d[temp]
means to access the temp
th element of the array pointed to by d
. I.e. d
points to an array of at least temp+1
double
s, and you wish to retrieve the temp
th of those.
Upvotes: 1