Java: Form a staircase shape of n coins where every k-th row must have exactly k coins
Staircase Coins
Write a Java program to form a staircase shape of n coins where every k-th row must have exactly k coins.
Example 1:
n = 3
The coins can form the following rows:
$
$ $
We will return 2 rows.
Example 2:
n = 4
The coins can form the following rows:
$
$ $
$
We will return 2 rows as the 3rd row is incomplete.
Example 3:
n = 5
The coins can form the following rows:
$
$ $
$ $
We will return 2 rows as the 3rd row is incomplete.
Sample Solution:
Java Code:
Sample Output:
Input a positive integer: 5 Number of rows: 2
Flowchart:
For more Practice: Solve these Related Problems:
- Modify the program to return the number of complete rows that can be formed.
- Write a program to find how many more coins are needed to complete the next row.
- Modify the program to print the staircase structure visually.
- Write a program to return the sum of coins in the completed rows.
Java Code Editor:
Previous: Write a Java program to add all the digits of a given positive integer until the result has a single digit.
Next: Write a Java program to check whether an given integer is a power of 4 or not.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics