Wednesday, January 15, 2020

Calculate the Nth term - Hacker Rank Solution

Objective
This challenge will help you learn the concept of recursion.
A function that calls itself is known as a recursive function. The C programming language supports recursion. But while using recursion, one needs to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.


Calculate the Nth term - Hacker Rank Solution


#include <string.h>
#include <math.h>
#include <stdlib.h>

int find_nth_term (int n, int a, int b, int c) {
    if(n == 1) return a;
    if(n == 2) return b;
    if(n == 3) return c;
    return find_nth_term(n-1, a, b, c) + find_nth_term(n-2, a, b, c) + find_nth_term(n-3, a, b, c);
}

3 comments:

  1. #include
    #include
    #include
    #include

    int find_nth_term(int n, int a, int b, int c) {

    if (n == 1) {
    return a;
    } else if (n == 2) {
    return b;
    } else if (n == 3) {
    return c;
    } else {
    return find_nth_term(n-1, a, b, c) + find_nth_term(n-2, a, b, c) + find_nth_term(n-3, a, b, c);
    }
    }
    int main() {
    int n, a, b, c;

    scanf("%d %d %d %d", &n, &a, &b, &c);
    int ans = find_nth_term(n, a, b, c);

    printf("%d", ans);
    return 0;
    }

    ReplyDelete
    Replies
    1. Return a+b instead of b
      And
      Return a+b+c instead of c

      Delete
  2. Check this out for more information..Calculate the Nth term – Hacker Rank Solution
    https://www.codeworld19.com/calculate-the-nth-term-hacker-rank-solution/

    ReplyDelete

Powered by Blogger.