Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ function that accepts four arguments int x[] An integer array int si

ID: 3774901 • Letter: W

Question

Write a C++ function that accepts four arguments

int x[] An integer array

int size: The size of the array

int a

int b

int sum(int x[], int size, int a, int b)

The function should calculate and return the sum of the array items between index a and index b. In other words, the sum x[a] + x[a+1] + .. .. + x[b]

Complete the main function as directed by the comments.

int main()

{

int num[8]= {1,0,4,5,9,10,-1,6};

//using the function you created, display the sum of the

//first 3 items in the num array  

//using the function you created, display the sum of the

//last 3 items int the num array  

return 0;

}

Explanation / Answer

Here is code:

#include <iostream>
using namespace std;
int sum(int x[], int size, int a, int b);
int main()
{
// array set
int num[8]= {1,0,4,5,9,10,-1,6};
//using the function you created, display the sum of the
//first 3 items in the num array
int result = sum(num,8,0,2);
cout << "sum of array between 0 and 2 is : " << result << endl;
//using the function you created, display the sum of the
//last 3 items int the num array
result = sum(num,8,5,7);
cout << "sum of array between 5 and 7 is : " << result << endl;
return 0;
}

int sum(int x[], int size, int a, int b)
{
// invalid index
if(a < 0 || b > size)
{
cout << "invalid index ";
exit(0); // exit program
}
else
{
int sum = 0;

// loops from a reaches b
while( a <= b)
{
sum += x[a];
a++;
}
return sum; //return the sum
}
}

Output:

sum of array between 0 and 2 is : 5                                                                                                   

sum of array between 5 and 7 is : 15

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote