While Loops

The for loop does 3 things for your: initialize, test, and increment the variable.

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

A while loop only does the test. We must include the statements to initialize and increment :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Read in 3 numbers: find total, using a while loop
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;
	int i=0;
	while(i<3) {
	  System.out.print("Enter a number: ");
	  num=keyboard.nextInt();
	  total=total+num;
	  i++;
	 }//loop
     System.out.print("Total="+total);
	}//main
}//class
CODE

If you work through the code carefully, you will notice that the value of i is 0, 1, and 2 inside the loop. When i 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!

NEXT: