consider the following sequence given by the recurrences realtion :
U1=-1 U2=1 U3=2 UN =(2*Un-1 ) - (5*Un-2) +(Un-3 +2) if (n>3)
write a program that enters an integer value n and then prints the value of n-th term Un and then sum of Un
#include <iostream>
int U(int n)
{
switch(n)
{
case 1 : return -1;
case 2 : return 1;
case 3 : return 2;
default: return 2 * U(n-1) - 5 * U(n-2) + 2 + U(n-3);
}
}
int main()
{
int n;
std::cout << "Input integer: ";
std::cin >> n;
if(n < 1)
{
std::cout << "Invalid integer value\n";
return 1;
}
std::cout << "U(" << n << ") = " << U(n) << "\n";
int sum = 0;
for(int i=1; i<n; ++i)
{
sum += U(i);
}
std::cout << "Sum U(" << n << ") = " << sum << "\n";
return 0;
}
Comments
Leave a comment