C# program to determine total ways stairs can be climbed
Here's a C# program that calculates the total number of ways to climb a staircase with a given number of steps. The program uses dynamic programming to optimize the solution by avoiding redundant calculations.
using System;
class Staircase
{
static int CountWays(int steps)
{
// Create a memoization table to store computed results
int[] memo = new int[steps + 1];
// Base cases
memo[0] = 1;
memo[1] = 1;
// Calculate number of ways for each number of steps
for (int i = 2; i <= steps; i++)
{
memo[i] = memo[i - 1] + memo[i - 2];
}
return memo[steps];
}
static void Main()
{
Console.Write("Enter the number of steps: ");
int steps = int.Parse(Console.ReadLine());
int ways = CountWays(steps);
Console.WriteLine("Total number of ways to climb the stairs: " + ways);
}
}
In this program, the CountWays method calculates the number of ways to climb a staircase with a given number of steps. It uses an array memo to store the previously computed results to avoid redundant calculations. The base cases are initialized with 1 since there is only one way to climb 0 or 1 step.
The Main method prompts the user to enter the number of steps and then calls the CountWays method to compute the total number of ways to climb the stairs. Finally, it displays the result on the console.
To use this program, you can copy and paste it into a C# development environment, such as Visual Studio, and run it.