Sunday, 17 May 2015

LOOPING

LOOPING
4.1 Basic element of Loop-there are three basic elements of the loop:-
Initializations , test expression, update expressions
Initialization are the statement which specify what should be the initial value of the variable which is been used to control the loop
Test expression is the condition which specifies that loop will continue or not.
Update expression is the statement which changes the value of the control variable as per requirement of the program.

4.2 Explain While statement
The while is a looping statement. Looping statements control execution of a series of other statements, causing  part of a program to execute repeatedly as long as a certain statement is met.
while(test expression)
{
 // program statement(s)
}

Ex1:-     num=1;
            while(num<=5)
            {
             System.out.print(num+”  “);
             num --
}
Output :- 1  2  3  4  5

Pragram 1.
 program to input a number and display factorial of it.
import java.util.*;
class check8
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int n,fact,i;
System.out.println(“enter a number”);
n=Sn.nextInt();
fact=1;
i=1;
while(i<=n)
{
fact=fact*i;
i=i+1;
}
System.out.println(“factorial of “+n+” is “+fact);
}
}
Pragram 2.
program to input a number and find its sum of digit, number of digit, reverse of number
import java.util.*;
class check7
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int dig,num,rev,len,sum,cp;
System.out.println(“enter a number”);
num=Sn.nextInt();
cp=num;
sum=0;
rev=0;
len=0;
while(cp!=0)
{
dig=cp%10;
sum=sum+dig;
len++;
rev=rev*10+dig;
cp=cp/10;
}
System.out.println(“length of number ”+len);
System.out.println(“sum of digits ”+sum);
System.out.println(“sum of digits ”+rev);
}
}

4.3 DO- WHILE STATEMENT:-
This loop is similar to the while loop except the test expression occurs at the bottom of the loop. this ensures that the body executes at least one time.
Syntax:-           do
                        {
                        Statement(s);
                        }while(test expression);
It will repeat statements given in the loop till condition given with it is true.
Exmple
int num=10;
do
{
System.out.println(num);
num--;
}while(num>=1);
This loop will print numbers from 10 to 1.

4.4 Explain the term the for loop  with an example [2005]
THE FOR LOOP:- The for loop is easy to use, normally we use for loop when number of times statements is to be repeated is known. The for loop has initialization, test expression, update statement at the beginning of the loop.
Syntax:-
            for(initialization;condition;increment)
            {
            Statement(s)
            }
In for loop all these three loop control statements are optional.
Example
            for(i=1;i<=10;i++)
            {
            System.out.println(i);
            }
it will display numbers from 1 to 10.

Example 2
            for(i=1,j=2;;i<=5;i++,j++)
            {
            System.out.print(i+”/”+j+”+”);
            }
            System.out.print(“\b”);
Above given loop will display
1/2+2/3+3/4+4/5+5/6

Example 3
            for(i=1;i<=10;i++);
            System.out.print(i);
It will display 11

Example 4
            for( ; ; )
            {
            System.out.println(“hello”);
}
It will display hello infinite times

4.5 EMPTY LOOP /TIME DELAY LOOP
The loop which do not have body with it is called empty loop this type of loop are used to give some interval before starting some process.
Example
for(i=1;i<=1000000;i++);
System.out.println(“computer “);
Here it will keep counting 1to 1000000 then display given message .

4.6  State one similarity and one difference between while loop and do while loop.                   [2005]
Similarity:- Both are looping statement they execute given statement till given condition is satisfied.
Difference:- While is an entry control loop. condition is checked first then body of the loop get executed. Do-while is exit control loop. Body of the loop executes first then condition is checked

4.7 Break: The break statement is used in many programming languages such as c, c++, java etc. Some times we need to exit from a loop before the completion of the loop then we use break statement and exit from the loop and loop is terminated. The break statement is used in while loop, do - while loop, for loop and also used in the switch statement.
Example
for(i=1;i<100;i++)
{
if(i%9==0)
break;
System.out.println(i)
}
It will display number from 1 to 8 as soon as i will become 9 loop will terminate.


