C Program to Count ways to reach the n'th stair - GeeksforGeeks

05 Nov, 2021
There are n stairs and 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. 
Consider the example shown in diagram. The value of n is 3. There are 3 ways to reach the top. The diagram is taken from Easier Fibonacci puzzles Examples:  
Input: n = 1
Output: 1
There is only one way to climb 1 stair

Input: n = 2
Output: 2
There are two ways: (1, 1) and (2)

Input: n = 4
Output: 5
There are five ways: (1, 1, 1, 1), (1, 1, 2), 
(2, 1, 1), (1, 2, 1), (2, 2)
 
Method 1: Recursion.Approach: We can easily find the recursive nature in the above problem. The person can reach nth stair from either (n-1)th stair or from (n-2)th stair. Hence, for each stair n, we try to find out the number of ways to reach n-1th stair and n-2th stair and add them to give the answer for the nth stair. Therefore the expression for such an approach comes out to be :  
ways(n) = ways(n-1) + ways(n-2)
The above expression is actually the expression for Fibonacci numbers, but there is one thing to notice, the value of ways(n) is equal to fibonacci(n+1).  
ways(1) = fib(2) = 1
ways(2) = fib(3) = 2
ways(3) = fib(4) = 3
For a better understanding, let’s refer to the recursion tree below -:  
Input: N = 4

                  fib(5)
           '3'  /        \   '2'
               /          \
           fib(4)         fib(3)
     '2'  /      \ '1'   /      \  
         /        \     /        \ 
     fib(3)     fib(2)fib(2)      fib(1) 
     /    \ '1' /   \ '0'
'1' /   '1'\   /     \ 
   /        \ fib(1) fib(0) 
fib(2)     fib(1)
So we can use the function for Fibonacci numbers to find the value of ways(n). Following is the implementation of the above idea.  
CPP
// A C program to count number of// ways to reach n't stair when// a person can climb 1, 2, ..m stairs at a time.#include <stdio.h> // A simple recursive program to find// n'th fibonacci numberint fib(int n){    if (n <= 1)        return n;    return fib(n - 1) + fib(n - 2);} // Returns number of ways to reach s'th stairint countWays(int s){    return fib(s + 1);} // Driver program to test above functionsint main(){    int s = 4;    printf("Number of ways = %d", countWays(s));    getchar();    return 0;}
Number of ways = 5
 
Complexity Analysis:  
As in the above approach we are doing redundant calculations such as finding fib(3) more than ‘1’ number of times. This increases it’s time complexity to exponential.It can be optimized to work in O(Logn) time using the previously discussed Fibonacci function optimizations.
As in the above approach we are doing redundant calculations such as finding fib(3) more than ‘1’ number of times. This increases it’s time complexity to exponential.
It can be optimized to work in O(Logn) time using the previously discussed Fibonacci function optimizations.
Generalization of the above problem How to count the number of ways if the person can climb up to m stairs for a given value m. For example, if m is 4, the person can climb 1 stair or 2 stairs or 3 stairs or 4 stairs at a time.Approach: For the generalization of above approach we can use the following recursive relation. We can write the recurrence as following.  
ways(n, m) = ways(n-1, m) + ways(n-2, m) + 
             ... + ways(n-m, m) 
In this approach to reach a stair-‘n’ we try climbing all possible number of stairs lesser than equal to ‘n’ from present stair.  
CPP
// A C program to count number of// ways to reach n't stair when// a person can climb either 1 or 2// stairs at a time#include <stdio.h> // A recursive function used by countWaysint countWaysUtil(int n, int m){    if (n <= 1)        return n;    int res = 0;    for (int i = 1; i <= m && i <= n; i++)        res += countWaysUtil(n - i, m);    return res;} // Returns number of ways to reach s'th stairint countWays(int s, int m){    return countWaysUtil(s + 1, m);} // Driver program to test above functions-int main(){    int s = 4, m = 2;    printf("Number of ways = %d", countWays(s, m));    return 0;}
Number of ways = 5
Complexity Analysis:  
Time Complexity: O(2^n). As in the above approach we are doing redundant calculations such as finding fib(3, 2) more than ‘1’ number of times which increases it’s time complexity to exponential.It can be optimized to O(m*n) by using dynamic programming. We build a table ‘res[]’ in bottom up manner.
As in the above approach we are doing redundant calculations such as finding fib(3, 2) more than ‘1’ number of times which increases it’s time complexity to exponential.It can be optimized to O(m*n) by using dynamic programming. We build a table ‘res[]’ in bottom up manner.
As in the above approach we are doing redundant calculations such as finding fib(3, 2) more than ‘1’ number of times which increases it’s time complexity to exponential.
It can be optimized to O(m*n) by using dynamic programming. We build a table ‘res[]’ in bottom up manner.
Auxiliary Space: O(1). o use of any data structure for storing values.  
Method 2: Dynamic Programming.Approach: This method uses the technique of Dynamic Programming to arrive at the solution.Approach: We create a table res[] in bottom up manner using the following relation:  
res[i] = res[i] + res[i-j] for every (i-j) >= 0
such that the ith index of the array will contain the number of ways required to reach the ith step considering all the possibilities of climbing (i.e. from 1 to i).Below code implements the above approach: 
CPP
// A C program to count number// of ways to reach n't stair when// a person can climb 1, 2, ..m// stairs at a time#include <stdio.h> // A recursive function used by countWaysint countWaysUtil(int n, int m){    int res[n];    res[0] = 1;    res[1] = 1;    for (int i = 2; i < n; i++) {        res[i] = 0;        for (int j = 1; j <= m && j <= i; j++)            res[i] += res[i - j];    }    return res[n - 1];} // Returns number of ways to reach s'th stairint countWays(int s, int m){    return countWaysUtil(s + 1, m);} // Driver program to test above functionsint main(){    int s = 4, m = 2;    printf("Number of ways = %d", countWays(s, m));    return 0;}
Number of ways = 5
Complexity Analysis:  
Time Complexity: O(m*n). As for each stair we check all possibilities ‘m’ and number of stairs is ‘n’.
Auxiliary Space:O(n). Use of array for storing mid-way values.
Please refer complete article on Count ways to reach the n’th stair for more details! 
bidibaaz123
AshokJaiswal
rajeev0719singh
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Regular expressions in C
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Create n-child process from same parent process using fork() in C
Conditional wait and signal in multi-threading
Lamport's logical clock