Introduction to Computer Algorithm: Data Structures, Complexity, and Optimization for Modern AI Systems

The 'While' Loop: Repeating Until a Condition is Met

Section 3

Repeating Actions: Loops (For, While) for Efficiency

Introduction to Computer Algorithm: Data Structures, Complexity, and Optimization for Modern AI SystemsRepeating Actions: Loops (For, While) for Efficiency

In the world of algorithms, we often need to repeat a set of instructions. We've already explored the 'for' loop, which is fantastic when you know exactly how many times you want to repeat something. But what happens when you don't know the exact number of repetitions beforehand? This is where the 'while' loop shines. A 'while' loop allows you to repeatedly execute a block of code as long as a specific condition remains true.

Think of it like this: 'While' this is true, keep doing that. The loop continues to run, checking the condition at the beginning of each iteration. If the condition is true, the code inside the loop executes. If the condition is false, the loop terminates, and the program continues with the code that follows the loop.

The basic structure of a 'while' loop typically involves:

  1. Initialization: Setting up any variables that will be used in the condition.
  1. The 'while' keyword: Followed by the condition enclosed in parentheses.
  1. The loop body: A block of code (usually enclosed in curly braces) that will be executed repeatedly.
  1. Condition update: Inside the loop body, something must happen to eventually make the condition false. If the condition never becomes false, you'll end up with an infinite loop, which is a common pitfall!

Let's look at a simple example. Imagine we want to count down from 5 to 1. We don't necessarily need a fixed number of iterations beforehand; we just want to keep going 'while' our counter is greater than zero.

チャプターへ戻る