Variable Examples in CS Thinking

Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of Variable.

This page combines explanation, solved examples, and follow-up practice so you can move from recognition to confident problem-solving in CS Thinking.

Concept Recap

A named container in a program that stores a value, which can be read, updated, or replaced. Variables have a name (identifier), a value (the data stored), and in many languages a type (what kind of data it holds).

A labeled box you can put things in, take things out, or change what's inside.

Read the full concept explanation โ†’

How to Use These Examples

  • Read the first worked example with the solution open so the structure is clear.
  • Try the practice problems before revealing each solution.
  • Use the related concepts and background knowledge badges if you feel stuck.

What to Focus On

Core idea: Variables give meaningful names to data values so programs can store, retrieve, and modify them.

Common stuck point: = means 'assign' not 'equals'. x = x + 1 is valid (not a paradox).

Sense of Study hint: When using variables, choose descriptive names that explain what the data represents (e.g., 'total_score' not 'x'). Initialize variables before using them, and keep track of how each variable's value changes as the program runs.

Worked Examples

Example 1

easy
Trace: SET x = 7. SET y = x + 3. SET x = y * 2. OUTPUT x, y.

Solution

  1. 1
    Step 1: x = 7.
  2. 2
    Step 2: y = 7 + 3 = 10.
  3. 3
    Step 3: x = 10 * 2 = 20. Output: x = 20, y = 10.

Answer

x = 20, y = 10.
Variables are named containers for storing values. When we reassign a variable, the old value is replaced. Other variables that used the old value are not affected.

Example 2

medium
Show how to swap the values of two variables a and b using a temporary variable. Trace with a = 5, b = 9.

Practice Problems

Try these problems on your own first, then open the solution to compare your method.

Example 1

easy
What is the output? SET score = 0. SET score = score + 10. SET score = score + 5. OUTPUT score.

Example 2

medium
Trace this swap algorithm: SET A = 3. SET B = 8. SET temp = A. SET A = B. SET B = temp. What are A and B at the end, and why is temp needed?