A building has n steps. A person can take 1,2 or 3 steps. In how many ways can a person reach top of building.
In order to build logic, lets think from first step
If N=1 and Steps=1. There is only 1 way to reach with 1 step.
F(1)=1
If N=2 and Steps=1. There 1 way to reach with 1+1 step.
F(2)=1
if N=2 and Steps=1,2 . There are 2 ways to reach, with 1+1 & 0+2 steps.
F(2)=2
if N=3 and Steps=1,2 . There are 3 ways to reach, with 1+1+1 , 1+2 & 2+1 steps.
F(3)=3.
if N=4 and Steps=1,2 . There are 5 ways to reach, with 1+1+1+1 , 1+2+1 , 1+1+2 , 2+1+1 & 2+2 steps.
F(4)=5
So what is that function , does it look similar to fibonacchi series ?
F(n) = F(n-1) + F(n-2)
So Extend the same function for 3 steps
F(n) = F(n-1) + F(n-2) + F(n-3)
So code it
int main() { int n, first = 0, second = 1, third=1, next, c; printf("Enter the number of terms\n"); scanf("%d",&n); for ( c = 3; c < n ; c++ ) { next = first + second + third; first = second; second = third; third = next ; } printf("Total Steps required =%d\n",next); return 0; }