4.8 Continue: The continue statement is used in many programming languages such as C, C++, java etc. Sometimes we do not need to execute some statements under the loop then we use the continue statement that stops the normal flow of the control and control returns to the loop without executing the statements written after the continue statement. There is the difference between break and continue statement that the break statement exit control from the loop but continue statement keeps continuity in loop without executing the statement written after the continue statement according to the conditions
Example
for(i=1;i<100;i++)
{
if(i%9==0)
continue;
System.out.println(i)
}
It will display number from 1 to 99 except numbers which are divisible be 9 because  as soon (i%9==0) condition will be true it will skip display statement.

4.9 RETURN STATEMENT: The return statement can be used to cause execution back to the caller to the method. Thus the return statement immediately terminates the method in which it is executed.


4.10  Explain break and continue statements. [2005] [2008]
break statement sends the control out of the loop. continue statement skips part of loop and goes for next iteration.
for(i=1;i<10;i++
{
if(i%2==0)
continue;
if(i==9)
break;
System.out.print(i);
}
in above example when i is even number then it will skip part of program and go for next iteration and when i is 9 it will terminate loop.
output will be 1357

4.11 DIFFERENCE BETWEEN WHILE AND DO-WHILE
WHILE LOOP
DO-WHILE LOOP
The while loop will not execute at all if the condition is not satisfied
The do while loop will execute at least once.

The while loop checks the condition first and then the execution begins
The do-while check the condition after executing the loop once

4.12 DIFFERENCE BETWEEN    FOR AND WHILE LOOP

FOR LOOP
WHILE LOOP
It is used when we know in advance how many repetitions are to be done
It is used when we do not know the number of repetitions are to be done.
The initialization, condition check and update is done at one line.
Here initialization, condition check and update is done at difference places.

Find and correct the errors in the following program segment:-                         [2006]
int n[]=(2,4,6,8,10);
for(int i=0;i<=5;i++)
System.out.println(“n[“+i+”]=”+n[i]);
The corrected program segment is:-
int n[]={2,4,6,8,10};
for(int i=0;i<5;i++)
System.out.println(“n[“+i+”]=”+n[i]);

Find the output of the following program segment, when:                                   [2006]
i)val=500
ii) val=1600
int val,sum,n=550;
sum=n+val>1750?400:200;
System.out.println(sum);
Output:- 200 for val =500
IMPORTANT  POINTS

ü  The statement within the block is executed one after the other. This type of structure is called sequential structure.

ü  Use of goto statement creates an unconditional jump within program.
ü  Control structure is used when tranfer of control takes place to the other part of the program depending on some conditon. 
ü  Java offers three selection statements: if, if...else and switch.
ü  While if statement checks only for the condition that evaluates true, if...else structure checks for both truth and falsity of a condition.
ü  The switch structure in Java consists of series of case keyword.
ü  Each of the case value must be a unique literal constant and not a variable.
ü  break statement  is used to skip out of switch structure.
ü  Switch structure is an efficient way of writing multiple if statements that contains only equality conditions of integral values.
ü  Repetitive statements in programming are called iteration or looping.
ü  In Java the looping statements for, while and do...while are used for performing iteration.
ü  Initialization part of the loop  contains assignment of value to a  control variable.
ü  Condition part of the loop is to test whether a boolean expression evaluates to true or false.
ü  Modification part is used for updating the initial value of the control variable.
In nested loops the iteration of innermost loop is done first and the Pragram 2.
ü  outermost at the end.
ü  For executing a statement or a block of codes repeatedly a specified number of times for loop is used.
ü  while and dowhile loops can be used where the number of iteration is not known before hand.
ü  break statement skips the rest of the statement of the body of the loop and exits the loop before the iteration is completed.
ü  continue statement forces to skip the rest of the statement of the body of the loop before the loop finishes the  iteration and passes control to execute the next  iteration of the loop.
ü  break and continue statements used with label can transfer control to any part of the program.
ü  When break and continue statements are used within nested loops the inner loop gets affected.

