0% found this document useful (0 votes)
19 views34 pages

4 - Control Statements

The document provides an overview of Java's control statements, categorizing them into selection, iteration, and jump statements. It details selection statements like 'if' and 'switch', iteration statements such as 'for', 'while', and 'do-while', and jump statements including 'break', 'continue', and 'return'. Each section includes syntax examples and explanations to illustrate their usage in controlling program flow.

Uploaded by

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

4 - Control Statements

The document provides an overview of Java's control statements, categorizing them into selection, iteration, and jump statements. It details selection statements like 'if' and 'switch', iteration statements such as 'for', 'while', and 'do-while', and jump statements including 'break', 'continue', and 'return'. Each section includes syntax examples and explanations to illustrate their usage in controlling program flow.

Uploaded by

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

CONTROL

STATEMENTS
 Java’s program control statements can be categorized as 2
 selection,

 iteration,

 jump.

 Selection statements allow program to choose different paths of execution


based upon the outcome of an expression or the state of a variable.

 Iteration statements enable program execution to repeat one or more


statements (that is, iteration statements form loops).

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


Java’s Selection Statements
3
• Java supports two selection statements : if & switch.
• These statements allow you to control the flow of the
program’s execution based upon conditions known only
during run time.

if
• The if statement is Java’s conditional branch statement.

if ( condition ) Ex: int a,b;


statement1; if(a<b) a=0;
else
statement2;
else b=0;
4
…..
• It is possible to control the if using a single boolean 5

variable.
boolean dataAvailable;
if (dataAvailable)
processdata();
else

waitformoredata();
int bytesAvailable;
if (bytesAvailable > 0){
processdata();
bytesAvailable -=n;
}else
waitformoredata();
Nested ifs… 6

• A nested if is an 'if' statement that is the target of another


if or else.
if(i == 10)
{
if (j < 20) a = b;
if(k > 100) // this if is
c = d;
else // associated with this else
a = c;
}
else a = d; // this else refers to if (i = =10)
The if-else-if Ladder….. 7

• A common programming construct that is based upon a


sequence of nested ifs is the if-else-if ladder.

if(condition)
statement;
else if (condition )
statement;
else if(condition)
statement;
.
.
.
else
statement;
// Demonstrate if-else-if statements.
class IfElse { 8
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…. 9

• The second of Java’s selection statements is the switch.


• The switch provides for a multiway branch. Thus, it
enables a program to select among several alternatives.
• Although a series of nested if statements can perform
multiway tests, for many situations the switch is a more
efficient approach.
• It works like this: the value of an expression is
successively tested against a list of constants.
• When a match is found, the statement sequence
associated with that match is executed.
The general syntax of switch… 10

switch(expression) {
case constant1:
statement sequence
break;
case constant2:
statement sequence
break;
...
default:
statement sequence
}
1
1
// Demonstrate the switch.
class SwitchDemo {
public static void main(String args[]) { 12

int i;
for(i=0; i<10; 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;
case 4: System.out.println("i is four");
break;
default: System.out.println("i is five or more");
}
}
}
class Switch { case 6:
public static void case 7: 1
main(String args[]) { case 8: 3
int month = 4; season = "Summer";
break;
String season;
case 9:
switch (month) { case 10:
case 12: case 11:
case 1: season = "Autumn";
case 2: break;
season = "Winter"; default:
break; season = “Invalid
case 3: Month";
case 4: }
case 5: System.out.println("April
is in the " + season +
season = "Spring";
".");
break; }}
Nested switch Statements…..
14
• It is possible to have a switch as part of the statement
sequence of an outer switch.
• This is called a nested switch. Even if the case constants
of the inner and outer switch contain common values, no
conflicts will arise.
switch(ch1) {
case 'A': System.out.println("This A is part of outer switch.");
switch(ch2) {
case 'A': System.out.println("This A is part of inner switch");
break;
case 'B': // ...
} // end of inner switch
break;
case 'B': // ...
Iteration Statements….
15
• Java’s iteration statement are for, while & do-while.
• These statements create loops, a loop repeatedly executes
the same set of instructions until a termination condition
is met.
While 16

• While loop repeats a statement or block while its


controlling expression is true.

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.
do-while..
17

• Sometimes it is desirable to execute the body of a loop at


least once, even if the conditional expression is false to
begin with.
• The do-while loop always executes its body atleast once,
because its conditional expression is at the bottom of
the loop.
do
{
…// body of loop
}while(condition);
for
for(initialization;condition;iteration)
18
{
//body
}
• 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 updation portion of the loop is executed. This is usually
an expression that increments or decrements the loop control
for…
•The loop then iterates, first evaluating the conditional expression,
19

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.
Declaring loop control variables inside the for loop..
for(int i=10, i>0; i++)
Using the comma….
Include more than one statement in the initialization
and iteration portions of the loop.
for(a=1, b=4; a<b; a++, b--)
For infinite loop
for(; ;) 20

{
…//body
}
•Can create infinite loop if you leave all parts empty.
•This loop will run forever there is no condition under
which it will terminate
The For-Each version of the for loop….
21
• The for-each version of the for is also refereed to as the
enhanced for loop.
• Syntax:
• for(type itr-var : collection) statement-block
• type specifies the data type.
• itr-var specifies the name of an iteration variable will
receive the elements from a collection. one at a time, from
beginning to end.
• The collection being cycled through is specified by
collection.
• There are various types of collections that can be used
with the for, ex. is array. 22

• With each iteration of the loop, the next element in the


collection is retrieved and stored in itr-var.
• The loop repeats until all elements in the collection have
been obtained.

int nums[]={1,2,3,4,5,6,7,8,9,10};
int sum=0;
for(int x: nums) sum=sum+x;
• As the iteration variable receives values from the
collection, type must be the same as the elements stored in
the collection.
Consider an example
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 2
int sum = 0; 3
for(int i=0; i < 10; i++)
sum += nums[i];
The above set of statements can be optimized as follows
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums)
•With each pass through the loop, x is automatically given a value
equal to the next element in nums.
•Thus, on the first iteration, x contains 1; on the second iteration, x
contains 2; and so on.
•Not only is the syntax streamlined, but it also prevents boundary
class ForEach
{ 24

public static void main(String args[])


{
int nums[]={1,2,3,4,5,6,7,8,9,10};
int sum=0;
for(int x: nums)
{
System.out.println("Value is :"+x);
sum=sum+x;
}
System.out.println("Summation : "+sum);
}
}
class Search
{ 25
public static void main(String args[])
{
int nums[]={6,8,3,7,5,6,1,4};
int val=5;
boolean found = false;
for(int x: nums)
{
if(x == val)
{
found = true;
break;
}
}
if(found)
System.out.println("Value found");
}
}
For multi-dimensional arrays 26

•The for-each version also works for multi-dimensional


arrays.

•Since a 2-d array is an array of 1-d array, the iteration


variable must be a reference to 1-d array.

•In general, when using the for-each for to iterate over an


array of N dimensions, the objects obtained will be arrays of
N–1 dimensions.
class ForEach
{
public static void main(String args[]) 2
{ 7
int sum = 0;
int nums[][] = new int[2][3];
// give nums some values
for(int i = 0; i < 2; i++)
for(int j=0; j < 3; j++)
nums[i][j] = (i+1)*(j+1);
for(int x[ ] : nums) //nums is a 2-d array and x is 1-
d array
{
for(int y : x) //y refers elements in 1-d array x
{
System.out.println("Value is: " +y);
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}
For Each…. 28

The for-each version of for has several applications viz.

 Finding average of numbers

 finding minimum and maximum of a set

 checking for duplicate entry in an array

 searching for an element in unsorted list etc.


Jump Statements….
29

• Java supports three jump statements: break, continue &


return. These statements pass control to another part of
the program.

Using break….
• The java break statement has three uses.
1. Terminates a statement in a switch.
2. Used to exit a loop.
3. Used as a civilized form of goto.
Using break to Exit a loop…
30

• Using break, we can force immediate termination of loop


bypassing the conditional expression and any remaining
code in the body of the loop.
Class BreakLoop
{
public static void main(String args[])
{
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.");
}
}
Using break as a Form of Goto….
31

• Java does not have a goto statement because it provides a


way to branch in an arbitrary and unstructured manner.
• There are few places where the goto is a valuable and
legitimate construct for flow control.
• The goto can be useful when we are exiting from a deeply
nested set of loops.
• Syntax :
break label;
class BreakLoop
{
32
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.println(j +" ");
}
System.out.println("This will not print.");
}
System.out.println("Loops complete.");
}
}
Using continue….
33

• If you want to continue running the loop but stop


processing the remainder of the code in its body for this
particular iteration, then will go for continue.
class Continue
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
System.out.println(i + " "); 0 1
if (i%2==0) continue; 2 3
System.out.println(" "); 4 5
} 6 7
} 8 9
}
return…
34

• The return statement is used to explicitly return from a


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

You might also like