Write the definition of a function named sumArray that receives two parameters: an array of element type int and an int that contains the number of elements of the array. The function returns the sum of the elements of the array as an int.

Respuesta :

Answer:

// here is program in C++.

#include <iostream>

using namespace std;

// function to calculate sum of elements of array

int sumArray(int ar[],int n)

{

   // variable

   int sum=0;

   for(int a=0;a<n;a++)

   {

   // calculate sum of all elements

       sum=sum+ar[a];

   }

// return sum

 return sum;

}

// driver function

int main()

{

 // variable

  int n;

  cout<<"enter the number of elements in array:";

  // read the number of elements

  cin>>n;

  // Declare an array of size n

  int ar[n];

  cout<<"enter "<<n<<" elements:";

  // read the elements of array

  for(int x=0;x<n;x++)

  {

      cin>>ar[x];

  }

   // call the function with parameter array and n

   // print the sum

  cout<<"sum of "<<n<<" elements of array is: "<<sumArray(ar,n)<<endl;

   return 0;

}

Explanation:

Read the number of elements and assign it to "n".Then create an array of size n of integer type.Read n elements of the array.Call the function sumArray() with parameter array and n.Here it will calculate the sum of all elements and return an integer which holds the sum of all elements.

Output:

enter the number of elements in array:5

enter 5 elements:3 6 12 9 5

sum of 5 elements of array is: 35

ACCESS MORE