Skip to main content
EDU-MMCS
You are currently using guest access (Log in)

Java Programming Language (Eng)

  1. Home
  2. Courses
  3. Весенний семестр
  4. Java Eng
  5. Basic Programming Language Constructs
  6. Lesson 8: While Loops

Lesson 8: While Loops

Lecture in pdf

Lesson 8: While Loops

Understanding conditional loops: while, do-while, and sentinel-controlled loops in Java.

Contents

Laboratory Works

  • • Lab 1: While Loop - Counter Values
  • • Lab 2: Do-while Loop - Counter Values
  • • Lab 3: Do-while with Sentinel and Exception Handling

Assignments

  • • Assignment 1: Employee Salary Calculator

Tasks for Independent Work

  • • Task 1: Sequences with While and Do-while
  • • Task 2: Decreasing Sequence with While and Do-while
  • • Task 3: Multiplication of Even Numbers
  • • Task 4: Sum of Five Numbers
  • • Task 5: Maximum Number in Sequence
  • • Task 6: Power of Two Sequence
  • • Task 7: Count Positive and Negative Numbers
  • • Task 8: Chessboard Pattern
  • • Task 9: Interactive Input Validation

Java Theory

  • • A while loop enables you to execute a block of code while a given condition is true. For example, you can use a while loop to process user input until the user indicates that there is no more data to enter.
String answer = scanner.nextLine();
while (!(answer.equals("quit"))) {
    answer = scanner.nextLine();
}
System.out.print("Ok");
  • • It's necessary to include answer = scanner.nextLine(); inside the loop braces. Failure to update the condition variable inside the loop body will result in an infinite loop.

Loops with General Condition

Important: Loops with a general condition are implemented in programs when we cannot determine the exact number of repetitions before entering the loop.

In many programming tasks, it's impossible to determine the exact number of loop repetitions before execution begins. Let's write a program ComputeProduct that calculates and displays the product of entered integers until their product is less than 10000.

import java.util.Scanner;

public class ComputeProduct {
    public static void main(String[] args) {
        int n, product;

        Scanner input = new Scanner(System.in);

        product = 1;
        while (product < 10000) {
            // Display the product
            System.out.println(product);
            // Get an integer
            System.out.print("Enter an integer: ");
            n = input.nextInt();
            // Update the product
            product *= n; 
        }
    }
}

Recall the AdditionQuiz program that asked the user to enter the answer to a sum of two single-digit numbers. Now, using a while loop with a general condition, this program can be rewritten to allow the user to repeatedly enter a new answer until it becomes correct, as shown in the RepeatAdditionQuiz program.

import java.util.Scanner;

public class RepeatAdditionQuiz {
    public static void main(String[] args) {
        int number1, number2, answer;

        Scanner input = new Scanner(System.in);

        // Generate two random integers number1 and number2
        number1 = (int)(Math.random() * 10);
        number2 = (int)(Math.random() * 10);

        // Get answer to "What is number1 + number2?"
        System.out.print(
            "What is " + number1 + " + " + number2 + "? ");
        answer = input.nextInt();

        // While answer is incorrect, request a new answer
        while (number1 + number2 != answer) {
            System.out.println("Wrong answer. Try again. ");
            System.out.print("What is " + number1 + " + " + number2 + "? ");
            answer = input.nextInt();
        }
        System.out.println("You got it!");
    }
}

The while loop in lines 19–23 repeatedly prompts the user to enter an answer as long as number1 + number2 != answer evaluates to true. Once number1 + number2 != answer becomes false, the loop exits.

Counter-Controlled Loops

Important: A counter-controlled while loop is used when we can determine before execution exactly how many loop repetitions are needed to solve the task. This number should appear in the loop condition as the final value.

The following code snippet calculates and displays the salaries of seven company employees. The loop body is the block of statements starting on the third line. The body gets input data to calculate an employee's salary and computes and displays that employee's salary. After displaying seven salaries, the message "All employees processed" is displayed.

count_emp = 0; // no employees processed yet
while (count_emp < 7) { // check count_emp value
    System.out.print("Enter hours worked: ");
    double hours = input.nextDouble();
    System.out.print("Enter hourly rate in rubles: ");
    double rate = input.nextDouble();
    double pay = hours * rate;
    System.out.println("Salary is " + pay + " rub.");
    ++count_emp; // move to next employee
}
System.out.println("\nAll employees processed.\n");

In this code snippet, three lines with comments directly control the loop. In the first statement count_emp = 0;, the variable count_emp stores the initial value 0, representing the number of employees already processed. The second line evaluates the condition count_emp < 7. If the condition is true, the block of statements representing the loop body executes, reading a new pair of input data and computing and displaying a new salary. In the last statement of the loop body ++count_emp;, 1 is added to the current value of count_emp. After the last step in the loop body, control returns to the line starting with while, and the condition is reevaluated for the next value of count_emp. The loop body executes once for each value of count_emp from 0 to 6 inclusive. Finally, count_emp becomes 7, and the condition becomes false. Once this happens, the loop body doesn't execute, and control passes to the statement System.out.println("\nAll employees processed.\n"); after the loop body.

Sentinel-Controlled Loops

Exit from a sentinel-controlled loop occurs as a result of reading a terminal marker following the last data item.

In many programs with loops, one or more additional data items are entered each time during the repetition of the loop body. Often we don't know how many data items the loop should process when it begins execution, so we must find some way to signal the program to stop reading and processing new data items.

One way to do this is to instruct the user to enter a unique value after the last data item, called a sentinel. The loop repetition condition checks each data item and causes exit from the loop when the sentinel is read. The sentinel value must be chosen carefully, as it should be a value that doesn't appear in the data items.

The SumScores program uses a while loop with a sentinel to sum exam scores regardless of their number.

import java.util.Scanner;

public class SumScores {
    public static void main(String[] args) {
        final int SENTINEL = -99;

        int sum, score;

        Scanner input = new Scanner(System.in);

        // Get score for first exam
        System.out.print("Enter score for first exam or "
            + SENTINEL + " to quit: ");
        score = input.nextInt();

        // Until sentinel is received,
        // get score for next exam and accumulate sum
        sum = 0;
        while (score != SENTINEL) {
            sum += score;
            System.out.print("Enter score for next exam or "
                + SENTINEL + " to quit: ");
            score = input.nextInt();
        }
        
        // Display sum of all exam scores
        System.out.println("Sum of all exam scores is " + sum);
    } 
}

Do-while Loop

Important: The do-while loop is similar to while and for loops, except that it executes the loop body first, then checks the loop repetition condition at the end.

  • • A do loop is very similar to a while loop, with the exception that a do loop will always execute the body of the loop at least once. In a while loop, if the condition is false from the start, the body of the loop will never execute.
  • • You might want to use a do loop if you know that the code will only execute in response to a user prompt for data. In this case, you know that the application will need to process at least one piece of data, and can, therefore, use a do loop.
String answer;
        
do {
    // Process the data
    answer = scanner.nextLine();
} while (!answer.equals("Quit"));

Example: The ValidateLetter program uses a do-while loop to validate letter input within a specified range.

import java.util.Scanner;

public class ValidateLetter {
    public static void main(String[ ] args) {
        String s;
        char letter_choice;
        
        Scanner input = new Scanner(System.in);

        do {
            System.out.print("Enter a Latin letter from A to E: ");
            s = input.nextLine();
            letter_choice = s.charAt(0);
        } while (letter_choice < 'A' || letter_choice > 'E');
    }
}

