Page 61 - CTS - CSA TP - Volume 2
P. 61
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 87 : Use the Do … While and While – do loops
Objectives
At the end of this exercise you shall be able to
• know the syntax of while and do…while loops and its use
• develop Java programs using while and do…while loops.
Requirements
Tools/Materials
• PC/Laptop with Window OS
• JDK Software
• Text editor (Visual studio / Sublime / Note pad)
Procedure
Both do-while and while loops are control flow structures in Java used for repetitive execution of a block of code.
They differ primarily in when the loop condition is evaluated.
TASK 1: Sum of numbers using a do-while loop
import java.util.Scanner;
public class DoWhileSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int number;
do {
System.out.print(“Enter a number (enter 0 to exit): “);
number = scanner.nextInt();
sum += number;
} while (number != 0);
System.out.println(“Sum of entered numbers: “ + sum);
scanner.close();
}
}
Output:
This program uses a do-while loop to repeatedly prompt the user to enter numbers until they enter 0. It calculates
and prints the sum of all entered numbers
46