Está en la página 1de 26

Computer Programming 2

1
Control Structures

Introduction to Algorithms
This module includes topics on:
1. Control Structures
2. Decision Control Structures
3. For loop
4. While and Do while

Control Structures
In this module, we are going to discuss control structures, that allows the program to choose a
direction in which to go based on a given condition.

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


 Use decision control structures (if, if-else, switch) which allows the program to select of
specific block of code to be executed.
 Use repetition control structures (while, do-while, for) which allows the program to execute a
block of codes a number of times.
 Use branching statements (break, continue, return) which allows the program to redirect the
flow of execution.
 Create program using control structures.

Decision Control Structures


Decision control structures are statements that allow the program to decide which block of
codes to be executed based from the given condition. The conditions in decision control structures
can be expressed using boolean expression. A Boolean expression is an expression that results to
boolean values (true or false). The following are the control structures used in Java:
 if statement
 if else statement
 if - else if - else statement

if Statement
The if-statement enables the program to execute a statement or block of codes if and only
if the boolean expression is true.
The if-statement is can be express this form,

Course Module
if (boolean_expression)
statement;
or
if (boolean_expression){
statement1;
statement2;
...
}

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


The figure below shows the execution flow of the if statement:

The flowchart above illustrates the process on how the program executes if-statement.
Flowchart is a diagram used to describe the process of a program, it uses shapes to represent the
steps or parts of the process. The diamond box represents a decision that determines which paths
is to be followed, or it denotes a boolean expression. Rectangular box represents the process
operation, or it denotes statements. Arrows connecting them represent the flow of control.
For example:
if(age>=18)
System.out.println("Qualified to vote!");

Below is the flowchart for the sample code above:

age >= 18

S
y
Computer Programming 2
3
Control Structures

if Statement Sample Program:

Output:

The program prompts the user to enter his age (lines 5–6) and displays "You are qualified
to vote it" if the value of age is greater than or equal to 18 (lines 7–8). If the value of age is less
than 18 it will do nothing.
Coding Guidelines:
1. Using if-statement without curly braces makes the code shorter, but it is prone to errors and
hard to read.
2. You should indent the statements inside the block, for example:
if( boolean_expression ){
//statement1;
//statement2;
}
3. Inside the block you can put any statement, meaning you have another if statement inside the
if statement, fir example:
if(boolean_expression){
if (boolean_expression){
//Statements
}
}

Course Module
if-else Statement
if-else statement is used when you want the program decide from which of the two sets of
statements is going to be executed based on whether the condition is true or false.
An if statement only executes the statements if the condition is true, and do nothing if the
condition is false. Unlike in an if-else statement the program can take alternative actions when the
condition is false. In the if-else statement we can execute another statements 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;
...
}

Below is the flowchart for if-else statement:

Based from the flowchart above, statement1 will be executed if the


boolean_expression evaluates to true, otherwise the statement2 will be executed.
Computer Programming 2
5
Control Structures

For example:
if(age>=18)
System.out.println("Qualified to vote!");
else
System.out.println("To young to vote!");

Below is the flowchart for the sample code above:

S S
y y

if-else Statement Sample Program:

Course Module
Output:

The program prompts the user to enter his age (lines 5–6) and displays "You are qualified
to vote it" if the value of age is greater than or equal to 18 (lines 7–8) and if the age is less than 18
it will display "You are too young to vote" (lines 10-11).

if-else if-else Statement


if-else if-else is used when the program have multiple alternative action to take. This
statement is actually an if-else statement with another if-else statement inside the else block.
Below is the form of nested-if statement:
if( boolean_expression ){
statement1;
statement2;
...
}
else{
if( boolean_expression ){
statement1;
statement2;
...
}
}

we usually write this as:


if( boolean_expression ){
statement1;
statement2;
...
}
else if( boolean_expression ){
statement1;
Computer Programming 2
7
Control Structures

statement2;
...
}
Take note that we can omit the last else block and we can add more else-if block after the
if-block.

Below is the flowchart for if-else if-else statement:

Boolean Expression 1

Boolean Expression 2