Here, the do-while loop prompts the user to enter a single Latin letter from A to E. After charAt(0) returns the first character in the read string, the loop repetition condition checks whether the variable letter_choice contains one of the required letters. If it does, the loop repetition condition becomes false, and the statement after the loop executes. If letter_choice contains some other letter, the condition is true, and the loop body repeats. Since we know that the program user will enter at least one character as input, the do-while statement is ideal for implementing input validation.

do-while Syntax Example
do {
  Statement(s)
} while (condition);
// Read until first even number
do {
  System.out.print("Enter an even number: ");
  num = input.nextInt();
} while ((num % 2) != 0);

Exception Handling

  • • Exceptions are the best mechanism for error handling. An exception is thrown by code with a run-time error, and caught by code that can handle the error. If the exception is not handled by a program, then the program terminates with a crash.
  • • An exception in Java is an object of java.util.InputMismatchException or some inherited class.
  • • Exceptions are handled in a try … catch block.
  • • When an exception appears inside a try block, program execution goes to the first appropriate exception handler – the catch block.
  • • If there are no handlers for the thrown exception, the program terminates with an error message.

Example 1:

import java.util.Scanner;
import java.util.InputMismatchException;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = 0;
        boolean flag = false;

        do {
            try {
                String s = scanner.nextLine();
                a = Integer.parseInt(s);
                flag = true;
            } catch (NumberFormatException e) {
                System.out.println(e.getMessage() + " Repeat input");
            }
        } while (!flag);

        System.out.println(a + " OK");
        scanner.close();
    }
}

Example 2:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = 0;
        String s = scanner.nextLine();
        
        try {
            a = Integer.parseInt(s);
            System.out.println(a + " OK");
        } catch (NumberFormatException e) {
            System.out.println("Wrong input");
        }
        
        scanner.close();
    }
}

Laboratory Work

Lab 1: While Loop

Objective: Ask the user to enter a number (N). Create a simple while loop with N repetitions that displays the values of the loop counter.

Expected Output:

Please enter a number and press Enter
3
The result: 
Current value of counter is 1
Current value of counter is 2
Current value of counter is 3

Please enter a number and press Enter
1
The result: 
Current value of counter is 1

File Name: L8Lab1.java
Class Name: L8Lab1

Algorithm:

  1. Create a new Java file named L8Lab1.java.
  2. Import the Scanner class: import java.util.Scanner;
  3. Define the class L8Lab1 with a main method.
  4. Inside the main method, create a Scanner object for input.
  5. Prompt the user with System.out.println("Please enter a number and press Enter");
  6. Read the integer input and store it in a variable N.
  7. Initialize counter = 1. Create a while loop: while (counter <= N)
  8. Inside the loop, print the counter value: System.out.println("Current value of counter is " + counter);
  9. Increment counter: counter++;
  10. Run the program (e.g., press F5 in your IDE).
  11. Test with different input values.
  12. Place the task description as a comment at the top of the file.
  13. Experiment by setting counter to a value greater than N and run the code.
  14. Format your code by pressing ALT + SHIFT + F.
  15. Extra Task: Think about how to check if entered data was a number. To make it possible you should use try...catch block.
  16. Upload the file to the learning management system.

Lab 2: Do-while Loop - Counter Values

Objective: Create a simple do..while loop with 5 repetitions that displays the values of the loop counter.

Expected Output:

The result: 
Current value of counter is 1
Current value of counter is 2
Current value of counter is 3
Current value of counter is 4
Current value of counter is 5

File Name: L8Lab2.java
Class Name: L8Lab2

Algorithm:

  1. Create a new Java file named L8Lab2.java.
  2. Import the Scanner class: import java.util.Scanner;
  3. Define the class L8Lab2 with a main method.
  4. Initialize counter = 1. Create a do..while loop: do { ... } while (counter <= 5);
  5. Inside the loop, print the counter value: System.out.println("Current value of counter is " + counter);
  6. Increment counter: counter++;
  7. Run the program (e.g., press F5 in your IDE).
  8. Test with different values to see the output.
  9. Place the task description as a comment at the top of the file.
  10. Format your code by pressing ALT + SHIFT + F.
  11. Upload the file to the learning management system.

