Page 67 - CTS - CSA TP - Volume 2
P. 67
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 89 : Use the Break and Continue Keywords
Objectives
At the end of this exercise you shall be able to
• know the syntax break and continue statements and its use
• develop Java programs using break and continue statements.
Requirements
Tools/Materials
• PC/Laptop with Window OS
• JDK Software
• Text editor (Visual studio / Sublime / Note pad)
Procedure
TASK 1: Using break in a Loop
import java.util.Scanner;
public class BreakExample {
public static void main(String[] args) {
// This program searches for a specific number in a loop
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter the target number: “);
int target = scanner.nextInt();
boolean found = false;
// Search for the target number in a loop
for (int i = 1; i <= 10; i++) {
if (i == target) {
found = true;
break; // Exit the loop when the target number is found
}
}
if (found) {
System.out.println(“The target number “ + target + “ is found.”);
} else {
System.out.println(“The target number “ + target + “ is not found.”);
}
scanner.close();
}
}
Output:
52