Control Statements:Selection statement ,Iteration statement and Jump statement in Java


Control statements in java :
It is a statement that determines whether the other statements will be executed or not. It controls the flow of a program.
control statements help with the control flow of the program.
Control flow is the order in which the statements execute. 

Control Statements can be divided into three categories, namely
A] Selection statement
B] Iteration statement
C] Jump statement

Let us discuss above statements one by one as follow:

A ] Decision-Making /Conditional /Selection statements:
Statements that determine which statement to execute and when are known as decision-making statements. The flow of the execution of the program is controlled by the control flow statement.
Selection statements allow your program to choose different paths of execution based upon the outcome of an
expression or the state of a variable.

Java supports two selection statements:
I ] if statement:
II ] switch statement:


I] If statement:


It contains 4 types:
1.simple if statement
2.if else statement
3.nested if statement
4.else if ladder statement


1.Simple if statement :

The if statement determines whether a code should be executed based on the specified condition.

Syntax:
if (condition)
{
statements
}


Example 1:
if ( num > 0 )
{
System.out.println("number  is positive");
}


Example 2 :
if (age>=18)
{
System.out.println("candidate eligible for vote");
}


The if statement is a single-selection statement because it selects or ignores a single action (or, as we’ll soon see, a single group of actions).


2. If..else statement :

if the condition specified is true, the if block is executed. Otherwise, the else block is executed.

Syntax:
if (condition)
{
Statements
}
else
{
Statements
}

Example 1:
if ( x > y )
{
System.out.println( "x is big");
}
else
{
System.out.println( "y is big or equal ");
}


Example 2:
if (age>=18)
{
System.out.println("candidate eligible for vote");
}
else
{
System.out.println("candidate not eligible for vote");
}


Example 3:
Program to calculate total salary of employee.

import java.util.*;
public class emp
{
public static void main(String args[])
{
float salary ,bonus;
Scanner sc=new Scanner(System.in);
System.out.println("enter the salary:");
salary=sc.nextFloat();
if(salary>=15000)
{
bonus=(salary*10)/100;
}
else
{
bonus=(salary*5)/100;
}
salary+=bonus;
System.out.println("Total salary ="+salary);
}
}
Output:
enter the salary:
10000
Total salary =10500.0

Or
enter the salary:20000
Total salary =22000.0


Example 4:

if ( marks>= 40 )
System.out.println( "Passed" );
else
System.out.println( "Failed" );


Example 5:
Write a java program to print given number is odd or even.

program:
import java.util.*;
public class demo
{
public static void main(String args[])
{
int n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number:");
n=sc.nextInt();
if(n%2==0)
System.out.println(n+" is even");
else
System.out.println(n+" is odd");
}
}

The if…else statement is called a
double-selection statement because it selects between two different actions (or groups of
actions).


3.Nested if statement :
nested-if statement means an if statement inside another if statement.
An if present inside an if block is known as a nested if block. It is similar to an if..else statement, except they are defined inside another if..else statement.

Syntax:
if (condition1)
{
if ( condition2)
{
Statements
}
}
Or
if (condition)
{
   if ( condition)
   Statements
  else
   statements
}
else
{
  if(condition)
   statements
else
  statements
}


Example 1 :
import java.util.*;
public class demo
{
public static void main(String args[])
{
int a,b,c;
Scanner sc=new Scanner(System.in);
System.out.println("Enter any three integer numbers:");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
System.out.print("Largest value is:");
if(a>b)
{
   if(a>c)
    System.out.print(a);
  else
  System.out.print(c);
}
else
{
if(c>b)
System.out.print(c);
else
System.out.print(b);
}
}
}


Output :
Enter any three integer numbers:
8
0
12
Largest value is:12


Example 2:
Program to find given number is positive or negative.
import java.util.*;
public class demo
{
public static void main(String args[])
{
int n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number:");
n=sc.nextInt();
if (n== 0)
{
System.out.println("number is zero");
}
else
{
if (n > 0)
{
System.out.println("number is positive");
}
else
{
System.out.println("number is negative");
}
}
}
}


Output:
Enter the number:
5
number is positive
Or
Enter the number:
-5
number is negative
Or
Enter the number:
0
number is zero


4 .Else if ladder / If else if statement :
There is another way of putting ifs together when multipath decisions are involved.
A multipath decision is a chain of ifs in which the statement associated with each else is an if.

Syntax:
if (condition1)
{
Statements
}
else if (condition2)
{
Statements
}
else if (condition3)
{
Statements
}
.
.
.
else
{
statements
}


Example 1 :
Program to find grade of student based on the marks obtained by student.

import java.util.*;
public class student
{
public static void main(String args[])
{
int score;
char grade;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the marks:");
score=sc.nextInt();
if ( score >= 90)
grade = 'A';
else if (score >= 80)
grade = 'B';
else if (score >= 70)
grade = 'C';
else if (score >= 60)
grade = 'D';
else
grade = 'F';
System.out.println("Student grade is:"+grade);
}
}

Output :
Enter the marks:
95
Student grade is:A

Or
Enter the marks:
35
Student grade is:F


If variable score is greater than or equal to 90, the first four conditions in the nested if…else statement will be true, but only the statement in the if part of the first if…else statement will execute. After that statement executes, the else part of the“outermost” .


Example 2:
Program to find given number is positive or negative.
import java.util.*;
public class demo
{
public static void main(String args[])
{
int n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number:");
n=sc.nextInt();

if( n > 0 )
System.out.println( "number is positive");
else if ( n< 0)
System.out.println("number is negative ");
else
System.out.println( "number is zero");
}
}

Output:
Enter the number:
5
number is positive
Or
Enter the number:
-5
number is negative
Or
Enter the number:
0
number is zero


Example 3:
It determines if a given alphabet is vowel or consonant.

//Demonstrates if-else ladder
import java.util.*;
public class Demo
{
public static void main(String[] args)
{
char ch ;  
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Charecter:");
ch=sc.next().charAt(0);

if (ch == 'a' || ch == 'A') System.out.println(ch + " is vowel.");
else if (ch == 'e' || ch == 'E') System.out.println(ch + " is vowel.");
else if (ch == 'i' || ch == 'I') System.out.println(ch + " is vowel.");
else if (ch == 'o' || ch == 'O') System.out.println(ch + " is vowel.");
else if (ch == 'u' || ch == 'U') System.out.println(ch + " is vowel.");
else
System.out.println(ch + " is a consonant.");
}
}  

Output:
Enter the Charecter:
E
E is vowel.

Or
Enter the Charecter:
Y
Y is a consonant.


Example 4:
import java.util.*;
public class student
{
public static void main(String args[])
{
String gender;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the gender(m or f or t):");
gender=sc.next();
if ( gender.equalsIgnoreCase("m"))
System.out.println("Gender is Male");
else if ( gender.equalsIgnoreCase("f"))
System.out.println("Gender is  Female");
else if(gender.equalsIgnoreCase("t"))
System.out.println("Gender is Trans");
else
System.out.println("Gender is undefined");
}
}

Output:
Enter the gender(m or f or t):
M
Gender is Male
Or
Enter the gender(m or f or t):
T
Gender is Trans


II ] Switch statement :
A switch statement in java is used to execute a single statement from multiple conditions.
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. The switch statement is called a multiple-selection statement because it selects among many different actions (or groups of actions).

Syntax:
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN :
// statement sequence
break;
default:
// default statement sequence .optional
}

expression must be of type byte, short, int, char,String or an
enumeration .
The value of the expression is compared with each of the values in the case statements. If a match is found, the code sequence following that case
statement is executed. If none of the constants matches the value of the expression, then the default statement is executed. However, the default statement is optional.
If no case matches and no default is present, then no further action is taken.
Duplicate case values are not allowed.
The break statement is optional. If you omit the break, execution will continue on into the next case. It is sometimes desirable to have multiple cases without break statements between them.


Example 1:
program to check whether a given number is odd or even using switch statement

Program:
import java.util.*;
public class SwitchDemo
{
public static void main(String[] args) throws Exception
{
Scanner sc =new Scanner(System.in);
int num, rem,temp;
System.out.println("Enter positive integer: ");
num=sc.nextInt();
temp=num;
rem = temp%2;
switch(rem)
{
case 1: System.out.println(num+" is odd");
break;
default: System.out.println(num +" is even");
break;
}
}
}

Output:
Enter positive integer:
5
5 is odd
Or
Enter positive integer:
8
8 is even


Example 2 :
program to print weekday based on given number using switch

import java.util.*;
public class SwitchDemo
{
public static void main(String[] args) throws Exception
{
Scanner sc =new Scanner(System.in);
int day;
System.out.println("Enter day number(1-7): ");
day=sc.nextInt();
System.out.print("Today is ");
switch(day)
{
case 1:System.out.print("SUNDAY.");
break;
case 2: System.out.print("MONDAY.");
break;
case 3:System.out.print("TUESDAY.");
break;
case 4:System.out.print("WEDNESDAY.");
break;
case 5: System.out.print("THURSDAY.");
break;
case 6: System.out.print("FRIDAY.");
break;
case 7: System.out.print("SATURDAY.");
break;
default: System.out.println("INVALID DAY.");
break;
}
}
}

Output:
Enter day number(1-7):
9
Today is INVALID DAY.

Or
Enter day number(1-7):
1
Today is SUNDAY.

Example 3:
program to implement simple calculator using switch statement

import java.util.*;
public class SwitchDemo
{
public static void main(String[] args) throws Exception
{
int x, y;
Scanner sc =new Scanner(System.in); System.out.println("Enter two numbers for operation:");

x = sc.nextInt();
y = sc.nextInt();
String c=" ";
do
{
System.out.println(":****Arithmetic operations****:");
System.out.println("1. Add"); System.out.println("2. Subtract"); System.out.println("3. Multiply"); System.out.println("4. Divide"); System.out.println("enter your choice:"); int ch= sc.nextInt();
switch (ch)
{
case 1:  System.out.println("Addition=" + (x+y));
break;
case 2:System.out.println("substraction=" + (x-y));
break;
case 3: System.out.println("multiplication="+(x*y));
break;
case 4: System.out.println("division="+ (x/y));
break;
default: System.out.println("Invalid Entry!:");
}
System.out.println("do u want to continue type 'yes' ");
c=sc.next();
}while(c.equalsIgnoreCase("yes"));
System.out.println("exit");
}
}

Output:
Enter two numbers for operation:
2
1
:****Arithmetic operations****:
1. Add
2. Subtract
3. Multiply
4. Divide
enter your choice:
3
multiplication=2
do u want to continue type 'yes'
No
exit

Or
Enter two numbers for operation:
4
2
:****Arithmetic operations****:
1. Add
2. Subtract
3. Multiply
4. Divide
enter your choice:
3
multiplication=8
do u want to continue type 'yes'
Yes
:****Arithmetic operations****:
1. Add
2. Subtract
3. Multiply
4. Divide
enter your choice:
1
Addition=6
do u want to continue type 'yes'
No
exit


Example 4:
Java program to derive month name from given month number.

Program:
import java.util.*;
public class SwitchDemo
{
public static void main(String[] args) throws Exception
{
Scanner sc =new Scanner(System.in);
int month;
System.out.println("Enter month number(1-12): ");
month=sc.nextInt();
System.out.print("Month  is ");
switch(month)
{
case 1:System.out.print(" January");
break;
case 2:System.out.print(" February");
break;
case 3:System.out.print(" March");
break;
case 4:System.out.print("April");
break;
case 5:System.out.print("May ");
break;
case 6:System.out.print("June");
break;
case 7:System.out.print(" July");
break;
case 8:System.out.print(" August");
break;
case 9:System.out.print("Septembet");
break;
case 10:System.out.print("October");
break;
case 11:System.out.print("November");
break;
case 12:System.out.print("December");
break;
default:System.out.print(" not a month ");
break;
}
}
}
Output :
Enter month number(1-12): 5
Month  is May
Or
Enter month number(1-12):
14
Month  is  not a month .



B] Looping Statements / Repetitive/
Iteration statements:

Statements that execute a block of code repeatedly until a specified condition is met are known as looping statements.
Or
Iteration statements enable program execution to repeat one or more statements.
Java provides the user with three types of  iteration statements :
1.while loop
2. do-while loop
3. for loop

A looping process ,in general would include the following 4 steps:

1)setting &initializing of a counter
2)Execution of statements in the loop
3)Test for a specified condition for execution of the loop
4)incrementing /decrementing the counter.


Entry controlled loop: When a condition is evaluated at the beginning of the loop.

--->If the test condition is true, the loop body would be executed otherwise, the loop would be terminated.

--->It is used when checking of test condition is mandatory before executing loop body.

Example :for ,while loop


Exit controlled loop: When a condition is evaluated at the end of the loop.

--->The loop body would be executed at least once, no matter if the test condition is true or false.

--->it is used when checking of test condition is mandatory after executing.

Example : do while loop


1) while loop :
it is entry controlled loop.
Syntax:
initialization;
while(condition)
{
body of the loop
Increment/decrement
}

The condition can be any Boolean expression. The body of the
loop is executed as long as the condition is true. When the condition becomes
false, the control passes to the next line which immediately follows the loop.


Example 1 :

int i=1;   
while(i<=5)
{      System.out.println(i); 
  i++;      
}


Output :
1
2
3
4
5

Example 2:
Write a java program to Reverse a number using a while loop.

import java.util.*;
public class Rev
{
public static void main(String[] args)
{
int num , reversed = 0;
Scanner sc =new Scanner(System.in);
System.out.println("Enter the number: ");
num=sc.nextInt();

while(num != 0)

int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println("Reversed Number: " + reversed);
}
}


Output:

Enter the number:
1234
Reversed Number: 4321


Infinitive while :
If you pass true in the while loop, it will be infinitive while loop.
If the expression passed in while loop results in any non-zero value then the loop will run the infinite number of times.


2) do-while loop :
It is exit controlled loop.
Syntax:
initialization;
do
{
body of the loop
increment/decrement
}
while(condition);

Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression. If the expression evaluates to true, then the
loop repeats otherwise it terminates. The condition must be a Boolean expression.
Note that the do-while loop always executes its body at least once.


Example :
int i = 1;
    do
{
      System.out.println(i);
      i++;
    }
    while (i <=5);


Output:
1
2
3
4
5

Infinitive do-while Loop :
If you pass true in the do-while loop, it will be infinitive do-while loop.

3) For loop :
It is entry controlled loop.
It is used to iterate a part of the program several times. If the number of iteration is fixed.

Syntax:
for(initialization;condition;increment/decrement)
{
Body of the loop
}


Example 1:
for(int i=1;i<=5;i++)
System.out.println(i);


Output:
1
2
3
4
5


Example 2:
Write a java program to Reverse a number using a for loop.

import java.util.*;
public class Rev
{
public static void main(String[] args)
{
int num , reversed = 0;
Scanner sc =new Scanner(System.in);
System.out.println("Enter the number: ");
num=sc.nextInt();
for(;num != 0; num /= 10)
{
int digit = num % 10;
reversed = reversed * 10 + digit;
}

System.out.println("Reversed Number: " + reversed);
}
}
Output:
Enter the number:
1234
Reversed Number: 4321


for infinitive loop :
If you pass two semicolons ;; inside for loop it is called infinitive loop.
Syntax:
for(;;)

//code to be executed 
}


For-Each loop /Enhanced for loop :
The traversal of elements in an array can be done by the for-each loop. The elements present in the array are returned one by one. It must be noted that the user does not have to increment the value in the for-each loop.

Syntax:

for(Type identifier: collection /array)

{

}

Example:
Write a java program to find sum of elements in an array using for-each loop.

Program:
public class demo
{
int sum=0;
public static void main(String args[])
{
int a[] = {10,20,30,40,50};
System.out.println("Elements of an array:");
for (int i : a) //for-each
{
System.out.println(i);
sum+=i;
}
System.out.println("Sum="+sum);
}
}
Output :
Elements of an array:
10
20
30
40
50
Sum=150



C] Branching/Jumping Statements :
Branching statements  are used to jump from a statement to another statement, there by the transferring the flow of execution.
Or
Jump statements are statements through which we can transfer control anywhere in the program.
Or
These statements transfer control to another part of your program.

Java provides 3 jumping statements
1.break statement
2.continue statement
3.return statement


Jump statements allow your program to execute in a nonlinear fashion.

1.Break statement :
The break statement in java is used to terminate a loop and break the current flow of the program.

The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.

Break statement has three uses.
1. It terminates a statement sequence in a switch statement.
2. It can be used to exit a loop.
3. It can be used as a “civilized” form of goto.


Example:
public class TestBreak
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
break;
}
System.out.println( "value of x-"+x );
}
}
}


Example 2:

It can be used as a “civilized” form of goto.
   
public class MyClass
{
  public static void main(String args[]) {
    boolean t = true;
     block1:
     {
 
   block2:{
          System.out.println("Before the break.");
          if(t) break block2;
          }
         // break out of block2
}
      System.out.println("This is after block.");
   }
}


Output:
Before the break.
This is after  block.


2.continue statement :
The continue statement skips the current iteration of a for, while , or do-while loop.
The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.
Or
Continue statement bypasses intermediate control and transfers control to the beginning of the loop.

A labeled continue statement skips the current iteration of an outer loop marked with the given label.


Example:
public class TestContinue
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}


Example 2:
public class Main
{
public static void main(String args[])
{
for (int n = 5; n < 15; n++)
{
// Odd numbers are skipped
if (n%2 != 0)
continue;
// Even numbers are printed System.out.println(n);
}
}
}

Output:
6
8
10
12
14


3.Return statement :
return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed.

Example 1:

Demonstrate return.
class Return
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if(t)
return; // return to caller
System.out.println("This won't execute.");
}
}


Output:
Before the return.

As you can see, the final println( ) statement is not executed. As soon as return is executed, control passes back to the caller.

"return” is also used to return values to the point where it is called. But it is possible to return only one value at a time.


Example 2:

int sum(int x, int y)
{

return x+y;
}

int k= sum(30,40);

Here “sum” function returns 70 into the variable k with the above call.

Questions :
1.Name any two jump statements used in Java programming.
     Ans: break ,return and continue
2.Describe break and continue statement with example.
3.explain various looping statements used in java.
4.explain various branching/jumping statements used in java.
5.explain various decision making or selection statements used in java.
6.Describe switch statement with suitable example.
7.List out the differences between entry controlled loop and exit controlled loop.
8.explain each control statements used in java with  suitable example.

Comments

Post a Comment

Popular posts from this blog

Applets - Inheritance hierarchy for applets, differences between applets and applications, life cycle of an applet, passing parameters to applets, applet security issues.

Java Database Connectivity (JDBC) ,Steps to connect to the database in Java