CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Control

Control Statements
Loops
while and do-while

The syntax of the while loop

while (booleanExpression)
{
   statements
}

How to code while and do-while loops

  • In a while loop, the condition is tested before the loop is executed.
  • In a do-while loop, the condition is tested after the loop is executed.
  • A while or do-while loop executes the block of statements within the loop as long as its Boolean expression is true.
  • If a loop requires more than one statement, you must enclose the statements in braces. Any variables or constants that are declared in that block have block scope.
  • If a loop requires just one statement, you don't have to enclose the statement in braces. However, that statement can't declare a variable or it won't compile.
  • If the condition at the start of a while statement never becomes false, the program goes into an infinite loop. You can cancel an infinite loop by closing the console window or pressing Ctrl+C.

A while loop that calculates a future value

int i = 1;
int months = 36;
while (i <= months)
{
    futureValue = (futureValue + monthlyPayment) * (1 + monthlyInterestRate);
    i++;
}

The syntax of the do-while loop

do
{
   statements
}
while (booleanExpression);

A do-while loop that calculates a future value

int i = 1;
int months = 36;
do
{
    futureValue = (futureValue + monthlyPayment) * (1 + monthlyInterestRate);
    i++;
}
while (i <= months);

The code for the Divisibility test by 3 and 9

public class DivisibilityTest
{
    static Scanner console = new Scanner(System.in);

    public static void main (String[] args)
    {
        int num;
        int temp;
        int sum;

        System.out.print("Enter a positive integer: ");
        num = console.nextInt();
        System.out.println();

        temp = num;

        sum = 0;

        do
        {
            sum = sum + num % 10; //extract the last digit
                                  //and add it to sum
            num = num / 10;       //remove the last digit
        }
        while (num > 0);

        System.out.println("The sum of the digits = " + sum);

        if (sum % 3 == 0)
            System.out.println(temp + " is divisible by 3");
        else
            System.out.println(temp + " is not divisible by 3");

        if (sum % 9 == 0)
            System.out.println(temp + " is divisible by 9");
        else
            System.out.println(temp + " is not divisible by 9");
    }
}
Previous | Loops | while and do-while | for | Application | nested for | Next