Lab 3: Do-while Loop with Sentinel and Exception Handling

Objective: An integer sequence is entered. The indication of completion of the sequence is the number 0 (if 0 is entered, input of numbers terminates). Output the minimum number in the sequence. Use a do..while loop. It is not allowed to use the standard min function.

Expected Output:

Please enter the sequence of numbers and finish with 0
3 5 1 0
the minimum number is 1

File Name: L8Lab3.java
Class Name: L8Lab3

Algorithm:

  1. Create a new Java file named L8Lab3.java.
  2. Import the required classes: import java.util.Scanner; and import java.util.InputMismatchException;
  3. Define the class L8Lab3 with a main method.
  4. Inside main, create a Scanner object for input.
  5. Prompt the user: System.out.println("Please enter the sequence of numbers and finish with 0");
  6. Declare variables: int numb; and int min = Integer.MAX_VALUE;
  7. Create a try-catch block to handle exceptions.
  8. Inside the try block, create a do..while loop: do { ... } while (numb != 0);
  9. Inside the loop, read input: numb = Integer.parseInt(scanner.nextLine());
  10. Check if numb != 0 and numb < min, update min if true.
  11. In the catch block, handle NumberFormatException with an appropriate message.
  12. After the loop, output the result: System.out.println("the minimum number is " + min);
  13. Run the program and test with various inputs, including non-numeric values.
  14. Format your code by pressing ALT + SHIFT + F.
  15. Upload the file to the learning management system.

Assignments

Assignment 1: Employee Salary Calculator

Objective: Write a program that calculates and displays the salary of each employee, as well as the company's total salary, based on hours worked by each employee and hourly rate in rubles.

Input:
int number_emp; // number of employees
double hours; // hours worked
double rate; // hourly rate in rubles

Variables:
int count_emp; // current employee
double pay; // current employee's salary in rubles
double total_pay; // company's total salary

Formulas:
pay = hours * rate;
total_pay = total_pay + pay;
count_emp = count_emp + 1;

Expected Output:

Enter number of company employees:
2
Enter hours worked:
20
Enter hourly rate in rubles:
400
Salary = 8000
Enter hours worked:
55
Enter hourly rate in rubles:
400
Salary = 22000
All employees processed
Total company salary = 30000 rub

File Name: L8Assign1.java
Class Name: L8Assign1

Tasks for Independent Work

Task 1: While and Do-while - Sequences with General Condition

To do: Output the sequence 3 5 7 9 ... 21 (from 3 to 21 with step = 2). Make it twice: using while and do..while loops.

Note: Within one project create two loops: while and do..while loops with different counters (counter1, counter2).

Expected Output:

3 5 7 9 11 13 15 17 19 21

File Name: L8Task1.java

Task 2: While and Do-while - Decreasing Sequence

To do: Output the sequence 15 12 9 6 3 0 (from 15 downto 0 with step = -3). Make it twice: using while and do..while loops.

Note: Within one project create two loops: while and do..while loops with different counters (counter1, counter2).

Expected Output:

15 12 9 6 3 0

File Name: L8Task2.java

Task 3: While - Multiplication of Even Numbers

To do: Calculate the multiplication of 2-digit even integers in the interval [10;20] (10 * 12 * 14 * 16 * 18 * 20). Use a while loop.

Note: Use a variable named product. Start with product = 1.

Expected Output:

10 * 12 * 14 * 16 * 18 * 20 = 9676800

File Name: L8Task3.java

Task 4: While - Sum of Five Numbers

To do: Five real numbers are entered. Calculate the sum of the numbers. Use a while loop.

Note: Use variables of type double: double sum = 0; double numb;

Expected Output:

Please enter 5 numbers and press Enter 1 4 2 9 2 The sum of inputted numbers = 18