In the flowchart shown above, if boolean_expression1 evaluates to true, the program will
execute the statement1 and skips the other statements, if false,s the program will proceed to
evaluate the boolean_expression2. If boolean_expression2 evaluates to true, the program executes
statement2 and skips the else statement, otherwise the program will execute statement3.
For example:
if(age>=18){
System.out.println("Qualified to vote!");
}
else if(age < 0){
System.out.println("Invalid age!");
}
else{
System.out.println("Too young to vote!");
}
Course Module
Below is the flowchart for the sample code above:

age >= 18

S
y age < 0

if-else if-else Statement Sample Program:

Output:
Computer Programming 2
9
Control Structures

The program prompts the user to enter his age (lines 5–6) and displays "You are qualified
to vote it" if the value of age is greater than or equal to 18 (lines 7–8) and if the age is less than 0
it will display "You have entered an invalid age!" (lines 10-11), otherwise it will display it will
display "You are too young to vote" (lines 13-14).

Common Errors when using the decision control structure:


1. Only boolean value is accepted in the condition statement. For
example,
//WRONG
int num = 0;
if( num ){
// statements
}

The variable num does not hold a boolean value.


2. Using = instead of == for comparison. For example,
int num = 5;
if( num = 5 ){ //error in the condition
// statements
}

This should be written as,


int num = 5;
if( num == 5 ){
// statements
}

Course Module
3. Adding semi-colon at the end of if statement. For example,
if(num == 5);
// statements

4. Writing elseif instead of else if.


int num = 5;
if(num = 5){ //error in the condition
// statements
}elseif(num == 0){ //error, no space between else and if
// statements
}

This should be written as,


int num = 5;
if(num == 5){
// statements
}else if(num == 0){
// statements
}

Switch Statement
Another way to allow the program to have multiple alternative action is through switch
statement. It is similar to if-else if-else statement, however, if-else if-else statement is based from
the condition (whether true or false), while the switch statement can test the given value or
expression to different cases.

Below is the swith-statement form:


switch( switch_expression ){
case case_value1:
// statements
break;
case case_value2:
// statements
break;
...
Computer Programming 2
11
Control Structures

case case_valueN:
// statements
break;
default:
//statements
}

The switch_expression is a variable or expression that must have a type value of char, short,
int, long or string. The case_values must have the same type value as the switch_expression for
they will be checked if one of them is equal to the switch_expression. The case_values should be
a constant expression, meaning they cannot contain variables such x + 1. The case_values should
also unique, it is not allowed duplicate case_value. The keyword break is optional, this statement
immediately ends (break) the switch statement. It is allowed in a switch statement to have no block.

The switch statement first evaluates with the switch_expression, and then it will check if
value of first case (case_value1) matches the value of switch_expression. If their value matches it
will execute all the statements after case value until a break statement is encountered. If the two
values didn't matched it will proceed to another case, then check again if it matches with the
switch_expression. The process will continue until the program finds the matching case. In case
that there is no case matches with the switch_expression the default will be executed.

For example:
int num = 2;
switch(num){
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
case 4:

Course Module
System.out.println("Four");
break;
default:
System.out.println("Invalid Number");
}

Below is the flowchart of the example above:

Sy

The example above checks whether the value of num matches from value 1, 2, 3 or 4. If
the value of num matches with anyone from the cases, the program will display the converted word
of a number, if there is no matching value, “Invalid Number” will be displayed.
Computer Programming 2
13
Control Structures

Sample switch Statement Program:

Course Module
The program prompts the user to enter any number (lines 4–6) and displays the converted
word of a number if the number have entered matches with the listed cases (8-25). If there is no
matching value if will do nothing since it has no default case in switch statement.

Repetition Control Structures


Repetition control structures are Java statements that allow the program to execute
statements repeatedly. Repetition control structure is also called as loop statement, you can use
this statement if you want your program to perform the desired number of actions. For example, if
you want to display String value hundred times, instead of writing hundred statements for
displaying String value you can simply write one loop statement that iterates 100 times and inside
the loop is a statement that display String value. The following are the repetition structures used
in Java:
 while
 do-while
 for loop

The while Loop


