Assignment Examples in CS Thinking

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

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

The operation of storing a value in a variable. The variable name goes on the left, the value on the right.

Assignment is like putting a label on a box and putting something inside. The label is the variable name; the contents is the value.

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: Assignment is not equality โ€” it's an action. x = x + 1 makes no sense in math, but in programming it means 'update x.'

Common stuck point: = means 'assign,' not 'equals.' Many languages use == for equality comparison.

Worked Examples

Example 1

easy
Trace the following code: SET x = 10. SET y = x. SET x = 20. OUTPUT x, y.

Solution

  1. 1
    Step 1: x is assigned 10.
  2. 2
    Step 2: y is assigned the current value of x, which is 10. So y = 10.
  3. 3
    Step 3: x is reassigned to 20. y is unchanged (still 10). Output: x = 20, y = 10.

Answer

x = 20, y = 10.
Assignment copies the current value, not a reference. Changing x later does not affect y because y received the value (10), not a link to x.

Example 2

easy
What is the difference between `x = 5` (assignment) and `x == 5` (comparison)?

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 a = 3. SET b = 4. SET a = a + b. SET b = a - b. OUTPUT a, b.

Example 2

medium
Trace the values of x and y after each line: SET x = 10 SET y = x + 5 SET x = y * 2 SET y = x - y What are the final values of x and y?

Background Knowledge

These ideas may be useful before you work through the harder examples.

variable