File Name: L8Task4.java

Task 5: Do-while - Maximum Number in Sequence

To do: A sequence of integers is entered. The indication of completion is the number 0 (if 0 is entered, input terminates). Output the maximum number in the sequence and its position. Use a do..while loop. It is not allowed to use the standard max function.

Expected Output:

Please enter the sequence of numbers and finish with 0 3 5 1 0 the maximum number is 5, its position is 2

File Name: L8Task5.java

Task 6: While - Power of Two Sequence

To do: Write a program using a counter-controlled while loop that displays the following output in the console:

0 1
1 2
2 4
3 8
4 16
5 32
6 64

File Name: L8Task6.java

Task 7: While with Sentinel - Count Positive and Negative Numbers

To do: Write a program that requests numeric values from the user and outputs the count of positive and negative entered values. Use 0 as the sentinel value.

Expected Output:

1 5 3 -6 8 -2 0 4 positive, 2 negative

File Name: L8Task7.java

Task 8: Chessboard Pattern

To do: Create the appropriate nested looping structure to output the characters in an 8×8 grid on the screen using System.out.print() or System.out.println() as appropriate. Include a decision structure to ensure that alternate rows start with opposite characters as a real chess board alternates the colors among rows.

Expected Output:

XOXOXOXO
OXOXOXOX
XOXOXOXO
OXOXOXOX
XOXOXOXO
OXOXOXOX
XOXOXOXO
OXOXOXOX

File Name: L8Task8.java

Task 9: Do-while and Try Block - Interactive Input Validation

To do: Write a program with an interactive input validation loop that reads pairs of integers until it encounters a pair where one number is a multiple of the other.

Expected Output:

2 3
5 7
6 2  stop: 6 is a multiple of 2

File Name: L8Task9.java

Lesson 8: While Loops.

◄ Lesson # 7: For and Foreach
Skip Navigation
Navigation
  • Home

    • Site pages

      • My courses

      • Tags

    • My courses

    • Courses

      • Весенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

        • МО_4курс

        • KP

        • АБМ1_ИИБ_25-26

        • Java Eng

          • Lesson 0. Introduction

          • Basic Programming Language Constructs

            • AssignmentLesson 1. Programming on Java in Microsoft Visual ...

            • AssignmentLesson 2. Data Types and Type Casting. Boolean type

            • AssignmentLesson 3. Java Conditional statement IF

            • AssignmentLesson 4: Ternary Operator and Switch Statement

            • AssignmentLesson #5: Mathematical Functions in Java

            • AssignmentLesson #6: Characters and Strings in Java

            • AssignmentLesson # 7: For and Foreach

            • AssignmentLesson 8: While Loops

          • Methods (functions)

          • Arrays

          • Topic 5

          • Topic 6

          • Topic 7

          • Topic 8

          • Topic 9

          • Topic 10

          • Topic 11

          • Topic 12

          • Topic 13

          • Topic 14

          • Topic 15

          • Topic 16

        • МО (ПО)

      • Осенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

      • Воскресная компьютерная школа

        • Пользователь компьютера плюс

        • Пользователь прикладных программ

        • Программирование I ступень

        • Программирование II ступень

        • Программирование III ступень

        • Архив

      • Воскресная математическая школа

        • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2025

        • Олимпиадная математическая школа

        • Повышение квалификации

        • Доступная математика

        • Лаборатория математического онлайн-образования мех...

        • Осенняя универсиада

        • Научно-практическая конференция

        • ВМШ

          • ВМШ -2025

        • Летняя олимпиадная математическая школа РНОМЦ и ме...

      • Государственная итоговая аттестация

      • Дополнительное образование

      • Олимпиады

      • Видеолекции

      • Разное

      • Архив курсов

      • Заочная школа мехмата ЮФУ

You are currently using guest access (Log in)
Java Eng
Data retention summary
Get the mobile app Яндекс.Метрика