Using C++ Do not make use of any variables in your answers to this question. Use
ID: 3834845 • Letter: U
Question
Using C++
Do not make use of any variables in your answers to this question.
Use recursive functions to cause repetition when needed. All numbers will be ints. No Loops
Part A. Write a function addup(x, y) that adds up all the numbers between x and y (inclusive), and returns their sum as its result.
e.g.
const int a = addup(2, 5);
defines a to be 14 because 2+3+4+5 = 14.
Part B. Write a function addup_arr(R, x, y), where R is an array of ints. It should add up all the numbers from position x to position y in the array, and return their sum as its result.
e.g.
const int b[] = { 7, 3, 1, 6, 14, 2, 9, 5 };
cout << addup_arr(b, 2, 5);
prints 23 because 1+6+14+2 = 23.
Part C. Write another function sum_arr(R, n), where R is an array of ints, and n is the size of that array. It should add up all the numbers in the array and return the result.
e.g.
cout << sum_arr(b, 8)
prints 47 because 7+3+1+6+14+2+9+5 = 47
Part D. Write a function max_arr(R, n), where R and n are as described in part c. It should find the largest number in the array, and return that maximum as its result. Hint – use an extra parameter to remember the biggest number encountered so far.
e.g. max_arr(b, 8) is 14
Explanation / Answer
#include <iostream>
using namespace std;
int addup(int x, int y){
if(x==y){
return x;
}
return x+addup(x+1,y);
}
int addup_arr(const int arr[], int x, int y){
if(x==y){
return arr[x];
}
return arr[x]+addup_arr(arr,x+1,y);
}
int sum_arr(const int arr[], int n){
if(n==1){
return arr[0];
}
return arr[n-1]+sum_arr(arr,n-1);
}
int max_arr(const int arr[], int n){
if(n==1){
return arr[0];
}
int ans1 = arr[n-1];
int ans2 = max_arr(arr,n-1);
if(ans1>ans2){
return ans1;
}
return ans2;
}
int main() {
// your code goes here
const int a = addup(2, 5);
cout<<a<<endl;
const int b[] = { 7, 3, 1, 6, 14, 2, 9, 5 };
cout << addup_arr(b, 2, 5) << endl;
cout << sum_arr(b, 8) << endl;
cout << max_arr(b, 8);
return 0;
}
OUTPUT :
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.