CS Fundamentals

Topic: Control Structures & Loops

1. Types of Loops

Loops allow computers to repeat a block of code multiple times without rewriting it. This concept is essential for efficiency and automation in programming.

The For Loop

Best used when you know exactly how many times you want to repeat code.

for (i = 0; i < 5; i++) {
  print(i);
}

Analogy: Running 5 laps around a track.

The While Loop

Best used when you don't know how many times to loop, but you know the condition to stop.

while (fuel > 0) {
  drive();
}

Analogy: Driving until the gas tank is empty.

The Do-While Loop

Similar to While, but guarantees the code runs at least once before checking the condition.

do {
  askInput();
} while (inputInvalid);

Analogy: Eating a bite first, then deciding if you want more.


2. Quick Review

Question 1: Which loop is best if you know you need to run code exactly 10 times?

3. Interactive Lab: The Loop Runner

Configure the simulation below to see how a "For Loop" processes logic step-by-step.

i=0
> Ready to run...
> Waiting for input...