- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# C program to find nth term of given recurrence relation

Suppose we have three numbers a, b, c and a value n. We follow a recurrence formula S(n) −

- S(1) returns a
- S(2) returns b
- S(3) returns c
- S(n) returns S(n-1) + S(n-2) + S(n-3) for all n > 3.

We shall have to find nth term by following this recurrence.

So, if the input is like a = 5, b = 2, c = 3, n = 6, then the output will be 28 because −

- S(6) = S(5) + S(4) + S(3)
- S(5) = S(4) + S(3) + S(2)
- S(4) = S(3) + S(2) + S(1) = 3 + 2 + 5 = 10
- so now S(5) = 10 + 3 + 2 = 15
- and S(6) = 15 + 10 + 3 = 28

To solve this, we will follow these steps −

Define a function solve(), this will take a, b, c, n,

- if n is same as 1, then:
- return a

- if n is same as 2, then:
- return b

- if n is same as 3, then:
- return c

- return solve((a, b, c, n - 1) + solve(a, b, c, n - 2) + solve(a, b, c, n - 3))

## Example

Let us see the following implementation to get better understanding −

#include <stdio.h> int solve(int a, int b, int c, int n){ if(n == 1) return a; if(n == 2) return b; if(n == 3) return c; return solve(a, b, c, n-1) + solve(a, b, c, n-2) + solve(a, b, c, n-3); } int main(){ int a = 5, b = 2, c = 3, n = 6; int res = solve(a, b, c, n); printf("%d", res); }

## Input

5, 2, 3, 6

## Output

28

- Related Articles
- Find nth term of a given recurrence relation in C++
- Find nth term of a given recurrence relation in Python
- C++ Program to Compute Combinations using Recurrence Relation for nCr
- Program to find nth Fibonacci term in Python
- C++ program to find Nth term of series 1, 4, 15, 72, 420…
- C++ program to find Nth term of the series 1, 5, 32, 288 …
- C++ program to find Nth term of the series 1, 8, 54, 384…
- C++ program to find Nth term of the series 3, 14, 39, 84…
- C++ program to find nth term of the series 5, 2, 13 41,...
- Program to find Nth term divisible by a or b in C++
- C++ program to Find Nth term of the series 1, 1, 2, 6, 24…
- C++ program to find Nth term of the series 1, 6, 18, 40, 75, ….
- C++ program to find Nth term of the series 5, 13, 25, 41, 61…
- C++ program to find Nth term of the series 0, 2, 4, 8, 12, 18…
- Find Pth term of a GP if Mth and Nth terms are given in C++

Advertisements