51.5k views
5 votes
Write the definition of a method named sumArray that has one parameter, an array of ints. The method returns the sum of the elements of the array as an int.

1 Answer

4 votes

Answer: Following code is in C++

#include<iostream>

using namespace std;

int sumArray(int a[]) //take array as argument

{

int s=0,i;

for(i=0;i<5;i++)

s+=a[i]; //sums every element

return s;

}

int main() {

int sum,a[]={1,7,4,9,6};

sum=sumArray(a); //calling the function

cout<<"Sum of array is : "<<sum; //printing sum to console

return 0;

}

OUTPUT :

Sum of array is : 27

Step-by-step explanation:

In the above mentioned code, an array is declared and initialized at the same time. A variable sum of int type stores sum returned the function sumArray() and then it is printed to the console. In the function sumArray(), a variable s of data type int is initialized with value 0 and a loop is executed in which every element of the array is added. At last, s is returned.

User John Nicely
by
7.0k points