Finding the sum of an array y by passing an array to a function using pointer C++ code example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Finding the total of an array y by passing an array to a function using pointer in C++ programming
To show: How to calculate the sum of array element using a function and a pointer in C++ programming
// a program to find the total values of an array y by passing an array to a function using pointer
#include <iostream>
using namespace std;
#define n 7
// function prototype
int get_total(int*, int);
int main(void)
{
int total, y[n]={6,9,2,4,5,23,12};
cout<<"\nCalling function get_total(y, n),";
cout<<"\nBy bringing along the value of y, an array";
cout<<"\nfirst address and n = 7, an array size.";
cout<<"\nAn array name, is the pointer to the";
cout<<"\n1st element of an array\n\n";
// function call, pass along the pointer to the first array element and the array size, and the
// return result assign to variable total
total = get_total(y, n);
cout<<"\nSum of the 7 array elements is "<<total<<endl;
return 0;
}
// the function definition
int get_total(int *ptr, int x)
{
int i, total = 0;
// traverse all the array elements
for(i=0; i<x; i++)
{
// displays the array content, pointed by pointer...
cout<<*(ptr+i)<<" ";
// do the summing up of the array elements
total += *(ptr+i); //total=total + *(ptr+i);
}
// return the result to the calling program
return total;
}
Output example:
Calling function get_total(y, n),
By bringing along the value of y, an array
first address and n = 7, an array size.
An array name, is the pointer to the
1st element of an array
6 9 2 4 5 23 12
Sum of the 7 array elements is 61
Press any key to continue . . .