🧩 Run the Code in Your Head: Variables, Loops, Conditions
Episode finished! 🎉
Episode transcript
A computer runs code line by line. Today we will act like a computer and trace the code in our heads.
In a flowchart every step has its own shape: Start and End are ovals, input and output are parallelograms, a process is a rectangle and a decision is a diamond. The arrows show the order of the steps.
A variable is a named box where we keep a value. When score is 5 and we write score = score + 3, the right side is worked out first: 5 + 3 = 8. The new value goes into the box.
Trace the code line by line and write the variable’s value in the table after each line. On line 1 the score became 5, on line 2 it became 8. What happens on line 3?
A loop runs the same lines again and again. The total starts at zero. The loop goes round three times and adds 2 each time: 2, 4, 6. In the end the total is 6.
Now you trace it. The number starts at 1. The loop goes round three times and the number is multiplied by 2 each time. After the first turn it is 2, after the second it is 4. What is it after the third turn?
A condition is a question: if the answer is yes we go one way, if it is no we go another way. The score is 12 and the question is “score > 10 ?”. 12 is bigger than 10, so the answer is Yes and it says “You win!”.
Did the code not give the result you expected? There is a bug. Here the loop should add 2 each turn, but it subtracts 2, so the result is −6 instead of 6. Finding the faulty line and fixing it is called debugging.
Summary: know the flowchart symbols, trace a variable line by line, write down every turn of a loop, pick the yes or no road in a condition, and if there is a bug, find it and fix it. Now try it in Kod Kulesi!