C++ Write a recursive function to compute the value of the following series for
ID: 3606639 • Letter: C
Question
C++
Write a recursive function to compute the value of the following series for a given n:
f(n) = 1 + 1/4 + 1/9 + 1/16 + ... + 1/n^2 for n >= 1
Write the base cases and recurrence relationship for the function in the comments that describe your function. For example, the base case for factorial is:
n! = 1 if n = 1
and the recurrence relation is:
n! = n * (n-1)! if n > 1
You should embed the function in a program that calls the recursive function to compute the value of the series for different values input by the user. Your program should obtain the input n from the user via the console. If n is greater than zero, your program should then print out the value of the series to the console; otherwise it should print out an error message. Your program should also contain a continuation loop that prompts the user to determine if they would like to continue.
One sample run of your program should be similar to the following example:
Enter the number n: 1
The value of the series for n = 1 is: 1.00
Would you like to continue? (Enter ‘Y’ or ‘N’): N
Explanation / Answer
#include<iostream>
using namespace std;
float series(int n){
//base condition
if(n==1){
return 1.0;
}
//recursive condition
else{
return (1.0/(n*n))+series(n-1);
}
}
int main(){
int n;
char c;
do{
cout << "Enter the number n:";
cin >> n;
cout << "The vlaue of the series for n = "<< n <<" is :" <<series(n) << endl;
cout << "Would you like to continue?(Enter 'Y' or 'N'):";
cin >> c;
}while(c=='Y');
return 0;
}
/*
sample output
The vlaue of the series for n = 1 is :1
Would you like to continue?(Enter 'Y' or 'N'): Y
Enter the number n: 5
The vlaue of the series for n = 5 is :1.46361
Would you like to continue?(Enter 'Y' or 'N'): Y
Enter the number n: 10
The vlaue of the series for n = 10 is :1.54977
Would you like to continue?(Enter 'Y' or 'N'): N
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.