Signup/Sign In

C++ Program To find Average Of Array Function Of Using Pointer

In this tutorial, we will learn how to print the average of an array by using the pointers.

C++ Program To find Average Of Array Function Of Using Pointer

Before proceeding to the implementation of the program, let's understand the approach.

In this problem, we are passing the value of an array using reference(passing address of the variable) so for this problem, we create a function after that we took an array value by the user after taking an array value we pass the address of an array to function(we pass the first index address and size of an array) and put some conditional statements in the function that help us to calculate the average of an array. After calculating the average of an array we return the average to function and in the main function, we print the value of an array calculated after average.

#include<bits/stdc++.h>
using namespace std;

// function declaration:
double Average(int *arr, int size);

int main ()
{

    int i, n;
    double avg;
  cout<<"Enter The Size Of Array\n";
  cin>>n;
  int average[n];
  cout<<"\nEnter The Array Elements\n"; 
 
 for(i=0; i<n; i++)
  {
  cin>>average[i];
 }
    
 cout << "\n\nAverage Value of An Array Is: " << Average(average , n)<< endl;
  
   return 0;
}

double Average(int *arr, int size)
{
   int i, sum = 0;     
   double avg;         

   for (i = 0; i < size; ++i)
   {
     sum += arr[i];
    }

   avg = double(sum) / size;

   return avg;
}


Enter The Size Of Array
5

Enter The Array Elements
8
9
1
5
6


Average Value of An Array Is: 5.8

Conclusion

Here, we have learnt how to implement a C++ program to print the average of array function using pointer.