Notes4 Control Structures

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 13

J.E.D.I.

Control Structures
1 Objectives
In the previous sections, we have given examples of sequential programs, wherein statements are
executed one after another in a fixed order. In this section, we will be discussing control structures,
which allows us to change the ordering of how the statements in our programs are executed.

At the end of the lesson, the student should be able to:


 Use decision control structures (if, else, switch) which allows selection of specific sections of code

to be executed
 Use repetition control structures (while, do-while, for) which allow executing specific sections of
code a number of times
 Use branching statements (break, continue, return) which allows redirection of program flow

2 Decision Control Structures


Decision control structures are Java statements that allows us to select and execute specific blocks of
code while skipping other sections.

2.1 if statement
The if-statement specifies that a statement (or block of code) will be executed if and only if a certain
boolean statement is true.

The if-statement has the form,

if( boolean_expression )
statement;

or

if( boolean_expression ){
statement1;
statement2;
. . .
}

where, boolean_expression is either a boolean expression or boolean variable.

Figure 1: Flowchart of If-Statement

Introduction to Programming III theboi 1


J.E.D.I.
For example, given the code snippet,

int grade = 68;

if( grade > 60 ) System.out.println("Congratulations!");

or

int grade = 68;

if( grade > 60 ){


System.out.println("Congratulations!");
System.out.println("You passed!");
}

Coding Guidelines:

1. The boolean_expression part of a statement should evaluate to a boolean value. That means that
the execution of the condition should either result to a value of true or a false.
2. Indent the statements inside the if-block.For example,
if( boolean_expression ){
//statement1;
//statement2;
}

2.2 if-else statement


The if-else statement is used when we want to execute a certain statement if a condition is true, and a
different statement if the condition is false.

The if-else statement has the form,

if( boolean_expression )
statement;
else
statement;

or can also be written as,

if( boolean_expression ){
statement1;
statement2;
. . .
}
else{
statement1;
statement2;
. . .
}

For example, given the code snippet,

int grade = 68;

if( grade > 60 ) System.out.println("Congratulations!");


else System.out.println("Sorry you failed");

or

int grade = 68;

if( grade > 60 ){


System.out.println("Congratulations!");
Introduction to Programming III theboi 2
J.E.D.I.
System.out.println("You passed!");
}
else{
System.out.println("Sorry you failed");
}

Figure 2: Flowchart of If-Else Statement

Coding Guidelines:

1. To avoid confusion, always place the statement or statements of an if or if-else block inside brackets
{}.
2. You can have nested if-else blocks. This means that you can have other if-else blocks inside another
if-else block.For example,
if( boolean_expression ){
if( boolean_expression ){
...
}
}
else{ . . .
}

2.3 if-else-if statement


The statement in the else-clause of an if-else block can be another if-else structures. This cascading of
structures allows us to make more complex selections.

The if-else if statement has the form,

if( boolean_expression1 )
statement1;
else if( boolean_expression2 )
statement2;
else
statement3;

Take note that you can have many else-if blocks after an if-statement. The else-block is optional and
can be omitted. In the example shown above, if boolean_expression1 is true, then the program
executes statement1 and skips the other statements. If boolean_expression2 is true, then the program
executes statement 2 and skips to the statements following statement3.

Introduction to Programming III theboi 3


J.E.D.I.

Figure 3: Flowchart of If-Else-If Statement


For example, given the code snippet,

int grade = 68;

if( grade > 90 ){


System.out.println("Very good!");
}
else if( grade > 60 ){
System.out.println("Very good!");
}
else{
System.out.println("Sorry you failed");
}

2.4 Common Errors when using the if-else statements:

1. The condition inside the if-statement does not evaluate to a boolean value. For example,

//WRONG
int number = 0;
if( number ){
//some statements here
}

The variable number does not hold a Boolean value.

2. Using = instead of == for comparison. For example,

//WRONG
int number = 0;
if( number = 0 ){
//some statements here
}

Introduction to Programming III theboi 4


J.E.D.I.
This should be written as,

//CORRECT
int number = 0;
if( number == 0 ){
//some statements here
}

3. Writing elseif instead of else if.

2.5 Example for if-else-else if


public class Grade
{
public static void main( String[] args )
{
double grade = 92.0;

if( grade >= 90 ){


System.out.println( "Excellent!" );
}
else if( (grade < 90) && (grade >= 80)){
System.out.println("Good job!" );
}
else if( (grade < 80) && (grade >= 60)){
System.out.println("Study harder!" );
}
else{
System.out.println("Sorry, you failed.");
}
}
}

2.6 switch statement


Another way to indicate a branch is through the switch keyword. The switch construct allows
branching on multiple outcomes.

The switch statement has the form,

switch( switch_expression ){
case case_selector1:
statement1; //
statement2; //block 1
. . . //
break;

case case_selector2:
statement1; //
statement2; //block 2
. . . //
break;
. . .
default:
statement1; //
statement2; //block n
. . . //
break;
}

where, switch_expression is an integer or character expression and, case_selector1, case_selector2


and so on, are unique integer or character constants.

When a switch is encountered, Java first evaluates the switch_expression, and jumps to the case
Introduction to Programming III theboi 5
J.E.D.I.
whose selector matches the value of the expression. The program executes the statements in order
from that point on until a break statement is encountered, skipping then to the first statement after
the end of the switch structure.

If none of the cases are satisfied, the default block is executed. Take note however, that
the default part is optional. A switch statement can have no default block.

NOTES:
 Unlike with the if statement, the multiple statements are executed in the switch statement without
needing the curly braces.
 When a case in a switch statement has been matched, all the statements associated with that case
are executed. Not only that, the statements associated with the succeeding cases are also executed.
 To prevent the program from executing statements in the subsequent cases, we use a break
statement as our last statement.

Coding Guidelines:

1. Deciding whether to use an if statement or a switch statement is a judgment call. You can decide
which to use, based on readability and other factors.
2. An if statement can be used to make decisions based on ranges of values or conditions, whereas a
switch statement can make decisions based only on a single integer or character value. Also, the
value provided to each case statement must be unique.

Figure 4: Flowchart of Switch Statements

2.7 Example for switch


public class Grade
{
public static void main( String[] args )
{
Introduction to Programming III theboi 6
J.E.D.I.
int grade = 92;

switch(grade){
case 100:
System.out.println( "Excellent!" );
break;
case 90:
System.out.println("Good job!" );
break;
case 80:
System.out.println("Study harder!" );
break;
default:
System.out.println("Sorry, you failed.");
}
}
}

3 Repetition Control Structures


Repetition control structures are Java statements that allows us to execute specific blocks of code a
number of times. There are three types of repetition control structures, the while, do-while and for
loops.

3.1 while loop


The while loop is a statement or block of statements that is repeated as long as some condition is
satisfied.

The while statement has the form,

while( boolean_expression ){
statement1;
statement2;
. . .
}

The statements inside the while loop are executed as long as the boolean_expression evaluates to
true.

For example, given the code snippet,

int i = 4;
while ( i > 0 ){
System.out.print(i);
i--;
}

The sample code shown will print 4321 on the screen. Take note that if the line containing the
statement i--; is removed, this will result to an infinite loop, or a loop that does not terminate.
Therefore, when using while loops or any kind of repetition control structures, make sure that you add
some statements that will allow your loop to terminate at some point.

The following are other examples of while loops,

Example 1:

int x = 0;
while (x<10)
{
System.out.println(x); 
x++;
}

Introduction to Programming III theboi 7


J.E.D.I.
Example 2:

//infinite loop
while(true)
System.out.println(“hello”);
Example 3:

//no loops
// statement is not even executed
while (false)
System.out.println(“hello”);

3.2 do-while loop


The do-while loop is similar to the while-loop. The statements inside a do-while loop are executed
several times as long as the condition is satisfied.

The main difference between a while and do-while loop is that, the statements inside a do-while loop
are executed at least once.

The do-while statement has the form,

do{
statement1;
statement2;
. . .
}while( boolean_expression );

The statements inside the do-while loop are first executed, and then the condition in the
boolean_expression part is evaluated. If this evaluates to true, the statements inside the do-while loop
are executed again.

Here are a few examples that uses the do-while loop:

Example 1:

int x = 0;
do
{
System.out.println(x);
x++;
}while (x<10);

This example will output 0123456789 on the screen.

Example 2:

//infinite loop
do{
 System.out.println(“hello”);
} while (true);

This example will result to an infinite loop, that prints hello on screen.

Example 3:

//one loop
// statement is executed once
do
  System.out.println(“hello”); 
while (false); 

Introduction to Programming III theboi 8


J.E.D.I.

This example will output hello on the screen.


Coding Guidelines:

1. Common programming mistakes when using the do-while loop is forgetting to write the semi-colon
after the while expression.
do{
...
}while(boolean_expression) //WRONG->forgot semicolon ;
2. Just like in while loops, make sure that your do-while loops will terminate at some point.

3.3 for loop


The for loop, like the previous loops, allows execution of the same code a number of times.

The for loop has the form,

for (InitializationExpression; LoopCondition; StepExpression){


statement1;
statement2;
. . .
}

where,
InitializationExpression -initializes the loop variable.
LoopCondition - compares the loop variable to some limit value.
StepExpression - updates the loop variable.

A simple example of the for loop is,

int i;
for( i = 0; i < 10; i++ ){
System.out.print(i);
}

In this example, the statement i=0, first initializes our variable. After that, the condition expression
i<10 is evaluated. If this evaluates to true, then the statement inside the for loop is executed. Next,
the expression i++ is executed, and then the condition expression is again evaluated. This goes on and
on, until the condition expression evaluates to false.

This example, is equivalent to the while loop shown below,

int i = 0;
while( i < 10 ){
System.out.print(i);
i++;
}

4 Branching Statements
Branching statements allows us to redirect the flow of program execution. Java offers three branching
statements: break, continue and return.

4.1 break statement


The break statement has two forms: unlabeled (we saw its unlabeled form in the switch statement)
and labeled.

4.1.1 Unlabeled break statement


The unlabeled break terminates the enclosing switch statement, and flow of control transfers to the
statement immediately following the switch. You can also use the unlabeled form of the break
statement to terminate a for, while, or do-while loop.
Introduction to Programming III theboi 9
J.E.D.I.

For example,

String names[] = {"Beah", "Bianca", "Lance", "Belle",


"Nico", "Yza", "Gem", "Ethan"};

String searchName = "Yza";


boolean foundName = false;

for( int i=0; i< names.length; i++ ){


if( names[i].equals( searchName )){
foundName = true;
break;
}
}

if( foundName ){
System.out.println( searchName + " found!" );
}
else{
System.out.println( searchName + " not found." );
}

In this example, if the search string "Yza" is found, the for loop will stop and flow of control transfers to
the statement following the for loop.

4.1.2 Labeled break statement


The labeled form of a break statement terminates an outer statement, which is identified by the label
specified in the break statement. The following program searches for a value in a two-dimensional
array. Two nested for loops traverse the array. When the value is found, a labeled break terminates
the statement labeled search, which is the outer for loop.

int[][] numbers= {{1, 2, 3},


{4, 5, 6},
{7, 8, 9}};

int searchNum = 5;
boolean foundNum = false;

searchLabel:
for( int i=0; i<numbers.length; i++ ){
for( int j=0; j<numbers[i].length; j++ ){
if( searchNum == numbers[i][j] ){
foundNum = true;
break searchLabel;
}
}
}

if( foundNum ){
System.out.println( searchNum + " found!" );
}
else{
System.out.println( searchNum + " not found!" );
}

The break statement terminates the labeled statement; it does not transfer the flow of control to the
label. The flow of control transfers to the statement immediately following the labeled (terminated)
statement.

Introduction to Programming III theboi 10


J.E.D.I.

4.2 continue statement


The continue statement has two forms: unlabeled and labeled. You can use the continue statement to
skip the current iteration of a for, while or do-while loop.

4.2.1 Unlabeled continue statement


The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression
that controls the loop, basically skipping the remainder of this iteration of the loop.

The following example counts the number of "Beah"s in the array.

String names[] = {"Beah", "Bianca", "Lance", "Beah"};


int count = 0;

for( int i=0; i<names.length; i++ ){

if( !names[i].equals("Beah") ){
continue; //skip next statement
}

count++;
}

System.out.println("There are " + count + " Beahs in the list");

4.2.2 Labeled continue statement


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

outerLoop:
for( int i=0; i<5; i++ ){

for( int j=0; j<5; j++ ){


System.out.println("Inside for(j) loop"); //message1
if( j == 2 ) continue outerLoop;
}

System.out.println("Inside for(i) loop"); //message2


}

In this example, message 2 never gets printed since we have the statement continue outerloop which
skips the iteration.

4.3 return statement


The return statement is used to exit from the current method. The flow of control returns to the
statement that follows the original method call. The return statement has two forms: one that returns
a value and one that doesn't.

To return a value, simply put the value (or an expression that calculates the value) after the return
keyword. For example,

return ++count;
or
return "Hello";

The data type of the value returned by return must match the type of the method's declared return
value. When a method is declared void, use the form of return that doesn't return a value. For
example,

return;

Introduction to Programming III theboi 11


J.E.D.I.
We will cover more about return statements later when we discuss about methods.

Introduction to Programming III theboi 12


J.E.D.I.

5 Exercises
5.1 Grades
Get three exam grades from the user and compute the average of the grades. Output the average of
the three exams. Together with the average, also include a smiley face in the output if the average is
greater than or equal to 60, otherwise output :-(.
1. Use BufferedReader to get input from the user, and System.out to output the result.
2. Use JOptionPane to get input from the user and to output the result.

5.2 Number in words


Get a number as input from the user, and output the equivalent of the number in words. The number
inputted should range from 1-10. If the user inputs a number that is not in the range, output, "Invalid
number".
1. Use an if-else statement to solve this problem
2. Use a switch statement to solve this problem

5.3 Hundred Times


Create a program that prints your name a hundred times. Do three versions of this program using a
while loop, a do-while loop and a for-loop.

5.4 Powers
Compute the power of a number given the base and exponent. Do three versions of this program using
a while loop, a do-while loop and a for-loop.

Introduction to Programming III theboi 13

You might also like