Page 63 - CTS - CSA TP - Volume 2
P. 63
COMPUTER SOFTWARE APPLICATION - CITS
TASK 3: Countdown using a while loop
import java.util.Scanner;
public class WhileCountdown {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter a starting number for countdown: “);
int count = scanner.nextInt();
while (count >= 0) {
System.out.println(count);
count--;
}
System.out.println(“Blastoff!”);
scanner.close();
}
}
Output:
This program uses a while loop to create a countdown starting from a user-specified number. It prints the
countdown and then displays “Blastoff!” when the countdown reaches 0.
TASK 4: Factorial Calculation using while loop
import java.util.Scanner;
public class WhileFactorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter a number to calculate its factorial: “);
int number = scanner.nextInt();
int factorial = 1;
int i = 1;
while (i<= number) {
factorial *= i;
i++;
48
CITS : IT & ITES - Computer Software Application - Exercise 87