Control Structure and Method
Control Structure and Method
Structure
3 and Method
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Describe three types of control structures;
2. Develop programs using selection structures;
3. Develop programs using repetitive structures;
4. Describe the syntax of declaring a method in Java ; and
5. Develop Java programs that have method overloading.
X INTRODUCTION
As highlighted in Topic 2, there are two basic aspects of programming: data and
instructions. To work with data, you need to understand variables and data
types; to work with instructions, you need to understand control structures and
methods. This topic will focus on control structures and methods. Variables and
data types have been elaborated upon, in Topic 2.
Bohm and Jacopini conducted research in the 1960s and concluded that all
programs can be written in a structured way by only using three control
structures, which are:
These structures that are capable of changing the flow of control in a program
can be implemented in Java language. We will look at each structure in the
following sections.
What is Algorithm?
A step-by-step problem-solving procedure written in natural language such as
English.
if (expression)
statement;
In Java, the expression value is from the boolean type, that is, the
expression has true/false values. Therefore, the expression value besides the
true or false is invalid for use in the expression.
Bi-selection
Bi-selection provides other alternatives if the requisite is not fulfilled. The
following is an example of an algorithm condition, where one of the choices is
accomplished.
The above algorithm can be translated into the if-else structure as:
if(expression)
statement 1;
else
statement 2;
TOPIC 3 CONTROL STRUCTURE AND METHOD W 45
In the case of single selection, if the expression has a false value, no action will
be taken. This is different from the case of bi-selection, where we are given
another alternative, that is, if the expression has a false value, statement 2
will be accomplished. With reference to the above example, if the age is or more
than 55, the words „compulsory retirement‰ will be printed.
Multi Selection
Multi selection enables the programmer to determine the actions that have to be
accomplished in certain conditions by imposing a requisite. Observe the
following algorithm:
At any one time, only one situation can take place. In this case, we use the if-
else-if structure. The Java code that is at par with this is:
if (raceCode == ‘M’)
System.out.println (“Malay”);
else if (raceCode == ‘C’)
System.out.println (“Chinese”);
else if (raceCode ==’I’)
System.out.println (“Indian”);
else
System.out.println (“Others”)
For example, say raceCode is valued ‘I’. With this value, the expression
raceCode ==’M’ will have a false value, therefore the program control will
abandon the statement System.out.println (“Malay”); and tests the next
expression, that is raceCode == ‘C’. This statement also has a false value
and the action that matches it i.e. System.out.println (“Chinese”); is
abandoned. The next expression is tested and found that the value to be true,
then the expression System.out.println(“Indian”); will be accomplished
and the „Indian‰ string will be printed as shown in Figure 3.3.
TOPIC 3 CONTROL STRUCTURE AND METHOD W 47
Java also supports the use of the ? Operator, which is sometimes very useful. The
expression:
Example:
SELF-CHECK 3.1
r = 2;
if (r > 1)
System.out.println (“AAA”);
else System.out.println (“BBB”);
if (r < 1)
System.out.println (“AAA”);
else System.out.println (“BBB”);
if (r != 1)
System.out.println (“AAA”);
else System.out.println(“BBB”);
switch (expression) {
case constant1:
statements1
break;
case constant2:
statements2
break;
.
. // (more cases)
.
case constantN:
statementsN
break;
default: // optional default case
statements(N+1)
} // end of switch statement
A switch statement allows you to test the value of an expression and, depending
on that value, to jump to another location within the switch statement. The
expression must be either integer-valued or character-valued. It cannot be a
String or a real number. The positions that you can jump to are marked with
"case labels" that take the form: "case constant:". This marks the position the
computer jumps to when the expression evaluates to the given constant. The
default statement is optional to the programmers. It provides a default jump
point that is used when the value of the expression is not listed in any case label.
The following is a program segment to test the choice made from the menu
system:
int choice = 1;
switch (choice) {
case 1: … // choose menu 1
break;
case 2: … // choose menu 2
break;
case 3: … // choose menu 3
break;
case 4: … // choose menu 4
break;
default: … // wrong input
break;
}
The break statement can also be used to force the program control to exit any
loop blocks.
50 X TOPIC 3 CONTROL STRUCTURE AND METHOD
Vtwg
Ecug"3
Hcnug
Vtwg
Ecug"4
Hcnug
Vtwg
Ecug"5
Hcnug
Vtwg
Ecug"6
Hcnug
Figure 3.4: Selection structure in multi selection using switch and break
The following example shows the use of a switch statement from the previous
example of the if-else-if structure:
TOPIC 3 CONTROL STRUCTURE AND METHOD W 51
switch (raceCode){
case ‘M’: System.out.println (“Malay”); break;
case ‘C’: System.out.println (“Chinese”); break;
case‘I’ : System.out.printn (“Indian”); break;
default : System.out.println (“Others”);
}
Observe that repetition takes only a few lines of coding as compared to the
sequential solution to accomplish the same task. From here, you can see the
advantages of using repetition in loop. Loops allow a sequence of instructions to
be repeated over and over.
The repetitive structure in Java is the same as in C, except that the expression that
is tested should take the boolean value. Repetition can be implemented by
using one of the following structures: while, do-while or for.
52 X TOPIC 3 CONTROL STRUCTURE AND METHOD
while (expression) {
block_statement
}
The while loop will not be accomplished at all if the expression value is
false the first time it is tested. Notice the example below to find the addition
integer from 1 to 100.
The while loop in the above example will stop when the value i exceeds 100.
When the i value exceeds 100, the requisite (expression)will become false.
For the repetitive structure while, there are four basic components that need to
be fulfilled.
1. Initial Statement
This statement will assign an initial value for the variable that will be used
in the loop. In our example, the i = 1 statement is the initial statement.
2. Stop Requisite
This requisite will be tested to determine whether the next iteration needs
to be accomplished. In the above example, i < = 100 is the stop
requisite.
4. Updated Statement
Normally, this statement is placed at the end of the loop. In our example,
the control variable, which is i will be updated i++.
In contrast, the do-while loop is a variation of the while loop. Its syntax is as
below:
do {
Statement1
Statement2
……
……
StatementN
} while (condition)
For the do-while loop, the loop body will be executed first. Then, the
condition is evaluated. If the condition is true, the loop body will be
executed. Otherwise, the loop will be terminated. The difference between the
while loop and do-while loop is the order in which the condition is
evaluated and the loop body executed.
for(initial_value;requisite;update){
block_statement
}
Unlike while and do-while statements, the for loop is used for the number of
loop repetitions that is already known in advance.
We can give an initial value to several variables that usually act as the calculator
in the first slot. Unlike C, Java allows the int type variable to be declared and
given its initial value at this slot. However, it is only valid in the body or for the
loop block where it is declared.
The second slot requisite is used to test the requisite that determines whether
the body of a for loop will be accomplished or not. The third slot which
is updates describes how to update to change the initial_value
(counter). C block_statement can consist of only one simple statement
or a block. Therefore, nested loop is also allowed.
54 X TOPIC 3 CONTROL STRUCTURE AND METHOD
HI
HI
HI
HI
HI
break;
In the above program, the program will exit the loop when the value of line
becomes 3 even though the requisite for the loop is line <=5. The result that
will be displayed is:
HI
HI
HI
TOPIC 3 CONTROL STRUCTURE AND METHOD W 55
break and continue can be used in while loops and do..while loops. They
can also be used in for loops and switch statement. Note that when a break
occurs inside an if statement, it breaks out of the loop or switch statement that
contains the if statement. If the if statement is not contained inside a loop or
switch, then the if statement cannot legally contain a break statement. A
similar consideration applies to continue statements.
Outer loop
Inner loop
*
**
***
****
*****
56 X TOPIC 3 CONTROL STRUCTURE AND METHOD
Remember
If you use a break statement inside a nested loop (that is the inner loop), it
will only break out of that loop, not out of the loop that contains the nested
loop (outer loop).
ACTIVITY 3.1
Do you know how to compare the values of two numbers? What is the
suitable loop instruction? Design a simple program.
SELF-CHECK 3.2
We will start with two examples in order to explain the concept of compound
statements. Consider the following two examples:
Example 1:
1 int x=2;
2 if (x==2)
3 System.out.println(“Hi”);
4 System.out.println(“Hello”);
5 System.out.println(“Bye”);
TOPIC 3 CONTROL STRUCTURE AND METHOD W 57
Example 2:
1 int x=2;
2 if (x==3)
3 {
4 System.out.println(“Hi”);
5 System.out.println(“Hello”);
6 }
7 System.out.println(“Bye”);
Hi
Hello
Bye
Bye
Do you know why there is a difference between the output for Example 1 and
Example 2?
In Example 1, there are no braces { } for the if statement in line 2. Thus, only one
statement that follows the if statement (that is Line 3) is subjected to the
condition of line 2 (i.e. if line 2 returns a true boolean value, then line 3 will be
executed whereas line 3 will not be executed if line 2 returns a false value). Line 4
and 5 will be executed irrespective whether line 2 returns a true or false value.
In Example 2, there are braces { } for the if statement in line 3 and line 6. All the
statements inside the braces (line 4 and 5) are subjected to the condition of line 2
(i.e. Lines 4 and 5 will be executed if line 2 returns a true value and they will not
be executed if line 2 returns a false value). Line 7 will be executed irrespective of
whether line 2 returns a true or false value because it is not inside the braces.
58 X TOPIC 3 CONTROL STRUCTURE AND METHOD
Example 3:
int x=2;
int y=3;
if (x==2)
{
if (y==1)
System.out.println(“Hi”);
System.out.println(“Hello”);
}
System.out.println(“Bye”);
Hello
Bye
Example 4:
Hi
Hello
Hi
Hello
Hi
Hello
*********************
Hi
Hi
Hi
Hello
SELF-CHECK 3.3
3.4 METHOD
Methods allow the programmer to modularise a program each method will
perform a single specialised task.
A query method is used to access only the objectÊs state and this operation does
not change the state of an object. Examples of this method are:
x getName()
x getPay()
x RetrieveID()
x checkPassword()
Finally, task methods are used to perform a specific task. This method may
change the state of the object. Examples of this method are:
x calculateAge()
x convertToCelcius()
Example:
}
return value
The <return_type> indicates the type of value returned by the method. If the
method does not return any value, then it should be declared void as shown
below:
}
TOPIC 3 CONTROL STRUCTURE AND METHOD W 63
If the method returns a value such as an int value, then the method should be
declared as int as shown in the example below:
If the method returns a String value, then the method should be declared as
String, as shown in the example below:
The same goes for other methods that return other data types such as float,
double, char, boolean, etc. Use the return statement within the method to pass
back value if the method returns a value as shown in the next example:
Note that the return statement should not be included within the method if it is a
void method.
Example 1:
Example 2:
Example 3:
Example 4:
Arguments
If a method does not return any value (i.e. it is a void method), then the method
must be a statement. For example:
calculateAge();
If a method has a parameter, then you need to include the arguments during the
method invocation. The arguments must match the parameters in order, number
and compatibility as defined in the method signature.
66 X TOPIC 3 CONTROL STRUCTURE AND METHOD
Example 5:
class obj {
public static void main (String[ ] args ){
int a=67;
int b=80; pass the
value
int max=getMax(a,b);
System.out.println(“Maximum is “ + max);
}
When you invoke a method that has parameter(s), the value of the argument is
passed to the parameter in the method as a pass-by-value. It means the value of
the variable represented as an argument in the method invocation will be passed
to the parameter. The argument will not be affected regardless of the changes
made to the parameter inside the method.
class obj {
public static void main (String[ ] args ){
int a=67, b=80;
float c=4.5f, d=89.7f;
int max1=getMax(a,b); //Line 5
float max2=getMax(c,d); //Line 6
System.out.println(“Maximum integer number is “ + max1);
System.out.println(“Maximum float number is “ + max2);
}
public static int getMax(int no1, int no2){ //first method
int max;
if (no1>no2)
max= no1;
else
max= no2;
return max;
}
float max;
if (no1>no2)
max= no1;
else
max= no2;
return max;
}
}
68 X TOPIC 3 CONTROL STRUCTURE AND METHOD
In line 5 of the above program, it will invoke the first method that will determine
the maximum value between two integer numbers. In line 6, it will invoke the
second method that will determine the maximum value between two float
numbers.
As you can see in the above program, two methods with the same name have
been declared. This approach of declaring more than one method with the same
name but with a different parameter list is known as method overloading. You
cannot overload methods based on different modifiers or return types.
x Bohm and Jacopini have conducted research in the 1960s and concluded that
all programs can be written in a structured way by only using three control
structures, namely: sequential structure, selection structure and repetitive
structure.
break Method
case Nested Loops
continue Repetitive Structure
do-while Selection Structure
for Sequential Structure
if switch
if-else while