ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT

Count the number of ways a baby can reach the nth stair taking 1 or 2 steps at a time in C language.

prodevelopertutorial July 13, 2018

Problem Description:

A baby wants to climb the stairs. It can take a single step at a time or take 2 steps at a time. Or it can take a combination of 1 and 2 steps at a time.
Given that there are N stairs, find the number of ways the baby can reach the top of the stairs.

Solution Diagram:

Suppose there are 3 steps, there can be 3 ways the baby can reach the top of the stairs. Below is the diagram to explain the same.

One Step at a time

no_of_ways_to_climb_stairs

 

Two-step then one step

no_of_ways_to_climb_stairs

 

One step then Two-step

no_of_ways_to_climb_stairs

 

More Example:

 

If steps = 1

    Only 1 way
If steps = 2

    (1, 1), (2)
    2 ways.
If steps = 4

    (1, 1, 1, 1), (2, 2), (1, 1, 2), (2, 1, 1), (1, 2, 1)
    5 ways.

In a way, this is equal to Fibonacci series. Here if there are N steps, then the number of ways to climb will be Fibonacci(N + 1)

 

Solution in C language:

#include<stdio.h>

int calculate_fibonacci(int num)
{
	if (num <= 1)
		return num;

	return calculate_fibonacci(num - 1) + calculate_fibonacci(num - 2);
}


int get_number_of_ways(int stairs)
{
	return (calculate_fibonacci(stairs + 1));
}


int main(int argc, char const *argv[])
{
	int no_of_stairs = 0;
	int no_of_ways = 0;

	printf("Please enter number of stairs\n");
	scanf("%d", &no_of_stairs);

	no_of_ways = get_number_of_ways(no_of_stairs);

	printf("The number of ways the baby can climb is %d \n",no_of_ways );

	return 0;
}

Output:

Please enter number of stairs
4
The number of ways the baby can climb is 5

 

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Daily we discuss about competitive programming questions, join us at:   Telegram Channel

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2021 ProDeveloperTutorial.com
Get top courses from: Educative.io