Learn about Find Sum & average in Range using Pointer & Function in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.
Contents
C program to find Sum & average in Range using Pointer & Function
User-defined function calculate() is defined to calculate sum and average and pointers are assigned to variables declared. Hence , pointers are passed as parameters to function.
#include<stdio.h>
double calculate(int *m, int *n, double *sum, double *avg);
int main()
{
int m, n;
int *pm, *pn;
pm= &m, pn= &n;
double sum=0.0, avg;
double *psum, *pavg;
psum= &sum, pavg= &avg;
printf("Enter m & n Values(m<n): ");
scanf("%d %d", pm, pn);
calculate(pm, pn, psum, pavg);
printf("Sum= %.2lf and average= %.2lf\n", *psum, *pavg);
return 0;
}
double calculate(int *m, int *n, double *sum, double *avg)
{
int i;
for(i=*m; i<=*n; i++)
{
*sum += i;
}
*avg = (*sum) / (*n -*m + 1);
}
Output:
Enter m & n Values(m<n): 40 50
Sum= 495.00 and average= 45.00
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Codes :
C Program to Find Sum and average in Range using Pointer
C Program to Check Odd-Even using Pointer