In this task, you are being asked to write a loop in Java.
Write a program that uses while loops to perform the following steps:
a) Prompt the user to input two integers: startingNum and endingNum (startingNum must be
less than endingNum).
b) Output all even numbers between startingNum and endingNum.
c) Output the sum of all even numbers between startingNum and endingNum.
d) Output the numbers and their squares between startingNum and endingNum.
e) Output the sum of the square of the odd numbers between startingNum and endingNum.
1. Create a program called WhileLoops.java. All loops will be written in this file.
2. Create appropriate variables and assign values using a Scanner object.
3. Correctly display appropriate messages.
import java.util.Scanner;
public class WhileLoops {
/** Main Method */
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in); // Create a Scanner
int startingNum = 2;
int endingNum = 1;
while (startingNum > endingNum) {
System.out.print("Enter first number: ");
startingNum = keyBoard.nextInt();
System.out.print("Enter second number (must be more than first number): ");
endingNum = keyBoard.nextInt();
if (startingNum > endingNum) {
System.out.print("First number must be less than second number. Try again. \n");
}
}
System.out.println("");
System.out.println("All even numbers between first number and second number:\n");
int number = startingNum;
int sum = 0;
while (number <= endingNum) {
if (number % 2 == 0) {
System.out.println(number + " ");
sum += number;
}
number++;
}
System.out.println("\nThe sum of all even numbers between first number and second number: " + sum);
// d. Output the numbers and their squares between 1 and 10.
System.out.println("The numbers and their squares between first number and second number");
number = 1;
while (number <= endingNum)
{
System.out.println(number + " -> " + number + "^2" + " = " + (number * number));
number++;
}
System.out.println();
number = startingNum;
sum = 0;
while (number <= endingNum) {
if (number % 2 != 0) {
sum += (number * number);
}
number++;
}
System.out.println("The sum of the square of the odd numbers between first number and second number: " + sum);
keyBoard.close();
}
}
Comments
Leave a comment