2. You\'re standing at the base of a staircase and are heading to the top. A sma
ID: 3712158 • Letter: 2
Question
2. You're standing at the base of a staircase and are heading to the top. A small stride will move up one stair, a large stride advances two. You want to count the number of ways to climb the entire staircase based on different combinations of large and small strides. For example, a staircase of three steps can be climbed in three different ways: via three small strides or one small stride followed by one large stride or one large followed by one small. A staircase of 5 steps can be climbed in eight different ways (I'll leave it up to you to enumerate each way :-) Write a static recursive function int countWays(int numStairs) that takes a positive numStairs value and returns the number of different ways to climb a staircase of that height taking strides of one or two stairs at a time.Explanation / Answer
The JAVA code for the following question is:
import java.util.Scanner;
class Stairs
{
// A recursive program to find n'th fibonacci number
static int fibo(int n)
{
if (n <= 1)
return n;
return fibo(n-1) + fibo(n-2);
}
// Returns number of ways to reach numStairs'th stair
static int countWays(int numStairs)
{
return fibo(numStairs + 1);
}
/*program to test above function */
public static void main (String args[])
{
Scanner in = new Scanner(System.in);
int numStairs = in.nextInt();
System.out.println("Number of ways = "+ countWays(numStairs));
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.