Skip Top Navigation Bar

Using For Loops

For Loops

For loops are considered pre-test loops.

A for loop header consists of three parts:

NOTE There are cases when parts of the header are left blank.

The general format of a for loop is as follows:

for (<initialization expression>; <Boolean expression>; <step expression>) { 
   //statments
}

Tracing For Loops


Your Turn

Let's try it in the Java Playground.

Printing Odd Numbers

Computing Your Average

This program prompts the user to enter the number of grades. Once all the grades are entered, it computes the average. It's important to initialize numGrades to 0 before any grades are entered. This variable needs an initial value in order to be a part of a sum.

int totalGrades = 0;
String input = IO.readln("How many grades?");
int numGrades = Integer.parseInt(input);
int grade = 0;
for (int gradeCount = 1; gradeCount <= numGrades; gradeCount++) {
   String input = IO.readln("Enter a grade.");
   grade = Integer.parseInt(input);
   totalGrades += grade; 
} 
if (numGrades != 0) {
   IO.print(totalGrades/numGrades);
}

Resources

Next Learn Tutorial