Write a class that uses DO-WHILE loops to perform the following steps:
a) prompt the user to input two integers: firstNum and secondNum. firstNum must be less than secondNum (data validation should always be a while loop with lead and looping prompts)
b) output all the odd numbers from firstNum to secondNum. Also output all the even numbers from firstNum to secondNum
c) output the sum of all the even numbers from firstNum to secondNum
d) output all the numbers from firstNum to secondNum and their squares
e) output the sum of the squares of all the odd numbers from firstNum to secondNum

Respuesta :

Answer:

  1. import java.util.Scanner;
  2. public class Main {
  3.    public static void main(String[] args) {
  4.        Scanner input = new Scanner(System.in);
  5.        int firstNum, secondNum;
  6.        do{
  7.            System.out.print("Input first number: ");
  8.            firstNum = input.nextInt();
  9.            System.out.print("Input second number: ");
  10.            secondNum = input.nextInt();
  11.            for(int i= firstNum; i <= secondNum; i++){
  12.                if(i % 2== 1){
  13.                    System.out.print(i + " ");
  14.                }
  15.            }
  16.            System.out.println();
  17.            int evenSum = 0;
  18.            for(int i= firstNum; i <= secondNum; i++){
  19.                if(i % 2== 0){
  20.                    System.out.print(i + " ");
  21.                    evenSum += i;
  22.                }
  23.            }
  24.            System.out.println();
  25.            System.out.println("Sum of even: " + evenSum);
  26.            System.out.println();
  27.            int squareOddSum = 0;
  28.            for(int i= firstNum; i <= secondNum; i++){
  29.                System.out.println(i + " : " + (i*i) );
  30.                if(i % 2 ==1){
  31.                    squareOddSum += i;
  32.                }
  33.            }
  34.            System.out.println();
  35.            System.out.println("Sum of squared odd number: " + squareOddSum);
  36.        }while(firstNum < secondNum);
  37.    }
  38. }

Explanation:

The solution code is written in Java.

Firstly, we create a Scanner object (Line 6) and use it get user input for first and second number (Line 10-13). We create a for loop and use modulus to check the current number is divisible by 2 and print out the odd number in loop (Line 15-19). We repeat the similar step to print the even number but at the same time, we also add the current number to evenSum variable and print the sum after the for loop (Line 23-33).

Next, we proceed to use another for loop to print out the number and their squares and then accumulate the sum of squares of all odd numbers (Line 36-41).

At last, we print out the sum of squares of odd numbers (Line 43).

In the do while loop condition,  if firstNum is smaller than secondNumber, the loop is ongoing (Line 45).