← Back to course
Code Crew G5 / Week 03 / Tuesday
2/6
Week 03 Β· Nesting boxes

Tuesday

Pass the question back
// A function that calls itself
⏱ about 15 min

Tuesday: Pass the question back

The crew lines up in a narrow tunnel to board the shuttle. Rocket is at the front.

"How many people are behind me?" he wonders. He cannot turn around in the tight tunnel.

Raven is just behind him. "What do you notice? Each person can only see the person right behind them."

Rocket grins. "So I ask you, and you ask the next person?"

Nova glows at the back. "Here is a hint. Someone at the end must answer without asking anyone."

Questions go back, answers come forward

Rocket asks Ada, "How many people are behind you?" Ada cannot see, so she asks Ben the same question.

The question travels back down the line. Dee is last, so Dee answers 0 without asking anyone.

Then each person adds 1 to the answer they heard. They pass the new number forward.

PersonAsksHears backSays forward
RocketAda3(knows 4 are behind him)
AdaBen23
BenCy12
CyDee01
Deenobody0

Every person follows the same rule: ask the person behind, then add 1. Only Dee does something different. Dee is the stopping point.

TAP THE ANSWERS INTO THE ORDER THEY TRAVEL FORWARD.
  • Tap a card.
  • Then tap its spot.
11st
22nd
33rd
44th
55th
Eve joins the line behind Dee. Now what does Eve say?
With Eve in line, what does Dee say?
With Eve in line, how many people are behind Rocket?
THINK ABOUT THE LINE.
  • Read the question.
  • Tap your answer.
Who answers without asking anyone?
Which way do the answers travel?

Practice lab: a longer line

Now eight crew members stand behind Rocket. Each one follows the same rule as before. Ask the person behind you, then add 1.

What number does the last person say?
What does the person just in front of the last person say?
How many people are behind Rocket?
How many questions are asked in all, counting the one Rocket asks?
LINE CHECK
  • Read the question.
  • Tap your answer.
Which person does something different from everyone else?
Rocket hears 7 from the person behind him. What does he know?
The last person steps out of line. Who is the new stopping point?
StatementTrue or false?
Questions travel toward the back of the line.?
The first answer comes from Rocket.?
Each answer is 1 more than the answer just behind it.?
If nobody stops the questions, no answer ever comes back.?
WHY THIS EXERCISEThe answer starts at the stopping point and grows by 1 as it moves forward.
A line has 12 people behind Rocket. What number does the second to last person say?
WHY THIS EXERCISEOnly one person, the last one, stands behind them.

Nice work! Questions going back and answers coming forward is exactly how recursion runs in code. Tomorrow we write our first recursive function.

← Monday