Practice Scope in CS Thinking

Use these practice problems to test your method after reviewing the concept explanation and worked examples.

Quick Recap

The region of a program where a variable is accessible. Variables defined inside a function have local scope; variables defined outside have global scope.

Scope is like rooms in a house. A variable created inside a room (function) can only be seen from inside that room. A variable in the hallway (global) can be seen from everywhere.

Example 1

medium
What is the output? SET x = 10. FUNCTION addFive(): SET x = 5. RETURN x + 5. OUTPUT addFive(). OUTPUT x.

Example 2

hard
Explain why using global variables inside functions is generally discouraged.

Example 3

medium
What is the output? SET y = 100. FUNCTION test(): OUTPUT y. test(). Will this work, or will there be an error?

Example 4

medium
What is the output? Explain any errors. SET count = 0 FUNCTION increment() SET count = count + 1 SET bonus = 10 END FUNCTION increment() OUTPUT count OUTPUT bonus