Skip to content

For and While Loops

A way to repeat code multiple times

  • Lesson
  • 2 min read
  • 11 of 15 in this chapter

What are loops?

Loops are sets of code that run multiple times until a certain condition is satisfied. Simply put it is a way to execute one command over and over again until a desired outcome is achieved. These are useful because code doesn’t have to be written over and over again to do a command.

For Loops

For loops are loops that are iterated multiple times over until a certain result is achieved. For loops are typically used when the amount of times you want to use a loop are known. For example...

Java
for(int i = 0;i < 5; i++){
 //you declare the value you want to iterate over to carry out
 //then you set the amount of times it carries it out
 /*the third statement adds to the value of I every time it
 iterates. The value is added after the code inside
 is finished*/
 //code here will carry out 5 times
 System.out.println(i);
 
}

The for loop will output this...

Java
0
1
2
3
4

While Loops

While loops are code loops where the code keeps running while a certain condition is met. The condition is checked at the start of the loop. For example…

Java
int checkingInt = 0;
while(checkingInt < 25){
 //the above shows the condition
 System.out.println(checkingInt);
 checkingInt += 5;
 //adds number by 5
 /*this repeats until the condition is
 no longer met*/
}

What it will output...

Java
0
5
10
15
20 

Do while loops

Do while loops are pieces of code that are executed before a condition is checked. For example...

Java
int checkingInt = 0;
do{

 System.out.println(checkingInt);
 checkingInt += 5;
 //adds number by 5
 /*this repeats until the condition is
 no longer met*/
 /*the condition is now checked
 after the code is carried out*/
}while(checkingInt < 25);