Monday 3 October 2016

Q. Explain different types of Selection Control statements in JAVA with syntax. Write a program in JAVA to find the greatest number among three given numbers. Your program should take input from the user.

Answer
Control Statements
The statements inside your source files are generally executed from top to bottom, in the order that they appear Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. ava contains the following types of control statements:
1- Selection Statements
2- Repetition Statements
3- Branching Statements
Selection statements
If Statement:
This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skips if block and rest code of program is executed .
 Syntax:
if(conditional_expression){
 <statements>;
 ...;
 ...;
}
If-else Statement:
The "if-else" statement is an extension of if statement that provides another option when 'if' statement
evaluates to "false" i.e. else block is executed if "if" statement is false.
Syntax: if(conditional_expression){
 <statements>;
 ...;
 ...; }
 else{ <statements>;
 ....;
 ....;
 }
Switch Statement:
This is an easier implementation to the if-else statements. The keyword "switch" is followed by an expression
that should evaluates to byte, short, char or int primitive data types ,only. In a switch block there can be one
or more labeled cases. The expression that creates labels for the case must be unique. The switch expression
is matched with each case label. Only the matched case is executed ,if no case matches then the default
statement (if present) is executed.
Syntax:
 switch(control_expression){ case
expression 1: <statement>; case
expression 2: <statement>;
 ...
 ... case expression n:
<statement>; default:
 <statement>;
 }//end switch


Write a program in JAVA to find the greatest number among three given numbers. Your program should take input from the user
Answer.

import java.io.*;
class GreatestNumber
{
public static void main(String args[]) throws java.lang.Exception
{
int n1,n2,n3;
BufferedReader buffer = new BufferedReader (new InputStreamReader(System.in));
System.out.println("Enter First number");
n1=Integer.parseInt(buffer.readLine());
System.out.println("Enter Second number");
n2=Integer.parseInt(buffer.readLine());
System.out.println("Enter Third number");
n3=Integer.parseInt(buffer.readLine());
if(n1>n2)
{
if(n1>n3)
{
System.out.println("n1 = "+n1+" is greater");
}
else
{
System.out.println("n3 = "+n3+" is greater");
}
}
else
{
if(n2>n3)
{
System.out.println("n2 = "+n2+" is greater");
}
else
{
System.out.println("n3 = "+n3+" is greater");
}
}
}
}
sos

No comments:

Post a Comment