EXAMPLE PROARAMS
Program 3.
program to display first 10 terms of fabonacci series:-
0,1,1,2,3,5,8,13,21,34
class febo
{
public static void main(String args[])
{
int i,fn,sn,cu;
fn=0;
sn=1
System.out.print( fn+”\t”+sn+”\t”);
for(i=3;i<=10;i++)
{
cu=fn+sn;
System.out.print( cu+”\t”);
fn=sn;
sn=cu;
}
}
}


Program 4.
 program to input a number and display it is prime or not.
import java.util.*;
class checkprime
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int num,i,ctr;
ctr=0;
System.out.println( “enter a number”);
num=Sn.nextInt();
for(i=1;i<=num;i++)
{
if(num%i==0)
ctr++;
}
if (ctr<=2)
System.out.println( num+”is prime);
else
System.out.println( num+”is not prime);
}
}

Program 5
program to check a number is Armstrong or not
import java.util.*;
class armstrong
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int num,sum,i,dig;
System.out.println( “enter a number”);
num=Sn.nextInt();
sum=0;
for(i=num;i!=0;i=i/10)
{
dig-i%10;
sum=sum+dig*dig*dig;
}
if(sum==num)
System.out.println( num+”is Armstrong”);
else
System.out.println( num+”is not Armstrong “);
}
}
Program 6
program to input Two numbers and display highest common factors of the numbers using long division method.
import java.util.*;
class high
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int a,b,x,y,r;

System.out.println( “enter two number”);
a=Sn.nextInt();
b=Sn.nextInt();
if(a<b)
{
x=a;
y=b;
}
else
{
x=b;
y=a;
}
while(true)
{
r=y%x;
if(r==0)
break;
y=x;
x=r;
}
System.out.println(“hcf of “+a+” and “+b+              ” is    “+x);
}
}
Program 7
 program to input Two numbers and display highest common factors of the numbers using long division method.
import java.util.*;
class high
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int a,b,h;
System.out.println( “enter two number”);
a=Sn.nextInt();
b=Sn.nextInt();
for(i=1;i<=a;i++)
{
if(a%i==0 && b%i==0)
h=i;
}
System.out.println(“hcf of “+a+” and “+b+              ” is    “+h);
}
}
Program 8
program to input Two numbers and display Least common Mutiple(LCM) of the numbers using long division method.
import java.util.*;
class high
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int a,b,lcm;
System.out.println( “enter two number”);
a=Sn.nextInt();
b=Sn.nextInt();
lcm=a;
while(lcm%b!=0)
{
lcm=lcm+a;
}
System.out.println(“lcm of “+a+” and “+b+              ” is    “+lcm);
}
}
Program 9
program to input numbers till the users choice find sum of even, odd numbers.
import java.util.*;
class user
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int num,ev=0,od=0
char ch=’y’;
while(ch==’y’ || ch==’Y’)
{
num=Sn.nextInt();
if(num%2==0)
ev=ev+num;
else
od=od+num;
System.out.println( “press y to continue”);
ch=Sn.next().charAt(0);
}
System.out.println( “sum of even”+ev);
System.out.println( “sum of odd”+od);
}
}
Program 10
Program to display prime number between 1 to 50
public class Break{
public static void main(String[] args){
int i,j;
System.out.println("Prime numbers between 1 to 50 : ");
for (i = 1;i < 50;i++ ){
for (j = 2;j < i;j++ ){
if(i % j == 0)
{
break;
}
}
if(i == j)
{
System.out.print(" " + i);
}
}
}
}
//output
 The Prime number in between 1 - 50 :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Program 11

 menu driven program to input a number and display is perfect or not , palindrome or not.
import java.util.*;
class menu
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int num,i,dig,rev,sum,choice=1;
while(choice!=0)
{
System.out.println( “1 . perfect number”);
System.out.println( “2. palindrome number”);
System.out.println( “0. exit”);
System.out.println( “enter your choice”);
choice =Sn.nextInt();
switch(choice)
{
case 1: System.out.println( “enter a number”);
            num=Sn.nextInt();
            sum=0;
           
for(i=1;i<num;i++)
{
if(num%i==0)
sum=sum+i;
}
if (sum==num)
System.out.println(num+” is perfect no.”);
else
System.out.println(num+” is not perfect no.”);
 Break;
case 2: System.out.println( “enter a number”);
            num=Sn.nextInt();
            rev=0;
            for(i=num;i!=0;i=i/10)
            {
            dig=i%10;
            rev=rev*10+dig;
            }
            if(rev==num)
System.out.println( num+” is palindrome”);
else
System.out.println( num+” is not palindrome”);
            break;
case 0  : break;
default: System.out.println( “invalid option”);
            break;
}
}
}
}
Program 12

 menu driven program convert temperature from Fahrenheit to Celsius and Celsius to Fahrenheit [2007]
