Modern Programming Tools and Techniques-I: Lecture 4: Control Structures
Modern Programming Tools and Techniques-I: Lecture 4: Control Structures
Modern Programming Tools and Techniques-I: Lecture 4: Control Structures
Techniques-I
Lecture 4: Control Structures
Selection Statements
Java supports two selection statements: if and switch.
if statement
if (condition) statement1;
else statement2;
if (i == 10) {
if (j < 20) a = b;
if (k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
//PROGRAM TO CHECK WHETHER A NUMBER IS EVEN using IF
statement
public class Even
{
public static void main(String[] args)
{
int num=102;
if(num%2==0)
{
System.out.println(num +"is even");
}
System.out.println("\"End of program\"");//escape sequence
}
}
The if-else-if Ladder
A sequence of nested ifs is the if-else-if ladder.
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
The if statements are executed from the top to down.
//PROGRAM TO CHECK WHETHER A NUMBER IS EVEN OR ODD USING IF ELSE
import java.util.Scanner;//program uses scanner class for input
public class EvenOdd
{
public static void main(String [] args)
{int num; //create scanner object to obtain input from keyboard
Scanner input =new Scanner(System.in);//input is the object
System.out.print("Enter the number----->");//prompt for input
num=input.nextInt(); //Read Integer
if(num%2==0)
{System.out.println(num+" is even");}
else
{
System.out.println(num+" is odd");
}}}
QUICK PRACTICE
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The expression must be of type byte, short, int, or char.
Each of the values specified in the case statements must be of
a type compatible with the expression.
Each case value must be a unique literal (i.e. constant not
variable).
Duplicate case values are not allowed.
The value of the expression is compared with each of the
literal 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.
The default statement is optional.
If no case matches and no default is present, then no further
action is taken.
The break statement is used inside the switch to terminate a
statement sequence.
When a break statement is encountered, execution branches
to the first line of code that follows the entire switch
statement.
//PROGRAM TO SHOW WORKING OF SWITCH CASE
import java.util.Scanner;
class SampleSwitch
{int choice;
choice=input.nextInt();
switch(choice) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
} }}
Nested switch Statements
When a switch is used as a part of the statement sequence
of an outer switch. This is called a nested switch.
Example:NestedSwitch.java
switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...
Difference between ifs and switch
switch can only test for equality, whereas if can evaluate any
type of Boolean expression. That is, the switch looks only for a
match between the value of the expression and one of its case
constants.
do {
// body of loop
} while (condition);
Example 1:
class var2 {
public static void main(String arr[]) {
int a, b;
b = 5;
for(a=0; a<b; a++) {
System.out.println("a = " + a);
System.out.println("b = " + b);
b--;
}
}
}
Comma (separator) is used while initializing multiple
loop control variables.
Example 2:
class var21
{
public static void main(String arr[]) {
int x, y;
for(x=0, y=5; x<=y; x++, y--) {
System.out.println("x= " + x);
System.out.println(y = " + y);
}
}
}
Initialization and iteration can be moved out from for loop.
Example 3:
class Loopchk
{
public static void main(String arr[])
{
for(int i=1, j=5; i>0 && j>2; i++, j--)
System.out.println("i is: "+ i + "and j is: "+j);
}
}
Nested Loops
class NestedLoop
{
public static void main(String arr[])
{
int i, j;
for(i=0; i<10; i++)
{
for(j=i; j<10; j++)
{
System.out.print(* );
System.out.println( );
}}
}
}
Enhanced for loop
As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse
collection of elements including arrays.
Syntax
Following is the syntax of enhanced for loop
for(declaration : expression) { // Statements }
Declaration The newly declared block variable, is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for
block and its value would be the same as the current array element.
Expression This evaluates to the array you need to loop through. The expression
can be an array variable or method call that returns an array.
Example:ForEach.java
public class Test {
for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};
class BreakLoop
{
public static void main(String arr[])
{
for(int i=0; i<100; i++)
{
if(i == 10) break;
// terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Java defines an expanded form of the break statement.
By using this form of break, we can break out of one or
more blocks of code.
These blocks need not be part of a loop or a switch. They
can be any block.
Further, we can specify precisely where execution will
resume, because this form of break works with a label.
break label;
When this form of break executes, control is transferred out of the
named block. The labeled block must enclose the break
statement.
class BreakLoop
{
public static void main(String arr[])
{
outer: for(int i=0; i<3; i++)
{
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++)
{
if(j == 10) break outer; // exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}
//PROGRAM TO SHOW USE OF BREAK LABEL
public class BreakLabel
{
public static void main(String[] args)
{ int n,i,j;
outer:
for(i=1;i<=5;i++)
{
for(j=5;j<=10;j++)
{if(i*j>12)
break outer;
System.out.println(i +" * " +j +" = " +i*j);
}}}}
Continue
In while and do-while loops, a continue statement causes control to be
transferred directly to the conditional expression that controls the loop.
In a for loop, control goes first to the iteration portion of the for statement
and then to the conditional expression.
For all three loops, any intermediate code is bypassed.
Example:
class Continue
{
public static void main(String args[])
{
for(int i=0; i<5; i++)
{
System.out.println(i + " ");
if (i%2 == 0) continue;
System.out.println("No Continue");
}
}
}
Similar to break statement, Continue may specify a label to describe
which enclosing loop to continue.
Example:
class ContinueLabel
{
public static void main(String args[])
{
outer: for (int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
if(j > i)
{
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
return
The return statement is used to explicitly return from a
method.
It causes program control to transfer back to the caller of
the method. if(t) statement is necessary. Without it, the Java compiler
Example: would flag an unreachable code error because the
compiler would know that the last println( ) statement
class Return { would never be executed.
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.");
}
}
PRACTICE
WAP TO CALCULATE THE DIVISION OF A
STUDENT ACCORDING TO MARKS OBTAINED
IN THREE SUBJECTS USING NESTED IF-ELSE
WAP TO ADD ,SUBTRACT,MULTIPLY AND
DIVIDE TWO NUMBERS USING SWITCH
WAP TO FIND SUM OF DIGITS OF A NUMBER
USING WHILE
WAP TO FIND AVERAGE OF N NUMBERS
USING FOR LOOP.
WAP TO PRINT FIRST N PRIME NUMBERS
WAP to find factorial of a number using
while and for loop
WAP to print fib series using while and for
loop
Wap to find reverse of a number and
whether it is palindrome or not
WAP to find a number is amstrong
number(153=)