0% found this document useful (0 votes)
25 views

Chapter 3 Control Statment

Uploaded by

sisay alemu
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Chapter 3 Control Statment

Uploaded by

sisay alemu
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Chapter 3

Control Statements

1
Control Statements
 Generally, the statements inside source programs are
executed from top to bottom, in the order that they
appear.
Control flow statements, however, alter the flow of
execution and provide better control to the programmer
on the flow of execution.
In Java control statements are categorized into 3 groups:
1. Selection or Decision Making Statements : allow the
program to choose different parts of the execution based on
the outcome of an expression
2. Iteration Statements enable program execution to repeat
one or more statements
3. Jump Statements enable your program to execute in a non-
linear fashion Prepared by: Melkamu D. 2
Selection Statements
These statements allow us to control the flow of program execution based on condition.
 Java supports 2 selection statements:
 if statements
 switch statements
If statement:
It performs a task depending on whether a condition is true or false.
It is basically a two-way decision making statement and is used in conjunction with an
expression.
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested:

Test False
expression
?

Prepared by: Melkamu D. True 3


1. Simple if Statement

 An if statement consists of a Boolean expression followed by


one or more statements.
 The syntax of an if statement is:
if (expression)
{
statement-block;
}
rest_of_program;
• If expression is true, statement-
block is executed and then
rest_of_program.
• If expression is false, statement-
block will be skipped & the
execution will jump to the
rest_of_program
Prepared by: Melkamu D. 4
2. if … else Statement

 The syntax of an if…else statement is:


if (expression)
{
True-block statement(s);
}
else
{
False-block statement(s);
}
rest_of_program;

 If expression is true, True-block


statement is executed and followed by
rest_of_program block.
 If expression is false, False-block
Statement is executed followed by
rest_of_program block.
Prepared by: Melkamu D. 5
3. if … else if (else if Ladder) Statement

 Is used when multiple decisions are involved.


 A multiple decision is a chain of ifs in which the statement
associated with each else is an if.
 The conditions are evaluated from the top(of the ladder),
downwards.
 As soon as the true condition is found, the statement
associated with it is executed and the control will skip the rest
of the ladder.
 When all the conditions become false, then the final
else containing the default statement will be
executed.
 The syntax of an if …. else if statement is:
Prepared by: Melkamu D. 6
if (expression 1)
{
statement(s)-1;
}
else if (expression 2)
{
statement(s)-2;
}
...
else if (expression n)
{
statement(s)-n;
}
else
default-statement;
rest_of_program;

Prepared by: Melkamu D. 7


4. Nested if … else Statement

 if…else statements can be put inside other if…else


statements. such statements are called nested if … else
statements.
 Is used whenever we need to make decisions after
checking a given decision.
 The syntax of a nested if…else statement is shown in the
next slide.
 True-block statement 1.1 is executed if both expression 1
and expression 1.1 are true. But if expression 1 is true and
if expression 1.1 is false, then it is False-block statement
1.1 which is going to be executed.
Prepared by: Melkamu D. 8
}
if (expression 1)
{
statement(s)-1;
if (expression 1.1)
{
True-block Statement 1.1 Nested if statement
}
else
{
False-block Statement 1.1
}
}
else if (expression 2)
{
statement(s)-2;
}
...
else if (expression n)
{
statement(s)-n;
}
else
default-statement;
rest_of_program; Prepared by: Melkamu D. 9
Switch statement
 We can design a program with multiple alternatives using if
statements to control the selection.
 But the complexity of such programs increases dramatically
when the number alternatives increases.
 Java has a multi-way decision statement called switch statement.
 The switch statement tastes the value of a given
variable(expression) against a list of case values and when a
match is found, a block of statements associated with that case
is executed.

Prepared by: Melkamu D. 10


Switch syntax

switch (expression)
{
case value-1:
statement-block 1;
break;
case value-2:
statement-block 2;
break;
......
......
default:
default_statement;
break;
}
rest_of_program
Prepared by: Melkamu D. 11
Contd…
 The expression must evaluate to a char, short or int, but not
long, float or double.
 The values value-1, value-2, value-3, … are constants or constant
expressions (evaluable to an integral constant) and are known as
case labels.
 Each of the case labels should be unique within the switch
statement.
 statement-block1,statement-block2,…. Are
statement lists and may contain zero or
more statements.
Prepared by: Melkamu D. 12
Contd…
 There is no need to put braces around the statement blocks of a
switch statement but it is important to note that case labels end with
a colon (:).
 When the switch is executed, the value of the expression is
successfully compared against the values value-1, value-2, ….
 If a case is found whose value matches with the value of the
expression, then the block of the statement(s) that follows the case
are executed; otherwise the default-statement will be executed.
 The break statement at the end of each block signals the end of a
particular case and causes an exit from the switch statement.

Prepared by: Melkamu D. 13


The ?: (Conditional) Operator
 Is useful for making a two-way decisions.
 This operator is a combination of ? and : and takes three
operands.
General formula:
conditional expression ? Expression1:expression2;
 The conditional expression is evaluated first. If the result is true,
expression1 is evaluated and is returned as the value of the
conditional expression. Otherwise, expression2 is evaluated and
its value is returned.

Prepared by: Melkamu D. 14


Contd…
 For example:
if (x<=40)
if(x<40)
slary=4*x+100; Can be written as:
else salary=(x!=40)? (x<40)?
salary=300;
(4*x+100):(4.5*x+100)):300;
else
slary=4.5*x+100;
 When the conditional operator is used, the code becomes more
concise and perhaps, more efficient. However, the reliability is
poor.
 It is better to use if statement when more than a single nesting
of conditional operator is required.

Prepared by: Melkamu D. 15


Exercise
1. Find out Errors in the following program and discuss ways for correction.
a) //Errors.java
public Class Errors{
public void main(String [] args){
int i, j = 32768;
short s = j;
double m = 5.3f, n = 2.1f;
float x = 5.3, y = 2.1;
byte z = 128;
System.out.println("x % y = "+x % y);
boolean b = 1 ;
if (b) System.out.println(“b is true”);
else System.out.println(“b is false”);
}
}

Prepared by: Melkamu D. 16


2. Write a Java application program that asks the user to enter two numbers
obtains the numbers from the user and prints the sum, product,
difference and quotient of the numbers?
3. Write a Java application program that asks the user to enter two integers,
obtains the numbers from the user and displays the larger number
followed by the words “is larger than “ the smaller number in the screen.
If the numbers are equal, print the message “These numbers are equal.”
4. Write four different Java statements that each add 1 to integer variable x.
5. Rewrite each of the following without using compound relations:
a) if(grade<=59 && grade>=50)
second+=1; 6. Write a Java application
b) if(num>100 || num<0) program that reads the
System.out.prinln(“Out of Range”); coefficients of a quadratic
else equation (ax2+bx+c=0),
sum+=num; generates and display the
c) If((M>60 && N>60)||T>200) roots.
y=1; Note:
else An appropriate message should be
y=0; generated when the user types
an invalid input to the equation.
Prepared by: Melkamu D. 17
Iterative/Loop Statements

 The process of repeatedly executing a block of statements is


known as looping.
 A loop allows you to execute a statement or block of
statements repeatedly until a termination condition is met.
 The statements in the block may be executed any number of
times, from zero to infinite number.
 If a loop continues forever, it is called an infinite loop.
 A program loop consists of two statements:
 Body of the loop.
 Control statements.
 A looping process, in general, would include the four steps:
1. Setting and initialization of a counter .
2. Execution of the statements in the loop.
3. Test for a specified condition for execution of the loop.
4. Increment/Decrement the counter.

Prepared by: Melkamu D. 18


Contd…

Depending on the position of the control statement in the loop, a control structure can
be either as the entry-controlled loop or as exit-controlled loop.
In entry-controlled loop, the control conditions are tested before the start of the loop
execution.
In exit-controlled loop, the test is performed at the end of the
body of the loop and therefore the body is executed
unconditionally for the first time.
Three types of loops in java:
1. while loops
2. do …while loops
3. for loops

Prepared by: Melkamu D. 19


1. The while loop

 Is the simplest of all the looping structures in Java.


 The while loop is an entry-controlled loop statement.
 The while loop executes as long as the given logical expression
between parentheses is true. When expression is false,
execution continues with the statement immediately after the
body of the loop block.
 The expression is tested at the beginning of the loop, so if it is
initially false, the loop will not be executed at all.
 The basic format of the while statement is:
Example:
int sum=0,n=1;
initialization; while(n<=100)
while (expression) {
{ sum+=n;
Body of the loop; n++;
} }
System.out.println(“Sum=“+sum;
) by: Melkamu D.
Prepared 20
Contd…

 The body of the loop may have one or more statements.


 The braces are needed only if the body contains two or more statements. However
it is a good practice to use braces even if the body has only one statement .

2. The do…while loop


 Unlike the while statement, the do… while loop executes the
body of the loop before the test is performed.
Syntax: initialization;
do
{
Body of the loop;
}
while (expression);
Prepared by: Melkamu D. 21
Contd…

 On reaching the do statement, the program proceeds to


evaluate the body of loop first.
 At the end of the loop, the test condition in the while statement
is evaluated. If it is true, the program continues to evaluate the
body of the loop once again.
 When the condition becomes false, the loop will be terminated and the control goes
to the statement that appears immediately after the while statement.
 The while loop is an exit-controlled loop statement.
Example:
int sum=0,n=1;
do
{
sum+=n;
n++;
} while(n<=100);
System.out.println(“Sum=“+sum);
Prepared by: Melkamu D. 22
3. The for loop

 Is another entry-controlled loop that provides a more


concise loop controlled structure.
 Syntax for the for loop is:

for(initialization; test condition; increment)


{
Body of the loop;
}

 We use the for loop if we know in advance for how many


times the body of the loop is going to be executed.
 But use do…. while loop if you know the body of the loop
is going to be executed at least once.
Prepared by: Melkamu D. 23
Contd…

 The execution of the for loop statement is as follows:


1. Initialization of the control variable(s) is done first, using assignment statement.
2. The value of the control variable is tested using the test condition. The test
condition is a relation operation that determines when the loop will exit.
 If the condition is true, the body of the loop is executed;
otherwise the loop is terminated and the execution continues
with the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to the for
statement after evaluating the last statement in the loop.
 Now the new value of the control variable is again tested to see
whether it satisfies the loop condition; if it does, the body of
the loop is again executed.

Prepared by: Melkamu D. 24


Contd…

Example
int sum=0;
for(n=1; n<=100; n++)
{
sum=sum+n;
}
System.out.println(“Sum is:”+sum);

Additional Features of for loop


A. More than one variable, separated by comma, can be initialized
at a time in the for statement.
Example:
for(sum=0, i=1; i<=100; i++)
{
sum=sum+i;
}
Prepared by: Melkamu D. 25
Contd…

B. Increment section may also have more than one part.


Example:
for(i=0, j=0; i*j < 100; i++, j+=2)
{
System.out.println(i * j);
}
C. The test condition may have any compound relation
and the testing need not be limited only to the
loop control variable.
Example:
for(sum=0, i=1; i<20 && sum<100; ++i)
{
sum=sum+i;
}
Prepared by: Melkamu D. 26
Contd…
D. You do not have to fill all three control sections, one or more
sections can be omitted but you must still have two
semicolons.
Example:
int n = 0;
for(; n != 100;) {
System.out.println(++n);
}

Prepared by: Melkamu D. 27


Nesting of for loops

 You can nest loops of any kind one inside another to any depth.
Example:
for(int i = 10; i > 0; i--)
{
while (i > 3)
{
if(i == 5){
break;
}
System.out.println(i); Inner Outer
i--; Loop Loop
}
System.out.println(i*2);
}

Prepared by: Melkamu D. 28


Jumps in Loops
 Jump statements are used to unconditionally transfer the
program control to another part of the program.
 Java has three jump statements: break, continue, and return.
1. The break statement
A break statement is used to abort the execution of a loop. The general
form of the break statement is given below:
break label;
It may be used with or without a label.
When it is used without a label, it aborts the execution of the innermost
switch, for, do, or while statement enclosing the break statement. When
used with a label, the break statement aborts the execution of any
enclosing statement matching the label.
A label is an identifier that uniquely identifies a block of code.

Prepared by: Melkamu D. 29


Examples

1. Outer: for( int k=1; k< 10; k++){


int i=k;
while ( i < 5) {
if(i%5==0) break Outer; // jump out of both loops
System.out.print(“ “+i);
i++;
}
System.out.println(“Outer Loop”);
}
2. int i=1;
while ( i < 10) {
if(i%2==0) break;
System.out.println(“ “+i);
}
System.out.println(“Out of the while loop”);
Prepared by: Melkamu D. 30
2. The continue statement

is used to alter the execution of the for, do, and while statements.
The general form of the continue statement is:
continue label;
It may be used with or without a label. When used without a label, it
causes the statement block of the innermost for, do, or while
statement to terminate and the loop’s boolean expression to be re-
evaluated to determine whether the next loop repetition should take
place.

Prepared by: Melkamu D. 31


Contd…

When it is used with a label, the continue statement transfers


control to an enclosing for, do, or while statement matching the
label.
Example:
int sum = 0;
for(int i = 1; i <= 10; i++)
{
if(i % 3 == 0)
{
continue;
}
sum += i;
}
1 + 2 +of4 +sum?
What is the value 5 + 7 + 8 + 10 = 37
Prepared by: Melkamu D. 32
3. The return Statement

A return statement is used to transfer the program control to the


caller of a method.
The general form of the return statement is given below:
return expression;
If the method is declared to return a value, the expression used
after the return statement must evaluate to the return type of that
method. Otherwise, the expression is omitted.

Prepared by: Melkamu D. 33


Contd…

//Use of Continue and break Statements *


class ContinueBreak
{
** Output
public static void main(String [ ]args) ***
{
Loop1: for(int i=1; i<100; i++) ****
{
System.out.println(" ");
*****
if (i>=8) break; ******
for (int j=1; j<100; j++)
{ *******
System.out.print("*");
if (j==i) continue Loop1;
Termination by BREAK
}
}
System.out.print("Termination by BREAK");
}
}

Prepared by: Melkamu D. 34


Exercise
1. What do the following program print?
public class Mystery3{
public static void main(String args[]){
int row = 10, column;
while(row >= 1){
column = 1;
while(column <= 10){
System.out.print(row % 2 == 1 ? “<” : “>”);
++column;
}
--row;
System.out.println();
}
}
}

Prepared by: Melkamu D. 35


Contd…
2. Write a Java application program that asks the user to enter an integer
number from the keyboard and computes the sum of the digits of the
number. [ Hint: if the user types 4567as input , then the output will be 22 ]
3. Given a number, write a program using while loop to reverse the digits of the
number. [ Hint: Use Modulus Operator to extract the last digit and the integer division by 10
to get the n-1 digit number from the n digit]
4. Using a two-dimensional array, write codes that could print the following outputs?
c) 5
a) 454
$ $ $ $ $ 34543
$ $ $ $ 2345432
$ $ $ 123454321
$ $
$
b) 1 d) 1 2 3 4 5 4 3 2 1
1 2 1234321
1 2 3 12321
1 2 3 4 121
1 2 3 4 5 Prepared by: Melkamu D.
1 36
E ND
Th e
u ! !!
k Yo
Th an
37 Prepared by: Melkamu D.

You might also like