import java.util.*;
class menu
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int choice=1;
double cel,fah;
while(choice!=0)
{
System.out.println( “1 . Fahrenheit to Celsius”);
System.out.println( “2. Celsius to Fahrenheit”);
System.out.println( “0. exit”);
System.out.println( “enter your choice”);
choice =Sn.nextInt();
switch(choice)
{
case 1: System.out.println( “enter temp in       Fahrenheit”);
       feh=Sn.nextDouble()
cel=(feh-32)*5/9;
System.out.println(cel+” celsius”);
break;
case 2: System.out.println( “enter temp in       Celsius”);
       cel=Sn.nextDouble()
feh=(feh*9/5)+32;
System.out.println(feh+“Fahrenheit”);
 break;

case 0  : break;
default: System.out.println( “invalid option”);
            break;
}
}
}

Program 13
 program to find sum to given series using menu driven program
1+(1+2)/(1*2)+(1+2+3)/(1*2*3)+…….n terms
X+X2/3!+X3/3!+X4/4!..........................XN/N!
import java.util.*;
class menu
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int X,N,choice.i,p,q,f;
double sum,term;
while(choice!=0)
{
System.out.println( “1 . Series 1”);
System.out.println( “2. Series 2”);
System.out.println( “0. exit”);
System.out.println( “enter your choice”);
choice =Sn.nextInt();
switch(choice)
{
case 1: System.out.println( “enter a number”);
            n=Sn.nextInt();
            p=0;     q=1; sum=0.0;
for(i=1;i<=n;i++)
            {
            p=p + i ;
            q=q * i;
            sum=sum+ p/q;
            }
            System.out.println( “sum =”+sum);
            break;
case 2 : System.out.println( “enter x and n”);
            x=Sn.nextInt();
            n=Sn.nextInt();
            f=1; sum=0.0;
            for(i=1;i<=n,i++)
            {
            f=f* i;
            term=Math.pow(x,i)/f;
            sum=sum+term;
            }
            System.out.println(sum);
            break;
case 0: break;
default: System.out.println( “invalid choice”);
             break;
}
}
}
}
Program 14

 program to display given pattern
            55555
54444
            54333
            54322
            54321
class pattern
{
public static void main(String args[])
{
int x,y,z;         
for(x=5;x>=1;x--)
{
for(y=5;y>=x;y--)
System.out.print( y);
for(z=1;z<x;z++)
System.out.print(x);
System.out.println( );
}
}}
Program 15

//program to display  given pattern
             1
           212
         32123    
       4321234
     543212345
class pattern
{
public static void main(String args[])
{
int x,y,z,sp,s;  
for(i=1,sp=4;i<=5;i++,sp--)
{
  for(s=1;s<=sp;s++)
            System.out.print(“ “);
 for( y=i;y>=1;y++)
            System.out.print( y);
 for(z=2;z<=i;z++)
            System.out.print( z);
System.out.println( );
}
}}

Program 16

Write a program to print the sum of negative number, sum of positive even and sum of positive odd number from a list of number(N) entered by the user. the list is terminates when the user enter a zero.                               [2005]
import java.util.*;
class check
{
public static void main(String args[]) throws Exception
{
buffer
int n,sn=0,se=0,so=0;
for(;;)
{
System.out.println"enter a number 0 to stop");
n=Sn.nextInt();
if(n==0)
break;
if(n<0)
sn+=n;
else if(n %2==0)
se+=n;
else
so+=n;
}
           
System.out.println("sum of negative\t"+sn);
System.out.println("sum of positive even\t"+se);
System.out.println("sum of positive odd\t"+so);
}
}
Program 17

