Count ways to reach the nth stair using step 1, 2 or 3 in C++

C++Server Side ProgrammingProgramming

We are given a total number of steps in a staircase that is n. A person can reach the next floor by skipping 1, 2 or 3 steps at a time. The goal is to find the number of ways in which the next floor can be reached by doing so.

We will use the recursive method by keeping in mind that to reach any i’th step, a person has to jump from i-1th step ( skip 1 step) , i-2th step (skip 2 steps ) or i-3th step ( skip 3 steps ).

Let’s understand with examples.

Input 

N=3 steps

Output 

Count of ways to reach the nth stair using step 1, 2 or 3 are: 4

Explanation 

There are total 3 steps
Jump from start ( skip 3 ) : 3 step
Jump from 1’st step (skip 2): 1+2
Jump from 2nd step (skip 1): 2+1
No skip 1+1+1

Input 

N=6 steps

Output 

Count of ways to reach the nth stair using step 1, 2 or 3 are: 24

Explanation 

There are total 6 steps
Ways: 1+1+1+1+1+1, 2+1+1+1+1, 3+1+1+1, 3+1+2, 3+2+1, 3+3 and so on.

Approach used in the below program is as follows

  • We are taking integer steps as a total number of steps.

  • Function stairs_step(int steps) takes all steps as input and returns a number of ways to reach the next floor by taking jumps or not..

  • Take the initial variable count as 0 for such ways.

  • If the number is 0 return 1.

  • If step count is 1 only 1 way.

  • If step count is 2 only 2 ways ( 1+1 or 2 ).

  • Else the ways = stairs_step (step-3)+stair_step(step-2)+stair_step(step-1).

(recursive method)

Example

 Live Demo

#include <iostream>
using namespace std;
int stairs_step(int steps){
   if(steps == 0){
      return 1;
   }
   else if(steps == 1){
      return 1;
   }
   else if (steps == 2){
      return 2;
   }
   else{
      return stairs_step(steps - 3) + stairs_step(steps - 2) + stairs_step(steps - 1);
   }
}
int main(){
   int steps = 5;
   cout<<"Count of ways to reach the nth stair using step 1, 2 or 3 are: "<<stairs_step(steps);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of ways to reach the nth stair using step 1, 2 or 3 are: 13
raja
Updated on 31-Oct-2020 05:40:34

Advertisements