Assignment Examples: 48 Problems with Answers
Worked examples of Assignment to try before you open each solution, then practice problems with answers.
Worked Examples
Example 1
easyShow solution
Answer
First step
Full solution
- 2. Step 2: y is assigned the current value of x, which is 10. So y = 10.
- 3. Step 3: x is reassigned to 20. y is unchanged (still 10). Output: x = 20, y = 10.
Example 2
easyExample 3
mediumExample 4
hardPractice Problems
Try each one, then open the solution to compare your method.
Example 1
easyExample 2
mediumSET x = 10
SET y = x + 5
SET x = y * 2
SET y = x - y
What are the final values of x and y?
Example 3
easyExample 4
easyExample 5
easyExample 6
easyExample 7
easyExample 8
easyExample 9
easyExample 10
easyExample 11
mediumExample 12
mediumExample 13
mediumExample 14
mediumExample 15
mediumExample 16
mediumExample 17
mediumExample 18
mediumExample 19
mediumExample 20
challengeExample 21
challengeExample 22
challengeExample 23
easyExample 24
easyExample 25
easyExample 26
easyExample 27
easyExample 28
easyExample 29
mediumExample 30
mediumExample 31
mediumExample 32
mediumExample 33
mediumExample 34
mediumExample 35
mediumExample 36
mediumExample 37
mediumExample 38
mediumExample 39
mediumExample 40
hardExample 41
hardExample 42
hardExample 43
hardExample 44
challengeWhat 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.
Ask yourself: Does a line store a value into a name with a single =, working out the right side before the left side changes?
Concept recap
The operation of storing a value in a variable. The variable name goes on the left of the assignment operator, and the value or expression goes on the right. The right side is evaluated first, then the result is stored in the variable on the left.
Each variable is a small whiteboard with its name written at the top. Assigning means erasing the board and writing the new value, so it only ever shows the latest one, and copying from one board to another copies what is written right now. The picture holds for numbers and text; for lists, many languages copy a link to the same list instead.
Read the full lesson on AssignmentBackground knowledge
These ideas may be useful before you work through the harder examples.