Objectives: Implement a basic recursive function in C++ with Microsoft Visual St
ID: 3738024 • Letter: O
Question
Objectives: Implement a basic recursive function in C++ with Microsoft Visual Studio.
PS: It's one lab so both questions are expected to be answered.
Question 1: Write a recursive function named sumSquares that returns the sum of the squares of the numbers from 0 to num, in which num is a nonnegative int variable. Also write a program to test your function. Example 1: ould match the example below. Please input a num: 3 Sum of the squares of the numbers from 0 to num: 14 Question 2: Write a recursive function that finds and returns the sum of the elements of an int array. Also, write a program to test your function. Use this array to test your program: int list[10]- 11,2, 3, 4, 5, 6, 7, 8,9, 10;Explanation / Answer
Question 1
#include <iostream>
using namespace std;
int sumSquares(int number);
int main() {
int num = 0;
cout<<"Please input a number :";
cin>>num;
cout<<"Sum of the squares of the numbers from 0 to "<<num<<" : "<<sumSquares(num);
}
int sumSquares(int n) // Definition of the function sumSquares
{
if(number==0)
return 0;
else
{
return (sumSquares(n-1) + (n*n));
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------
Question 2
#include <iostream>
using namespace std;
int sumArray(int Arr[], int size) // Definition of the recursive function to find sum of array
{
if (size <= 0) // If array size is 0 or less function will return 0
return 0;
return (sumArray(Arr, size - 1) + Arr[size - 1]); //else function will calculate sum rescursively
}
int main()
{
int Ar[] = {1,2,3,4,5,6,7,8,9,10}; // Initialising the array to test
int s = sizeof(Ar) / sizeof(Ar[0]); // Finding the size of the array
cout<<"Sum of the array is : "<<sumArray(Ar, s); // Print the sum
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.