C Program to Find Sum and average in Range using Pointer

In this article, we are going to learn how to find Sum and average in a given Range of numbers using Pointer in C language with examples. First, we will ask the user to enter the range from where to where.

1. C Program to Find Sum and average in Range using Pointer


In this example, we are asking users to provide the range from where to where. Once the user will provide this range we will iterate over this range and add the numbers to find the sum. Using this sum then we will calculate the average.

#include<stdio.h>

int main()
{
  int startRange, endRange;
  int *ptrstartRange, *ptrendRange;

  ptrstartRange = &startRange;
  ptrendRange = &endRange;

  double Sum, Average;

  double *ptrSum;
  double *ptrAverage;

  ptrSum = &Sum;
  ptrAverage = &Average;

  printf("Please enter the range (startRange < endRange): ");
  scanf("%d %d", ptrstartRange, ptrendRange);

  for(int i= startRange ; i<=endRange ; i++)
  {
    *ptrSum += i;
  }

  *ptrAverage = (*ptrSum) / (*ptrendRange - *ptrstartRange + 1);

  printf("The Sum of Numbers within the range is = %.2lf ", *ptrSum);
  printf("\nThe Average of the Numbers within the Range is = %.2lf", *ptrAverage);

  return 0;
}

Output

Please enter the range (startRange < endRange): 5
10
The Sum of Numbers within the range is = 45.00  
The Average of the Numbers within the Range is = 7.50

2. Find Sum & average in Range using Pointer & Function


In this example, we are just making a function that will compute the sum and average for us. It will return the sum and average values to the calling function to display the results.

#include<stdio.h>

double calSumAndAverage(int *m, int *n, double *sum, double *avg);

int main()
{
  int startRange, endRange;
  int *ptrstartRange, *ptrendRange;

  ptrstartRange = &startRange;
  ptrendRange = &endRange;

  double Sum, Average;

  double *ptrSum;
  double *ptrAverage;

  ptrSum = &Sum;
  ptrAverage = &Average;

  printf("Please enter the range (startRange < endRange): ");
  scanf("%d %d", ptrstartRange, ptrendRange);
  
  calSumAndAverage(ptrstartRange,ptrendRange,ptrSum,ptrAverage);

  printf("The Sum of Numbers within the range is = %.2lf ", *ptrSum);
  printf("\nThe Average of the Numbers within the Range is = %.2lf", *ptrAverage);

  return 0;
}

double calSumAndAverage(int *startRange, int *endRange, double *Sum, double *Average)
{
  for(int i=*startRange; i<= *endRange; i++)
  {
    *Sum += i;
  }

  int number = (*endRange -*startRange) + 1;
  *Average = (*Sum) / number;
}

Output

Please enter the range (startRange < endRange): 2
10
The Sum of Numbers within the range is = 54.00 
The Average of the Numbers within the Range is = 6.00