0% found this document useful (0 votes)
23 views51 pages

Contol Structures

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views51 pages

Contol Structures

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Control structures in

java
 Selection statements
 Iterative statements
 Jump statements
Java’s Selection Statements

 Java supports two selection statements: if and switch.


 These statements allow you to control the flow of your program’s
execution based upon conditions known only during run time.
If
 The if statement is Java’s conditional branch statement. It can be used to
route program execution through two different paths.

 Here is the general form of the if statement:

if (condition)
statement1;
else
statement2;

 Here, each statement may be a single statement or a compound statement


enclosed in curly braces (that is, a block).
 The condition is any expression that returns a boolean value.
 The else clause is optional.
 The if works like this: If the condition is true, then statement1 is executed.
Otherwise,statement2 (if it exists) is executed.
 In no case will both statements be executed.
Example:

int a, b;
// ...
if(a < b)
a = 0;
else
b = 0;
Nested ifs

 A nested if is an if statement that is the target of another if or else.


 Nested ifs are very common in programming.
 When you nest ifs, the main thing to remember is that an else statement always
refers to the nearest if statement that is within the same block as the else and
that is not already associated with an else.

Example:
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;
The if-else-if Ladder
A common programming construct that is based upon a sequence of
nested ifs is the if-else-if ladder.

 It looks like this:


if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
 The if statements are executed from the top down.
 As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of
the ladder is bypassed.
 If none of the conditions is true, then the final else statement
will be executed.
 The final else acts as a default condition; that is, if all other
conditional tests fail, then the last else statement is
performed.
 If there is no final else and all other conditions are false, then
no action will take place.
Example:
Here is the output
produced by the program:
// Demonstrate if-else-if statements.
class IfElse April is in the Spring.
{
public static void main(String args[])
{
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Switch

 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.
 it provides a better alternative than a large series of if-else-if
statements.
Switch
Here is the general form of a switch statement:
switch (expression) {  The expression must be of type byte,
case value1:
short, int, or char;
// statement sequence  Each of the values specified in the
break; case statements must be of a type
compatible with the expression.
case value2:
 Each case value must be a unique
// statement sequence
literal (that is, it must be a constant,
break;
not a variable).
...
 Duplicate case values are not
case valueN:
allowed.
// statement sequence
break;
default:
// default statement
sequence
}
The switch statement works like this:
 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.
 However, 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. This has
the effect of “jumping out” of the switch.
// A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
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;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
The output produced by this program is shown here:

i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
switch

 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.
 Omitting the break statement has many practical applications in real
programs.
class Switch case 6:
{ case 7:
public static void main(String args[]) case 8:
{ season =
"Summer";
int month = 4;
break;
String season;
case 9:
switch (month)
case 10:
{
case 11:
case 12:
season =
case 1:
"Autumn";
case 2: break;
season = "Winter"; default:
break; season =
case 3: "Bogus Month";
case 4: }
case 5: System.out.println("April is in the " +
season + ".");
season = "Spring";
}
break;
}
Nested switch Statements

 Using a switch as part of the statement sequence of an outer


switch. This is called a nested switch.
 Since a switch statement defines its own block, no conflicts arise
between the case constants in the inner switch and those in the
outer switch.
Example:

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: // ...
There are three important features
of the switch statement to note:

■ The switch differs from the if in that 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.
■ No two case constants in the same switch can have identical values.
Of course, a switch statement enclosed by an outer switch can have
case constants in common.
■ A switch statement is usually more efficient than a set of nested ifs.
Iteration Statements

 Java’s iteration statements are for, while, and do-while.


 These statements create what we commonly call loops.
 A loop repeatedly executes the same set of instructions until a
termination condition is met.
while
 The while loop is Java’s most fundamental looping statement.
 It repeats a statement or block while its controlling expression is true.

Here is its general form:


while(condition) {
// body of loop
}

 The condition can be any Boolean expression.


 The body of the loop will be executed as long as the conditional expression is true.
 When condition becomes false, control passes to the next line of code immediately
following the loop.
 The curly braces are unnecessary if only a single statement is being
repeated.
// Demonstrate the while loop.
When you run this program, it will “tick” ten
class While times:
{ tick 10
public static void main(String args[]) tick 9
{ tick 8
int n = 10; tick 7
while(n > 0) { tick 6
tick 5
System.out.println("tick " + n);
tick 4
n--;
tick 3
}
tick 2
}
tick 1
}
 Note:
 The while loop evaluates its conditional
expression at the top of the loop, the body of
the loop will not execute even once if the
condition is false to begin with.
 Thebody of the while (or any other of Java’s
loops) can be empty.
Example, in the following fragment, the call to
println( ) is never executed:

int a = 10, b = 20;


while(a > b)
System.out.println("This will not be
displayed");
// The target of a loop can be empty.
class NoBody {
public static void main(String args[]) {
int i, j;
i = 100;
j = 200;

// find midpoint between i and j


while(++i < --j) ; // no body in this loop
System.out.println("Midpoint is " + i);
}
}

This program finds the midpoint between i and j. It generates the


following output:
Midpoint is 150
do-while
 The do-while loop always executes its body at least once, because
its conditional expression is at the bottom of the loop.

 Its general form is


do {
// body of loop
} while (condition);

 Each iteration of the do-while loop first executes the body of the
loop and then evaluates the conditional expression.
 If this expression is true, the loop will repeat.
 Otherwise, the loop terminates. As with all of Java’s loops, condition
must be a Boolean expression.
// Demonstrate the do-while loop.

class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
} while(--n > 0);
}
}

 The do-while loop is especially useful when you process a


menu selection, because you will usually want the body of a
menu loop to execute at least once.
For

The general form of the for statement:

for(initialization; condition; iteration) {


// body
}

If only one statement is being repeated, there is no need for the curly
braces.
 The for loop operates as follows.

 When the loop first starts, the initialization portion of the loop
is executed.
 Generally, this is an expression that sets the value of the loop
control variable, which acts as a counter that controls the loop.
It is important to understand that the initialization expression
is only executed once.
 Next, condition is evaluated. This must be a Boolean
expression. It usually tests the loop control variable against a
target value. If this expression is true, then the body of the
loop is executed. If it is false, the loop terminates.
 Next, the iteration portion of the loop is executed. This is
usually an expression that increments or decrements the loop
control variable. The loop then iterates, first evaluating the
conditional expression, then executing the body of the loop,
and then executing the iteration expression with each pass.
 This process repeats until the controlling expression is false.
Example:

class ForTick {
public static void main(String args[]) {
int n;
for( n=10; n>0; n--)
System.out.println("tick " + n);
}
}
Declaring Loop Control Variables Inside the for Loop

 Often the variable that controls a for loop is only needed for the purposes
of the loop and is not used elsewhere. When this is the case, it is possible to
declare the variable inside the initialization portion of the for.

// Declare a loop control variable inside the for.


class ForTick {
public static void main(String args[]) {
// here, n is declared inside of the for loop
for(int n=10; n>0; n--)
System.out.println("tick " + n);
}
}

 When you declare a variable inside a for loop, the scope of that variable
ends when the for statement does.
 Outside the for loop, the variable will cease to exist.
Using the Comma
 There will be times when you will want to include more than one statement in
the initialization and iteration portions of the for loop.
 Java permits you to include multiple statements in both the initialization and
iteration portions of the for. Each statement is separated from the next by a
comma.

// Using the comma.


class Comma {
output:
public static void main(String args[]) { a=1
int a, b; b=4
a=2
for(a=1, b=4; a<b; a++, b--) {
b=3
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}
Some for Loop Variations
 One of the most common variations involves the conditional
expression.
 Specifically, this expression does not need to test the loop control
variable against some target value.
 In fact, the condition controlling the for can be any Boolean
expression.

For example,consider the following fragment:


boolean done = false;
for(int i=1; !done; i++) {
// ...
if(interrupted()) done = true;
}
Some for Loop Variations
Either the initialization or the iteration expression or both may be absent, as in
this next program:

// Parts of the for loop can be empty.


class ForVar {
public static void main(String args[]) {
int i;
boolean done = false;
i = 0;
for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10)
done = true;
i++;
}
}
}
Some for Loop Variations
You can intentionally create an infinite loop (a loop that never
terminates) if you leave all three parts of the for empty.

For example:
for( ; ; ) {
// ...
}

This loop will run forever, because there is no condition under which it
will terminate.
Nested Loops
Like all other programming languages, Java allows loops to be nested. That
is, one loop may be inside another.

For example, here is a program that nests for loops:


// Loops may be nested.
class Nested {
public static void main(String args[]) { The output :
int i, j; .....
for(i=0; i<5; i++) { ....
for(j=i; j<5; j++) ...
System.out.print(".");
..
System.out.println();
.
}
}
}
Jump Statements

 Java supports three jump statements: break, continue, and return.


 These statements transfer control to another part of your program.
Using break
 In Java, the break statement has three uses.

 First,it terminates a statement sequence in a switch statement.


 Second, it can be used to exit a loop.
 Third, it can be used as a “civilized” form of goto.

Using break to Exit a Loop

 By using break, you can force immediate termination of a loop,


bypassing the conditional expression and any remaining code in the
body of the loop.
 When a break statement is encountered inside a loop, the loop is
terminated and program control resumes at the next statement
following the loop.
Here is a simple example:
output:
// Using break to exit a loop. i: 0
class BreakLoop { i: 1
i: 2
public static void main(String args[]) { i: 3
for(int i=0; i<100; i++) { i: 4
i: 5
if(i == 10) i: 6
break; // terminate loop if i isi: 10
7
i: 8
System.out.println("i: " + i); i: 9
} Loop complete.
System.out.println("Loop complete.");
}
}
 The break statement can be used with any of Java’s loops, including
intentionally infinite loops.

 When used inside a set of nested loops, the break statement will
only break out of the innermost loop.
// Using break with nested loops.
output:
class BreakLoop3 {
Pass 0: 0 1 2 3 4 5 6 7 8
public static void main(String args[]) { 9
for(int i=0; i<3; i++) { Pass 1: 0 1 2 3 4 5 6 7 8
9
System.out.print("Pass " + i + ": ");
Pass 2: 0 1 2 3 4 5 6 7 8
for(int j=0; j<100; j++) { 9
if(j == 10) Loops complete.
break; // terminate
loop if j is 10
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Loops complete.");
}
}
Using break as a Form of Goto –
Labelled break
 Java does not have a goto statement, because it provides a way to
branch in an arbitrary and unstructured manner.
 Use of goto: the goto can be useful when you are exiting from a
deeply nested set of loops.
 Java defines an expanded form of the break statement.
 By using this form of break, you 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, you can specify precisely where execution will resume,
because this form of break works with a label.
Using break as a Form of Goto
 The general form of the labeled break statement is shown here:
break label;

 Here, label is the name of a label that identifies a block of code. When
this form of break executes, control is transferred out of the named
block of code.
 The labeled block of code must enclose the break statement, but it does
not need to be the immediately enclosing block. This means that you can
use a labeled break statement to exit from a set of nested blocks.
 A label is any valid Java identifier followed by a colon. Once you have
labeled a block, you can then use this label as the target of a break
statement.
 You cannot break to any label which is not defined for an enclosing block.
// Using break to exit from nested loops
class BreakLoop4 {
public static void main(String args[]) {
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.");
}
}
This program generates the following output:
Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.
Using continue
 Continue statement continue running the loop, but stop processing
the remainder of the code in its body for this particular iteration.

 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.
class Continue {
Here is the output from
public static void main(String args[]) {
this program:
for(int i=0; i<10; i++) { 01
23
System.out.print(i + " ");
45
if (i%2 == 0) 67
continue; 89

System.out.println("");
}
}
}
This code uses the % operator to check if i is even. If it is, the loop
continues without printing a newline.
Labelled continue
 continue may specify a label to describe which enclosing loop to continue.

// Using continue with a label. The output of this program:


0
class ContinueLabel {
01
public static void main(String args[]) { 024
outer: for (int i=0; i<10; i++) { 0369
for(int j=0; j<10; j++) {
0 4 8 12 16
0 5 10 15 20 25
if(j > i) { 0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
System.out.println();
0 8 16 24 32 40 48 56 64
continue outer;
0 9 18 27 36 45 54 63 72 81
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
Difference between break and continue staments.

 The break statement results in the termination of the loop, it will come out of
the loop and stops further iterations.

class Break
{
public static void main(String args[])
{ Output:
// Illustrating break Break
System.out.println("Break\n----------------"); ---------
1
for(int i=1;i<=5;i++)
{
2
if(i==4) 3
I AM HERE
break;
System.out.println(i);
}
System.out.println(“I AM HERE");
}
}
Difference between break and continue staments.

 The continue statement stops the current execution of the iteration


and proceeds to the next iteration.
class Continue
{
public static void main(String args[])
{ Output:
// Illustrating continue Continue
-------------
System.out.println("Continue\n-------------"); 1
for(int i=1;i<=5;i++) 2
{ 3
if(i==4) 5
continue;
System.out.println(i);
}

}
}
Return
 The return statement is used to explicitly return from a method.
 That is, it causes program control to transfer back to the caller of the method.
 At any time in a method the return statement can be used to cause execution
to branch back to the caller of the method. The return statement immediately
terminates the method in which it is executed.

Example:
// Demonstrate return.
The output :
class Return {
Before the 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.");
}
}
 The final println( ) statement is not executed. As soon as return is executed,
Difference between while and do-while
loop.

While Do- while


·It is an entry controlled loop. ·It is an exit controlled loop
·While loop checks for the condition first. ·do while loop, execute the statements in the
so it may not even enter into the loop, if loop first before checks for the condition.
the condition is false. ·At least one iteration takes places, even if the
·No iteration takes places, if the condition condition is false the very first time.
is false the very first time.
int MAX=5;
int MAX=5; int k = 0;
int j = 0; do{
while (j < MAX){ System.out.format("Do While Loop : %d\n",
System.out.format(" While Loop : %d\n", k);
j); k++;
j++; } while (k < MAX);
}

You might also like