Write a program to calculate and print the sum of odd numbers and the sum of even numbers for the first n natural numbers.[2006]
The integer n is to be entered by the user.
import java.util.*;
class prog1
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int even=0,odd=0,i,n;
System.out.println(“Enter a number”);
n=Sn.nextInt();
for(i=1;i<=n;i++)
{
if(i%2==0)
   even=even+i;
else
      odd=odd+i;
}
System.out.println(“Sum of Even “+even);
System.out.println(“Sum of Odd “+odd);
}
}
}
Program 18

Write a program that outputs the results of the following evaluations based on number entered by the       [2006]
User:-
i.                    Natural Logarithm of the number.
ii.                  Absolute value of the number.
iii.                Square root of the number.
iv.                Random numbers between 0 and 1.
import java.util.*;
class menu
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int choice=1,n;
double cel,fah;
while(choice!=0)
{
System.out.println( “1 Natural Logarithm of the number.”);
System.out.println( “2. Absolute value of the number”);
System.out.println( “3. Square root of the number”);
System.out.println( “4. Random numbers between 0 and 1”);
System.out.println( “0. exit”);
System.out.println( “enter your choice”);
choice =Sn.nextInt();
switch(choice)
{
case 1: System.out.println( “Enter a number”);
            n =Sn.nextInt();
System.out.println(“Natural Logarithm =\t”+Math.log(n));
break;
case 2: System.out.println( “Enter a number”);
            n =Sn.nextInt();
System.out.println(“Absolute value =\t”+Math.abs(n));
break;
case 3: System.out.println( “Enter a number”);
            n =Sn.nextInt();
System.out.println(“Square Root =\t”+Math.sqrt(n));
break;
case 4: System.out.println(“Random Number =”+Math.random());
            break;
case 0  : break;
default: System.out.println( “invalid option”);
}
}
}
}


Program 19:- . Write a program to calculate and print the sum of each of the following series
Sum(S)= 2-4+6-8+……..20
Sum(S)= x/2+x/5+x/8+x/11….. +x/20
(value of x to be input by the user.) [2008]

import java.io.*;
class  abc
{
public static void main(String[] args) throws Exception
            {
DataInputStream d=new DataInputStream(System.in);
            int x,s,i;
                        s=0;
            for(i=2;i<=20;i=i+2)
            {
                        if(i%4==0)
                        s=s-i;
                        else
                        s=s+i;
            }
System.out.println("Sum is series 1 is "+s);
System.out.println("Enter a number");
x=Integer.parseInt(d.readLine());
double sum=0.0;
for(i=2;i<=20;i=i+3)
{
sum=sum+(double)x/i;
}
System.out.println("Sum is series 2 is "+sum);
}
}
Program 20:- Write a menu driven program to accept a number form the user and check whether it is a palindrome or a perfect number.
Palindrome number:- a number is a palindrome which when read in reverse order is same as read in the right order. E.g 11,101,151 etc.
Perfect number:- a number is called perfect if it is equal to the sum of its factors other than the number itself. E.g – 6=1+2+3

import java.util.*;
class menu
{
public static void main(String[] args)throws Exception
            {
Scanner Sn=new Scanner(System.in));
int ch=1,i,num=0,r;
while(ch!=0)
{
System.out.println("1. Palindrome number\n2. Perfect number");
System.out.println("0. exit\n Enter your choice");
ch=Sn.nextInt();
if(ch==1 || ch==2)
{
System.out.println("Enter a number");
            num=Sn.nextInt();
}
switch(ch)
{
case 1  :           r=0;    
                        for(i=num;i!=0;i=i/10)
                        r=r*10+i%10;
                        if(r==num)
            System.out.println("Palindrome");
                        else
            System.out.println("Not Palindrome");
                        break;
case 2:             r=0;
                        for(i=1;i<num;i++)
                        {
                        if(num%i==0)
                        r=r+i;
                        }
                        if(r==num)
                        System.out.println("Perfect no");
                        else
            System.out.println("Not perfect");
                        break;
case 0:             break;

default: System.out.println("invalid option");
            break;
}
}
}
}

