Write a C function that accepts four arguments int x An inte
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;
}
Solution
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
![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) T 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) T](/WebImages/34/write-a-c-function-that-accepts-four-arguments-int-x-an-inte-1098902-1761580170-0.webp)
![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) T 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) T](/WebImages/34/write-a-c-function-that-accepts-four-arguments-int-x-an-inte-1098902-1761580170-1.webp)