Loading [MathJax]/jax/output/CommonHTML/jax.js
Back
Close

Basics of Recursive Programming (recitation)

madooei
918 views

Create a recursive countdown function that takes in an integer n and prints out a countdown from n to 1.

First, think about a base case for the countdown function.

What is the simplest input the problem could be given?

The simpleset input is where there is no need to count down! That is, when n == 1 we simply print out 1.

After you’ve thought of a base case, think about a recursive call with a smaller argument that approaches the base case.

Need a hint?

What happens if you call countdown(n - 1)?

Then, put the base case and the recursive call together, and think about where a print statement would be needed.

// { autofold
public class Main {
// }
// REQUIRES: n >= 1
// EFFECTS: prints out numbers from n to 1
public static void countdown(int n) {
// TODO: complete the code here
}
public static void main(String[] args) {
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Is there an easy way to change "countdown" to count up instead?
// { autofold
public class Main {
// }
// REQUIRES: n >= 1
// EFFECTS: prints out numbers from 1 to n
public static void countup(int n) {
// TODO: complete the code here
}
public static void main(String[] args) {
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants