Home > Enterprise >  Program that computes the nth element of a number series given by a formula
Program that computes the nth element of a number series given by a formula

Time:11-02

Write a method/function with name cpSeries that computes the nth element in a series of numbers, given by the formula: a(n) = (a(n-1))2 a(n-2) when: n>1 and assuming that: a(1)=1, a(0)=0 Note that indexing of the series starts from 0.

I have already written the above code but it runs for an infinite time and I don't know how to fix it in order to compute the nth element.

Any ideas? I have to use only functions to solve this problem.

# include <stdio.h>

int cpSeries(int n)
{    
    int Nthterm = 0;
    int i;
    
    if (n==0) {
        cpSeries(0) == 0;
    }
    else if (n==1) {
        cpSeries(1) == 1;
    }
    for (i=0; i<=n; i  ){
        Nthterm = cpSeries((n-1))*cpSeries((n-1))   cpSeries((n-2));
        return Nthterm;
    }
}

int main()
{
    int n=6;
    printf("The Nth term of the series is: %d",cpSeries(n));
}

CodePudding user response:

If the provided equation gives you the nth element, I don't see the need for a loop.

Also, in the if conditions, you are calling the function again, but what you should do is return the value you need.

int cpSeries(int n){
    
    int Nthterm;
    
    if (n==0){
        
        Nthterm = 0;
    }
    else if (n==1){
        
        Nthterm = 1;
    }
    else {

        Nthterm = cpSeries((n-1))*cpSeries((n-1))   cpSeries((n-2));   
    }

    return Nthterm;    
}


CodePudding user response:

Your final conditions just call the function another time instead of returning 0 or 1.

instead of

if (n==0) {
    cpSeries(0) == 0;
}
else if (n==1) {
    cpSeries(1) == 1;
}

use

if (n==0) {
    return 0;
}
else if (n==1) {
    return 1;
}

CodePudding user response:

C is not a declarative language where you can specify the return value y of a function f given an argument x by writing something like f(x) = y, but you have to use a return statement.

Change cpSeries(0) == 0; to

return 0;

to avoid the infinite recursion (and the same for n == 1).

  •  Tags:  
  • c
  • Related