The while loop executes the statements repeatedly as long as the condition is true. The
while loop has this form:
while(loop_condition){
//loop body
statements;
}

Below is the flowchart of while loop statement:

The statements inside the while loop will be executed as long as the loop_condition
evaluates to true. If the loop_condition evaluates to false it will exit or stop the loop. For example:
Computer Programming 2
15
Control Structures

int x = 1;
while(x <= 5){
System.out.print(x);
x++;
}

Below is the flowchart for the code snippet above:

The sample code snippet will display 12345. The program will first execute the statement
int x = 1;, this defines the variable x with an initial value of 1. Next, the program will execute the
while loop statement with loop_condition x<=5, in this case we yield true for the loop_condition.
Now that the loop_condition is true, the program displays the value of x which is 1. After the
program displays the value of x, it will execute the x++;, which means increment the value of x by
1, now we get 2 for the value of x. Next step is, the program will execute again the loop_condition,
in this step we evaluate the loop_condition to true since the value of x is 2. Then it will just repeat
the process until the value of x reaches to 5. The loop stops when the value of x is greater than 5.
The following are other examples of while loops,
Example 1:
int x = 5;
while (x>0)
{
System.out.print (x);
x--;
}

Course Module
The example above will display 54321. In this case we used decrement operator. The while
loop will stop when the value of x becomes 0.

Example 2:
int x = 0;
while(x<=5){
System.out.println(“Hello World!”);
}

The sample code above will have an infinite loop or it will just display “Hello World”
continuously without stopping. It leads to infinite loop because we didn't put statement that
controls the iteration. In this case, the value of x remains 0 and loop_condition (x<=5) is will
always be true.

Example 3:
//no loops
int x = 5;
while(x<5){
System.out.println(“Hello World!”);
}

The sample code above will display nothing because it will not reach the statements
System.out.println(“Hello World!”); due to loop_condition (x<5) evaluates to false.

While Loop Sample Program:


Computer Programming 2
17
Control Structures

The program prompts the user to enter any number (lines 5–6). Now, if num > 0 is true,
the program adds the value of num to sum. The value of variable num depends on the user’s input
(in this case num is 5), for each loop the value of num is decremented by 1. when the value of num
reaches 0, num > 0 is false, so the loop exits. Therefore, the sum is 5 + 4 + 3 + 2 + 1 = 15.

The do-while Loop

The do-while loop is almost the same as while loop, where they execute the body of loop
repeatedly as long as the condition is true. The only difference is that, do-while loop executes the
body of loop first and then evaluates the loop_condition.

The do-while loop has this form:

do{
//loop body
statements;
} while(loop_condition);

Take note that there is a semi-colon after the while expression, that is a common mistake
when using do-while loop.

Below is the flowchart of do-while loop:

Course Module
As you can see from the flowchart above, the loop body was executed first and then
evaluates the loop_condition. If the loop_condition evaluates to true, the loop body will be
executed again and if it is false, the loop will be terminated. The loop will continue as long as the
loop_condition evaluates to true. For example:

int x = 1;
do{
System.out.print(x);
x++;
} while(x <= 5);

Below is the flowchart for the code snippet above:

The sample code snippet will display 12345. The program will first execute the statement
int x = 1;, this defines variable x with an initial value of 1. Next, the program will execute the do-
while loop statement which will execute first the loop body, the loop body will display and
increment the value of x. After that, it will evaluate the loop_condition (x<=5), if the
loop_condition evaluates to true it will execute again the loop_body. The program will repeat the
same process until the value of x becomes 6.
The following are other examples of do-while loops,
Example 1:
int x = 5;
do{
System.out.print (x);
x--;
} while (x>0);

The example above will display 54321.

Example 2:
int x = 0;
Computer Programming 2
19
Control Structures

do{
System.out.println(“Hello World!”);
} while(x<=5);

The sample code above will have an infinite loop or it will just display “Hello World”
continuously without stopping.

Example 3:
int x = 5;
do{
System.out.println(“Hello World!”);
} while(x<5);

The sample code above will display Hello World!”, this loop will just execute the body of
statement then terminate the loop because the loop_condition (x<5) evaluates to false. Use a do-
while loop if you want your loop_body to be executed at least once.

