Java recursive function that takes as input the number of rows n and outputs the total number of pins that would exist in a pyramid with n rows
Consider a frame of bowling pins shown below, where each * represents a pin:
*
* *
* * *
* * * *
* * * * *
There are 5 rows and a total of 15 pins.
If we had only the top 4 rows, then there would be a total of 10 pins.
If we had only the top three rows, then there would be a total of six pins.
If we had only the top two rows, then there would be a total of three pins.
If we had only the top row, then there would be a total of one pin.
Write a java recursive function that takes as input the number of rows n and outputs
the total number of pins that would exist in a pyramid with n rows. Your program
should allow for values of n that are larger than 5.
Answer:
import java.util.Scanner;
public class QuestionBowlingPins
{
/**
* numberOfPins
* Recursively compute number of bowling pins if we have n rows.
* If there are no rows, then there are 0 pins.
* If there is only one row, then there is 1 pin.
* If there are two rows, then we have two pins in row 2 + 1 from row 1 = 3
* If there are three rows, then we have three pins in row 3, plus
* the three pins if there were two rows, for 6 pins.a
* The recursive definition is:
* pins(n) = n + pins(n-1)
**/
public static int numberOfPins(int rows)
{
if (rows <=0) return 0;
return (rows) + numberOfPins(rows-1);
}
// ======================
// main method
// ======================
public static void main(String[] args)
{
// Input variables
int num_rows;
int num_pins;
Scanner scan = new Scanner(System.in);
System.out.println("How many rows of bowling pins will there be?");
num_rows = scan.nextInt();
num_pins = numberOfPins(num_rows);
System.out.println("You will need to set up " + num_pins + " bowling pins.");
}
}
Leave a reply