Ques Convert the following segment into equivalent for loop.                             [2008]
            int i=1;
            while(i<=20)
            {
            System.out.println(i+" ");
            i++;
            }
Ans;- int i;
            for(i=1;i<=20;i++)
            {
              System.out.println(i+” “);

            }

CONDITON CHECKING

CONDITON CHECKING

There are three programming construct followed by java programming language
Ø  SEQUENCE
Ø  SELECTION/CONDITION CHECKING
Ø  REPETITION/ITERATION

3.1 SEQUENCE: - Sequence indicates the flow of control passes from one instruction to the next in sequence. In other word statement executes one after other in an order in which they are written.
3.2 SELECTION;-It indicates the flow of control depends upon condition. If one condition is true then one set of statement will execute otherwise another set of statement will execute.
There are two type of selection
i.                    single selection structure e.g if –else
ii.                  multiple  selection structure e.g switch case
3.3 REPETITION; - It indicates that some set of statements is to be executes till particular condition is been satisfied. In other words if a statement executed more than once, the technique of repetition is applied.
There are three iteration statements;-
While loop
do while loop
for loop

3.4 IF STATEMENT; - the if statement allows branching (decision making) depending upon the value of the variable.
Syntax :- if(condition)
                        {
Statement _1(s);
}
else
{
statement_2(s)
}
=>Here condition must be given in such a manner so that it returns Boolean value.
=>If  condition will be true then statement_1 will execute otherwise statement_2 will execute.
=>else is optional, we can have if without else.
Example 1
// program to find higher number out of two number.
class check1
{
public static void main(String args[])
{
int  x=10,y=30;
if(x>y)
{
            System.out.println(“ higher no is ”+x);
}
else
{
            System.out.println(“ higher no is ”+y);
}
}
}
// output is
higher no is 30

Example 2
// program to find absolute value of number
class check2
{
public static void main(String args[])
{
int x=-25;
if(x<0)
{
x=x * -1;
}
System.out.println( “absolute value of x is ”+x);
//Output is
Absolute value of x is 25

Ø  here is x is a positive number the condition will become false and x will remain positive so no operation  needed to take place that is why else block is not used.


Example 3
// program to find character ch is alphabet or not.
class check2
{
public static void main(String args[])
{
char ch=’B’
if((ch>=’a’ && ch<=’z’) && (ch>=’A’ && ch <=’Z’))
System.out.println( ch+” is an alphabet”):
else
System.out.println( ch+” is not an alphabet”):

}
}
//output
B is an alphabet
Ø  If single statement is to be followed by an if or else block then curly brackets can be omitted.

3.5 NESTED IF:- Nested if/else structures test for multiple causes by placing if/else selection inside if/else selection structure. The if/else selection structure uses the condition till three levels. The following illustrates if format

if(condition)
{
            if(conditions)
            {
                        Statement(s)
            }
            else
{         
                        Statement(s)
            }
}          //end of if
else
{
            // another if else block
}



Example 4
// program to find highest of three number using nested if
import java.util.*;
class check2
{
public static void main(String args[])
{
Scanner Sn=new Scanner(System.in));
int x,y,z,m;
Systemout.println(“enter three number”);
x=Sn.nextInt();
y= Sn.nextInt();
z= Sn.nextInt();
if(x>=y)
{         
            if(x>=z)
                        m=x;
            else
                        m=z;
}
else
{
            if(y>=z)
                        m=y;
            else
                        m=z;
}
System.out.println(“highest  number is ”+m);
}
}

// above program will input 3 number from user if x is greater than y  then x will be compared with z if this condition is also true then it will display x otherwise it will display z else if x is less then y then y will be compared with z and depending upon condition given in else block y or z will be displayed.

Example 6:-
// program to find calculate net salary of the employee depending upon basic salary.


Basic                                       DA      HRA
Less than 2000                        10%     5%
Greater than equal to 2000     25%     15%
But less than 4000
Greater than equal to 4000     30%     25%
But less than 8000
Greater than 8000                   40%     30%
import java.util.*;
class check2
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int basic;
double da,hra,net;
Systemout.println(“enter basic salary”);
basic=Sn.nextInt();
if(basic<2000)
{
da=0.10*basic;
hra=0.05*basic;
}
else if(basic<4000)
{
da=0.25*basic;
hra=0.15*basic;
}
else if(basic<8000)
{
da=0.30*basic;
hra=0.25*basic;
}
else
{
da=0.40*basic;
hra=0.30*basic;
}
net=basic+da+hra;
System.out.println(“Basic Salary “+basic);
System.out.println(“Dearness allowance “ + da);
System.out.println(“House rent “+hra);
System.out.println(“Net Salary “+net);
}
}

Example 7:-

A cloth showroom has announced the following discounts on the purchase of items, based on the total cost of the item purchased:-
Total Cost                                    Discount(in percentage)
Less than Rs 2000                       5%
Rs 2001 to Rs. 5000         25%
Rs. 5001 to Rs 10000       35%
Above Rs. 10000              50%
Write a program to input the total cost and to compute and display the amount to be paid by the customer after availing the discount.                                             [2006]
import java.util.*;
class prog2
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int cost;
double amt,dis;
Systemout.println(“Enter Cost to the item”);
cost=Sn.nextInt();
if(cost<=2000)
  dis=cost*0.05;
else if(cost<=5000)
  dis=cost*0.25;
else if(cost<=10000)
  dis=cost*0.35;
else
  dis=0.50;
amt=cost-dis;
System.out.println(“Amount to be paid “+amt);
}
}

3.6 SWITCH CASE:- the switch case is multiple branching statement used to compare one variable with many constants but only for equality.
Syntax:-
switch (expression)
{
  case <value1> : expression(s)
                                    break;
  case <value2> : expression(s)
                                    break;
:
            :
 default : expression(s)
}
Example 8:-

program to input two numbers and an operator perform arithmetic operation as per operator
import java.util.*;
class check7
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int a,b;
char op;
System.out.println(“enter 2 numbers and one operator”);
a= Sn.nextInt();
b= Sn.nextInt();
op=Sn.next().charAt(0);
switch(op)
{
case  ‘+’: System.out.println(a+b);
                break;
case  ‘-’: System.out.println(a-b);
                break;
case  ‘*’: System.out.println(a*b);
                break;
case  ‘/’: if(b==0)
                System.out.println(“divide by zero”);
               else
                        System.out.println(a/b);
                break;
default : System.out.println(“invalid operator”);
            break;
}
3.7 When is it better to use switch statement instead of if ? why?
OR
COMPARE switch WITH if
The switch statement is java’s multiple branch selection statement. It provides an easy to dispatch execution to different parts of the code bases on the value of a expression. It provides a better alternative for a large series of if-else-if statement. Some important features of switch statement are listed below:-
  1. The switch statement can only test for equality, the statement can evaluate any type of Boolean expression.
  2. The switch only look for a match between the value of the expression and one of its case constants values. The if-else statement uses a series of expression having unrelated variable
  3. No two case constants in a switch can have identical values.
  4. switch case can work only upon int and char data type where as if else can work with all data types.

3.8 What is the effect of absence of break statement in switch case statement?
Break is to terminate the sequence , without break each and every following case of the switch statement will be executed. This situation also known as Fall through.
Eg.
switch(ch)
{
case ‘a’ : System.out.println(“A says Apple”);
case ‘e’ : System.out.println(“E says Egg”);
case ‘i’ : System.out.println(“I says Ink”);
}
When user input a into ch the output will be as follows
A says Apple
E says Egg
I says Ink


3.9 Explain with the help of an example each of the following in a switch-case statement
i.                    break
ii.                  default                                    [2005]
i.                    break:- the keyword break is used with the switch statement to break the sequential control of execution and brings the control to the statement immediately following the switch block.
If break is missing then fall through takes place.
ii.                  Default is optional statement, it executed the statements when no choice is satisfied. .i.e. when data with the switch does not match  with any of the cases.
If default is missing then no action takes place if all case matches fail.
Example.
switch(var)
{
case 1: System.out.print(“one”);
            break;
case 2: System.out.print(“two”);
            break
default: System.out.print(“none”);
            break;
}
if the value of variable is 1 then it will display one and follow the statement given after switch.
If value of the variable is other than 1 or 2 then is will follow default and display none.
3.10 Differentiate between if and switch statements.                                             [2006] 
 If can use relational or logical operator where as switch can compare only for equality.
