USE C++
Write a sum() function that is used to find the sum of the array
through pointers. In
this program we make use of * operator. The * (asterisk) operator
denotes the
value of variable.
Input: array = 2, 4, -6, 5, 8, -1
Output: sum = 12
#include <iostream>
using namespace std;
int sum(int arr[],int n) //function definition
{
int *ptr=arr;
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+*ptr; //using pointers
ptr++; //increment pointer
}
cout<<"sum is: "<<sum;
}
int main()
{
int arr[100];
int n;
cout<<"Enter the number of elements: ";
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr[i]; //taking input
}
cout<<"Input array: ";
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
sum(arr,n); //function call
return 0;
}
DON'T FORGET TO HIT LIKE.
THANKS BY HEART.
COMMENT DOWN IF ANY PROBLEM.
Get Answers For Free
Most questions answered within 1 hours.