In: Computer Science
Java program
Use Do-while
Write a do-wile loop that asks the user to enter two numbers. The numbers should be added and the sum displayed. The loop should ask the user whether he or she wishes to perform the operation again. If so, the loop should repeat, otherwise, it should terminate.
Use Continue branching statement
Write a program that reads an integer and display all the positive ODD numbers from 0 to n (integer entered by the user). Use CONTINUE branching statement to skip the display of EVEN in the result.
Dear Student ,
As per the requirement submitted above , kindly find the below solution.
Question 1 :Do While Loop
Here a new java program with name "DoWhileNumbers.java" is created, which contains following code.
DoWhileNumbers.java :
import java.util.*;//import package
//Java class
public class DoWhileNumbers {
//entry point of program , main() method
public static void main(String[] args) {
// creating object of Scanner
class
Scanner sc=new
Scanner(System.in);
//using do while loop asking user
to enter numbers
do
{
//asking user to
enter number 1
System.out.print("Enter Number 1: ");
int
num1=sc.nextInt();//reading number1
//asking user to
enter number 2
System.out.print("Enter Number 2: ");
int
num2=sc.nextInt();//reading number2
//print
result
System.out.println("Sum of "+num1+" and "+num2+" is :
"+(num1+num2));
//asking user
whether want to perform operation again
System.out.print("Want to sum another numbers : ");
String
response=sc.next();//reading response
//checking
response
if(response.equals("Yes"))
{
continue;
}
else
{
break;
}
}while(true);
}
}
======================================================
Output : Compile and Run DoWhileNumbers.java in the browser and will get the screen as shown below
Screen 1 :DoWhileNumbers.java
**************************************
Question 2:
OddNumbers.java :
import java.util.*;//import package
//Java class
public class OddNumbers {
//entry point of program , main() method
public static void main(String[] args) {
// creating object of Scanner
class
Scanner sc=new
Scanner(System.in);
//asking user to enter number
System.out.print("Enter Number :
");
int num=sc.nextInt();//reading
number
if(num >0)
{
//using for loop checking
numbers
for(int i=1;i<=num;i++)
{
//checking odd
numbers
if(i%2!=0)
{
//display odd number
System.out.print(i+" ");
}
else
{
continue;//continue the loop
}
}
}
else
{
//when negative
number is entered
System.out.print("Enter number greater than 0 ");
}
}
}
============================
Screen 1 :Screen when number less than 0 is entered
Screen 2 :Screen showing positive odd numbers
NOTE : PLEASE FEEL FREE TO PROVIDE FEEDBACK ABOUT THE SOLUTION.