Don’t worry, unlock all articles / blogs on PrepInsta by just simply logging in on our website
C++ Program for Staircase Problem
July 2, 2020
Staircase Problem
Staircase Problem is a simple array manipulation problem, which can be solved using the concept of recursion and fibonacci series. This problem was also asked as a sample problem in TCS CodeVita Season 9 coding competition. This competition is organized by TCS every year in search of World’s Best Coders.
There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time.
Count the number of ways, the person can reach the top.
C++ Code
#include <iostream>
using namespace std;
int calc(int n);
int count(int x);
int main ()
{
int n ;
cout<<("Enter number of stairs : ");
cin>>n;
cout<<("Number of ways = %d", count(n));
return 0;
}
int count(int x)
{
return calc(x + 1);
}
int calc(int n)
{
if (n <= 1)
return n;
return calc(n-1) + calc(n-2);
}
Output
Enter number of stairs : 5
8
Staircase Problem in Other Coding Languages
Python
To find the solution of Staircase problem in Python Programming language click on the button below:
#include
using namespace std;
int main(){
int n; cin >> n;
int dp[n+1]{0};
dp[0] = 0;
dp[1] = 1;
dp[2] = 2;
for(int i=3; i<=n; i++){
dp[i] += dp[i-1];
dp[i] += dp[i-2];
}
cout << dp[n];
}