C++ program example: pass one-dimensional array to function

Passing one-dimensional array to function

This is the C++ program example to calculate the average of integers input from keyboard. The integers are stored in a one-dimensional array passed to the avg function.

// C++ program: Passing one-dimensional array to function
#include <cstdlib>
#include <iostream>
using namespace std;

double avg(int arr[],int size){ //don't specify the size of array between [ and ]
    int sum=0;
    double r;
    for(int i=0;i<size;i++)

int main(){
   int n;
   cout<<"Enter number of integers:";
   int arr[n];
   for(int i=0;i<n;i++){
       cout<<"Value "<<i+1<<":";

cout<<"Average="<<avg(arr,n)<<endl; //place only the name of array when the function is called



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.