DSA Factory
Free lessonsProgramming basics · Stage 5 · Functions · Step 4

Names stay inside

Know that each function has its own boxes, and that numbers are copied when you pass them in. About 9 minutes.

Every function has its own boxes

Think of two classrooms in a school. Each has its own monitor, and both monitors may be called Sam. Nobody gets confused, because each Sam belongs to a different room.

Functions work in the same way. A variable made inside a function belongs to that function, and it disappears when the function ends. Another function can have a box with the same name, and the two never clash. That is why you can use n or total or count in every helper you write.

A variable lives inside: the function that made it.

Numbers are copied in

When you call a helper and give it a number, the helper gets a copy of the number, not your original box. If the helper changes its copy, your original stays exactly as it was.

That is why our halving helper can safely count n down to 0. The caller's number is untouched. It also means a helper can't change a caller's variable by accident. If you want something back from a helper, you have to return it.

To get a result back, return it. Changing the copy does nothing outside.
In code
def halvings(n):
    count = 0
    while n > 0:
        n = n // 2
        count = count + 1
    return count
Calling halvings with a = 10
a: 10
0
n: ?
1
result: ?
2
line
a
10

The caller has a box called a holding 10.

Move 1 of 4
Quick check

A helper takes a number n and counts it down to 0 inside. The caller passed in its own variable a, which held 10. What does a hold after the call?

  1. A10
  2. B0
  3. C4
Show the answer

10. The helper worked on a copy. The caller's a is untouched.

Your problem

Halving report

Write a helper that counts how many times a number can be halved (whole-number division) until it reaches 0. Return a list of four numbers: the halvings of a, the halvings of b, then a and b themselves, exactly as they were given.

Example
a = 10, b = 3 → [4, 2, 10, 3]

0 ≤ a, b ≤ 2,000,000,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding