Advertisements
So my assignment is to write a program that used while loops to perform 6 different things. 1. prompt the users to input two integers: firstNum and secondNum (firstNum must be less than secondNum). 2. output all the odd numbers between firstNum and secondNum inclusive 3. output the sum of all the even numbers between firstNum and secondNum inclusive 4. output all the numbers and their squares between 1 and 10 5. output the sum of the squares of all the odd numbers between firstNum and secondNum inclusive 6. output all the uppercase letter. and lastly there is a hint: if currentNum % 2 = 0, then the currentNum is an even number. Otherwise it is an odd number.
Hi Friend,
Try the following code:
import java.util.*; public class NumberExample{ public static void main(String[]args){ int sum=0,sumSquares=0; int num1=0,num2=0; Scanner input=new Scanner(System.in); System.out.print("Enter First Number: "); num1=input.nextInt(); System.out.print("Enter Second Number: "); num2=input.nextInt(); if(num1>num2){ System.out.print("Your First Number is greater than second.So Please re-enter: "); num1=input.nextInt(); } else{ System.out.println("Odd Numbers: "); while(num1 <= num2) { if(num1%2 != 0) { System.out.println(num1); sumSquares+=(num1*num1); } if(num1%2 == 0) { sum+=num1; } num1++; } System.out.println("Sum Of Even Numbers: "+sum); System.out.println("Numbers and their squares between 1 and 10"); int i=1; while(i <= 10) { System.out.println(i+" "+(i*i)); i++; } System.out.println("Sum Of square of odd Numbers: "+sumSquares); } } }
Thanks