For Loops

This program uses a for loop to repeat the same instruction 3 times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package numbers;
import java.util.*;
public class Numbers {
  public static void main(String[] args) {
    Scanner keyboard=new Scanner(System.in); //do just once
    int num, total=0;
    for(int i=0;i<3;i++) {
      System.out.print("Enter a number: ");
      num=keyboard.nextInt();
      total=total+num;
    }//loop
    System.out.print("Total="+total);
  }//main
}//class
CODE

Sample output:

Enter a number: 9
Enter a number: 12
Enter a number: 3
Total=24

A for loop is extremely powerful. A for loop has three parts. The parts are separated by semicolons. The format is shown below:

for (_______; _________; __________) ____________;
      first     test     at end       statement  

The first part assigns any initial values;
The second part is a Boolean expression. If this expression is true, the loop will continue;
The third part is anything you want to do at the end of the loop.

A for loop is a good choice when we know how many times we want the code to repeat.

If you work through the code carefully, you will notice that the value of i is 0, 1, and 2 inside the loop. When n becomes 3, the loop ends. When the loop ends, the next
statement after the loop is executed.

Another very important point to note is that the body of the loop is either the single
statement that follows the for clause, or all of the statements enclosed in curly braces{ }.

If you leave off the curly braces the prompt will print 3 times, then you will
have an opportunity to input just one number. Try it!

Another advantage of the for loop is that we can ask the user how many numbers they want
to add, then loop that many times instead of using the constant 3.

NEXT: