Skip to main content

Command Palette

Search for a command to run...

A Basic Guide to Coding Pt. 2: Loops

By Varsha Kumar

Published
2 min read

Loops are essential to programming. Without loops, coding would be very inefficient and time-consuming (e.g., printing “Hello World” 100 times). Loops also allow for flexibility, meaning that you can repeat a certain number of times based on user input and so on. In general, there are three different types of loops in most programming languages: while, for, and do-while loops.

Three Components of a Loop

Before you can even care for picking a while, do-while, or for loop, you must first understand the three components of a loop: initialization, condition, and iteration.

Initialization: There is a counter variable per loop to keep track of how many times it can run. Initialization is setting that counter variable for any value, 0, 100, or even 1000.

Condition: This is usually a boolean expression to see if it continues (if true for most programming languages), and if false will immediately terminate the loop. This allows for the loop to end (to avoid infinite loops and errors).

Iteration: How many times the loop will run, and is done so by modifying the counter variable set during initialization.

While Loops

While loops are the most flexible. The syntax is essentially like this:

int counter = 5; // initialization
while (counter > 0) { // condition
System.out.println("Hello World!");
counter++; // iteration
}

The example above allows for this while loop to run 5 times. You can place the counter variable and iteration anywhere, but it depends on where it is.