do-while Loop Sample Program:

Course Module
The program prompts the user to enter any number repeatedly until the user entered 0.
Every time the user entered number it will be saved to variable num then the value of num will be
added to variable sum. The loop will not stop until the user entered 0. The program will just add
all the numbers that the user have entered.

The for Loop

The for loop is the same as the previous loop statement where it allows the program to
execute statement repeatedly. Unlike the previous loops, for loop has clear form to define loop.
Below is the form to define for loop:

for (loop_initial_expression; loop_condition; step_expression){


//loop body
statements;
}

The for loop statement starts with the keyword for, followed by a pair of parenthesis
enclosing the control structure of the loop. This structure used to define the limit of the iteration
and it is consist of loop_initial_expression followed by the loop_condition, then step_expression,
and they are separated by semi-colon. The loop_initial_expression is used to set the initial or
starting value of the loop variable. The loop_condition is used to compare the loop_variable to a
certain value (or value that defines the limit of the loop). The step_expression is used to update the
loop variable. The control structure is followed by the loop body enclosed inside the braces. loop
body contains statements that will be executed repeatedly based from the limit defined in control
structure. Below is the flowchart of for loop:
Computer Programming 2
21
Control Structures

As you can see from the flowchart, for loop first executes the loop_initial_expression, after
the program set the initial value of loop variable the program will proceed to loop_condition, if the
loop condition evaluates to true, the program will proceed to loop body, otherwise it will exit the
loop. After the loop body, the program will now execute the step_expression to update the loop
variable, then loop back to loop_condition, the process will continue as long as the loop_condition
evaluates to true.

For example:

int x;
for(x = 0; x <=5; x++){
System.out.print(x);
}

Course Module
The sample code snippet will display 12345. Below is the flowchart of while loop statement:

Based from the flowchart above, the program will executes first the x=0
(loop_initial_expression), after that, it will evaluate x<=5 (loop_condition), in this case we yield
true for this expression because the value x is 0 and it is less than 5, then the program will execute
the loop body. Next, x++ (step_expression) will be executed, this means that variable x will be
incrementd by 1. After the step_expression the program will execute again the loop_condition.
The same process will be repeated until the value of x becomes greater than 5.

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


int x = 0;
while( x < 5 ){
System.out.print(x);
x++;
}

The following are other examples of for loops,


Example 1:

int x;
for(x=5; x>0; x--){
System.out.print(x);
}
Computer Programming 2
23
Control Structures

The example above will display 54321. In this case we used decrement operator. The while
loop will stop when the value of x becomes 0.
Example 2:

int x;
for(x=0; x<=5; x--){
System.out.print("Hello World!");
}

The sample code above will loop until the maximum negative int value. In this case, the
value of x is decremented by 1 and loop_condition (x<=5) is will always be true.

Example 3:

int x;
for(x=5; x<5; x--){
System.out.print("Hello World!");
}

The sample code above will display nothing because it will not reach the statements
System.out.println(“Hello World!”);, due to loop_condition (x<5) evaluates to false.

while Loop Sample Program:

Course Module
The program prompts the user to enter any number (lines 7–8). The program will display
the value x repeatedly based from the number of the user’s input.

The Nested Loop

Nested loop is a loop inside the loop. The body of loop contains any statement, therefore it
could have another loop. Nested loops consist of an outer loop and one or more inner loops, this
means that for every loop inside the outer loop there is a complete execution of inner loop.

For example:

for(int x = 1; x<=3; x++)


{
for(int y = 1; y<=5; y++)
{
System.out.print(y);
}
System.out.println();
}
Computer Programming 2
25
Control Structures

Based from the sample code above, the outer will execute the loop body 3 times and it
contains inner loop and a statement that add new line (System.out.println()). The output of a
complete inner loop is 12345 therefore the final output of the sample code is:

1
2
3
4
5

Course Module 1
2
3
4
Nested Loop Sample Program:

The program prompts the user to enter table size (lines 6–7). The program will display
Multiplication Table and the size of the table will be based from the user’s input.

También podría gustarte