Calculate the Nth term in C hackerrank solution

      

  #include <stdio.h>
  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 {
          int term;
          for (int i = 4; i <= n; i++) {
              term = a + b + c;
              a = b;
              b = c;
              c = term;
          }
          return term;
      }
  }
  
  int main() {
      int n, a, b, c;
      scanf("%d %d %d %d", &n, &a, &b, &c);
      
      int nth_term = find_nth_term(n, a, b, c);
      printf("%d\n", nth_term);
      
      return 0;
  }
  
     
            

Let's go through the solution step by step:

We include the header file to use the standard input/output functions.

The find_nth_term() function takes four integer parameters: n, a, b, and c. It calculates and returns the value of the Nth term in the series based on the given rules.

Inside the find_nth_term() function, we check the base cases for n = 1, n = 2, and n = 3. If n is one of these values, we simply return a, b, or c respectively, as mentioned in the problem statement.

If n is greater than 3, we enter the else block. We declare an integer variable term to store the current term in the series.

We use a for loop starting from 4 up to n to calculate the value of the Nth term. Inside the loop, we update the values of a, b, and c according to the rules mentioned in the problem statement.

Finally, we return the calculated term as the Nth term of the series.

In the main() function, we declare integer variables n, a, b, and c to store the input values.

We use the scanf() function to read the input values from the user.

We call the find_nth_term() function with the input values to calculate the Nth term.

We use the printf() function to print the calculated Nth term.