Answer to Question #141711 in C for chinnari rao

Question #141711
write function definition(recursive as well as non-recursive)to generate the following series upto n numbers.the first two numbers are known.
1 2 6 16 44 120.....
1
Expert's answer
2020-11-02T11:19:36-0500

(a) Non-recursive function

void funct_iter(unsigned n){
    unsigned prev0 = 1, prev1 = 2;
    for (unsigned i = 1; i <= n; i++){
        if (i == 1 || i == 2) cout << i << " ";
        else {
            unsigned temp = prev1;
            prev1 = (prev0 + prev1) * 2;
            prev0 = temp;
            cout << prev1 << " ";
        }
    }
    cout << endl;
}

(b) Recursion

unsigned funct_rec0(unsigned n){
    if (n == 0 || n == 1) return n + 1;
    else return (funct_rec0(n - 1) + funct_rec0(n - 2)) * 2;
}

void funct_rec1(unsigned cur, unsigned n){
    if (cur <= n){
        cout << funct_rec0(cur - 1) << " ";
        funct_rec1(cur + 1, n);
    }
    else cout << endl;
}

void funct_rec(unsigned n){
    funct_rec1(1, n);
}

Execution (main function):

int main() {
    funct_rec(6);
    funct_iter(6);
    return 0;
}

Output:

1 2 6 16 44 120
1 2 6 16 44 120

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS