Notes4 Control Structures
Notes4 Control Structures
Notes4 Control Structures
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.
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.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.
if( boolean_expression )
statement;
or
if( boolean_expression ){
statement1;
statement2;
. . .
}
or
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;
}
if( boolean_expression )
statement;
else
statement;
if( boolean_expression ){
statement1;
statement2;
. . .
}
else{
statement1;
statement2;
. . .
}
or
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{ . . .
}
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.
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
}
//WRONG
int number = 0;
if( number = 0 ){
//some statements here
}
//CORRECT
int number = 0;
if( number == 0 ){
//some statements here
}
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;
}
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.
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.");
}
}
}
while( boolean_expression ){
statement1;
statement2;
. . .
}
The statements inside the while loop are executed as long as the boolean_expression evaluates to
true.
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.
Example 1:
int x = 0;
while (x<10)
{
System.out.println(x);
x++;
}
//infinite loop
while(true)
System.out.println(“hello”);
Example 3:
//no loops
// statement is not even executed
while (false)
System.out.println(“hello”);
The main difference between a while and do-while loop is that, the statements inside a do-while loop
are executed at least once.
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.
Example 1:
int x = 0;
do
{
System.out.println(x);
x++;
}while (x<10);
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);
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.
where,
InitializationExpression -initializes the loop variable.
LoopCondition - compares the loop variable to some limit value.
StepExpression - updates the loop variable.
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.
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.
For example,
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.
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.
if( !names[i].equals("Beah") ){
continue; //skip next statement
}
count++;
}
outerLoop:
for( int i=0; i<5; i++ ){
In this example, message 2 never gets printed since we have the statement continue outerloop which
skips the iteration.
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;
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.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.