153k views
3 votes
Write a recursive function program to find the nth element in the following arithmetic numerical sequence: 3, 11, 27, 59, 123, ...

User Katharine
by
8.0k points

1 Answer

3 votes

following are the code in c++

#include<bits/stdc++.h>

using namespace std;

//fuction to find nth term of the sequence

int val(int n){

if(n==1){

return 3;

}else{

return val(n-1)+8*pow(2,n-2);

}

}

// driver fuction

int main(){

int n;

cout << "Which element of the sequence would you like to know?\\";

cin >> n;

//checking for input less than 1

do{

if(n<1)

{

cout<<"Please enter a number greater than 0:"<<endl;

cin>>n;

}

}while(n<1);

//printing the output

cout<<n<<"th element of the sequence is: ";

cout << val(n);

}

Step-by-step explanation:

in the given code, if user enter input less than 1 then it will again ask for the input greater than 0 . When the input is greater than 0,it calls the recursive function with the parameter n .if the input is 1 then function will give 3 as output. And when input is greater than 1, the recursive function will return nth element of the given sequence.

output

which element of the sequence would you like to know?

-1

Please enter a number greater than 0:

0

Please enter a number greater than 0:

5

5th element of the sequence is: 123

User Metamorphic
by
7.6k points