Study Web

Programming Fundamentals

Control Structures: Conditionals and Loops

Learn how to control program flow using if/else statements, while loops, for loops, and nested structures.

Control Structures: Conditionals and Loops

What are Control Structures?

By default a program executes statements one by one from top to bottom. Control structures change this order — they allow you to skip blocks of code, repeat them, or choose between alternatives. The two main categories are conditional statements (branching) and loops (repetition). Mastering control structures is essential because nearly all real programs must make decisions and repeat operations.

Conditional Statements (if / else)

An if statement executes a block only when its condition evaluates to True. Example: if age >= 18: print "Adult" — prints only when age is 18 or above.

An if-else statement provides two branches: one for True and one for False. Exactly one branch always executes. Example: if score >= 60: result = "Pass" else: result = "Fail".

The if-elif-else chain (Python) or else-if ladder (Java, JavaScript) handles multiple conditions. The interpreter checks each condition in order and executes only the first matching branch, then skips all others — even if later conditions are also True.

Nested if statements place an if inside another if's body. Useful for multiple independent conditions, but deep nesting (more than 2–3 levels) harms readability. Flatten nested ifs using logical AND when possible.

Comparison and Logical Operators

  • == equal, != not equal, < less than, > greater than, <= less or equal, >= greater or equal — each returns True or False.
  • AND (Python: and): True only when both operands are True.
  • OR (Python: or): True when at least one operand is True.
  • NOT (Python: not): inverts the boolean — not True = False.
  • Short-circuit evaluation: AND stops at first False; OR stops at first True — improves performance and avoids errors from evaluating expensive or invalid expressions.

While Loop

A while loop repeats its body as long as its condition is True. Before each iteration the condition is evaluated — if True the body runs; if False the loop ends. Example: count = 0; while count < 5: print count; count = count + 1 — prints 0 through 4.

Infinite loop risk: if the condition never becomes False the program loops forever and must be force-killed. Always ensure the loop body includes an update that eventually makes the condition False.

break immediately exits the loop regardless of the condition. continue skips the rest of the current iteration and jumps directly back to the condition check, allowing subsequent iterations to proceed. Both work inside for loops too.

For Loop

A for loop iterates over a sequence and automatically stops when the sequence is exhausted. Preferred when the number of iterations is known in advance or you are traversing an existing collection.

  • range(n) generates 0, 1, 2, ..., n-1.
  • range(start, stop) generates start up to (but not including) stop.
  • range(start, stop, step) uses a custom step — range(0, 10, 2) gives 0, 2, 4, 6, 8. A negative step counts down: range(10, 0, -1) gives 10, 9, ..., 1.
  • Iterating over a list: for item in my_list: — each element in order.
  • Iterating over a string: for char in "hello": — processes 'h', 'e', 'l', 'l', 'o' individually.

Nested Loops

A nested loop places one loop inside another. The inner loop runs completely for every single iteration of the outer loop. Example: outer 3 iterations × inner 4 iterations = 12 total iterations. Common uses: processing 2D grids, generating all pairs from two lists. Be careful with large data — 1000 × 1000 = 1,000,000 iterations can be very slow.

Choosing While vs For

  • Use a for loop when you know how many iterations are needed or are traversing a sequence.
  • Use a while loop when iterations depend on an unpredictable condition — for example, reading user input until they type "quit".

Common Loop Patterns

Accumulator: total = 0; for num in numbers: total += num — computes the sum.

Counter: count = 0; for item in items: if condition: count += 1 — counts matching items.

Search: found = False; for item in items: if item == target: found = True; break — stops as soon as the target is found.

Maximum/minimum: maximum = numbers[0]; for num in numbers: if num > maximum: maximum = num — tracks the largest value seen so far. Initialize with the first element, not zero, to handle lists of negative numbers.