What is this exercise asking us to do?

Jun 10, 2015 at 5:27am
What is exercise #7 in this link asking us to do? http://en.wikibooks.org/wiki/C%2B%2B_Programming/Exercises/Iterations

Write a program that asks the user to type an integer N and compute u(N) defined with :
u(0)=3
u(n+1)=3*u(n)+4

Im unfamiliar with this notation. Does this have something to do with discrete math?
Jun 10, 2015 at 6:47am
It's a recursive series. The way it works is this: you are given the initial value (u(0)=3) and, when asked to find the next value (u(1)), you must use the value generated before to find the new value. For example, u(1) = u(0+1) = 3*u(0)+4 = 13. u(2) = u(1+1) = 3*u(1)+4 = 43. So on and so forth.
Jun 10, 2015 at 8:42am
I think I get it. But how do I know when to end this recursive program? I mean, it doesn't tell us when to end it. Should I just pick an arbitrary number of recursions to end at?

Jun 10, 2015 at 8:45am
It will end when u(0) is reached, which returns 3. eg.
u(2) will call u(1) which will call u(0), each using the returned value in its equation.
Last edited on Jun 10, 2015 at 8:48am
Jun 10, 2015 at 8:46am
Just think of it like making a Fibonacci calculator, except instead of adding the previous term, also multiply it by 3 and add 4.
Last edited on Jun 10, 2015 at 8:46am
Jun 10, 2015 at 9:14am
Alright, played around with it a little but I think I got it. Can someone test it out a confirm?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

int rec (int N)
{
    if(N==0)
        return 3;
    else if (N>0)
        return 3*rec(N-1)+4;
}

int main ()
{
    int N;
do{
    cout << "Please enter an integer N: " << flush;
    cin >> N;
   
 if(N==0)
        cout << "u(0) = " << rec(N) << endl;
    else
    cout << "u(" << N << ") = " << rec(N) << endl;
    cout << "\n";
    } while(N!=-1);

    return 0;
}


Thank you everyone for your input. I appreciate it :)
Last edited on Jun 10, 2015 at 9:19am
Jun 10, 2015 at 11:15am
I can confirm that this works for positive integers.
Topic archived. No new replies allowed.