If can use any type of variable for comparison where as switch can use only int and char data types.

3.11 Turnary to if else
e.g. 1->  x=(x<0)? X*-1 : x;
Ans:-  if(x<0)
                x=x*-1;
            else
                x=x;
e.g.2 ->  c=(a!=b)? a :b;
Ans      if(a!=b)
            c=a;
            else
            c=b;

Do yourself
a)      System.out.println(x%2==)?”even”:”odd”);
b)      Tax=value<=10000?0:0.10*value
c) System.out.println(n%4==0?”leap year”:”not  leap year”);
d) grade=mark>=80?’A’:mark>=60?’B’:    mark>=40    ’C’:’D’;
3.12 if else to  using turnary
e.g. 1   if(x>10)
y=y+1;
else
y=y+5
Ans:-
 y+=x>10? 1 : 5 ;
Do your self
A) if(y%4)
flag=1;
    else
flag=0;
B) if(mark>=80)
grade=’A’;
     else if(mark>=60)
grade=’B’;
     else
grade=’C’;
C) if(per>=40)
System.out.println(“pass”);
    else
Systen,out.println(“fail”);
c)      if(sale<=5000)
   comm.=0.05*sale;
 else if (sale<=10000)
  comm.=0.10*sale;
else
 comm.=0.15*sale;

3.13 if else to switch case
if(grade==’A’)
            System.out.println(“Excellent”);
else if(grade==’B’)
            System.out.println(“Well Done”);
else if(grade==’C’)
            System.out.println(“Satisfactory”);
else if(grade==’D’ || grade==’E’)
            System.out.println(“Work Hard”);
else
            System.out.println(“Failed”);

Using switch case
switch(grade)
{
case ‘A’: System.out.println(“Excellent”);
               break;
case ‘B’:System.out.println(“Well Done”);
               break;
case ‘C’: System.out.println(“Satisfactory”);
               break;
case ‘D’:
case ‘E’: System.out.println(“Work Hard”);
               break;
default: System.out.println(“Failed”);
             break;
}

3.14 switch case to if else
EXAMPLE 1
switch(ch)
{
case ‘a’:
case ‘A’: System.out.println(“ AIRTEL”);
               break;
case ‘e’:
case ‘E’: System.out.println(“E-Comm”);
                break;
case ‘i’:
case ‘I’: System.out.println(“IDEA”);
             break;
case ‘o’:
case ‘O’: System.out.println(“ORANGE”);
              break;
case ‘u’:
case ‘U’: System.out.println(“U-tube”);
                        break;
default: System.out.println(“not vowel”);
              break;
}

using if else
if(ch==’a’ || ch==’A’)
 System.out.println(“ AIRTEL”);
else if(ch==’e’ || ch==’E’)
 System.out.println(“E-Comm”);
else if(ch==’i’ || ch==’I’)
             System.out.println(“IDEA”);
else if(ch==’o’ || ch==’O’)
 System.out.println(“ORANGE”);
else if(ch==’a’ || ch==’A’)
            System.out.println(“U-tube”);
else
            System.out.println(“Not vowel”);

EXAMPLE 2
switch(grade)
{
case ‘A’: switch(slab)
              {
             case 1: sal+=4000;
                        break;
            case 2: sal+=3000;
                        break;
             }
            break;
case ‘B’:switch(slab)
             {
            case 1: sal+=2000;
                        break;
            case 2: sal+=1000;
                        break;
}
                  break;
}
 using if else
if(grade==’A’)
{
     if(slab==1)
              sal+=4000;
     else if (slab==2)
 sal+=3000;
}
else if(grade==’B’)
{   
    if(slab==1)
            sal+=2000;
    else if(slab==2)
 sal+=1000;

}