Skip to content

A programming quiz: find number of ways a for frog’s moves

A frog can only move forward in steps of 1 or 2 steps long. Write a code to return the number of all combinations of the moves the frog can use to cover a given distance.
For example, a distance of 3 steps can be covered in three ways: 1-1-1, 1-2, and 2-1.

multiplication-on-number-line

 

public class Frog {

	public static int numberOfWays(int n) {
		if (n == 1) {
			return 1;
		} else if (n == 2) {
			return 2;
		} else {
			return numberOfWays(n - 1) + numberOfWays(n - 2);
		}
	}

	public static void main(String[] args) {
		System.out.println(numberOfWays(3));
		System.out.println(numberOfWays(4));
		System.out.println(numberOfWays(5));
		System.out.println(numberOfWays(6));
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.