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

Comprog - Java Chap 4

The document discusses different control structures in Java programming including branching statements like if/else and switch/case statements that allow programmers to selectively execute code based on conditions, as well as looping statements that repeatedly execute code. It provides syntax examples and flowcharts to illustrate if/else, nested if, and switch/case statements. The document also includes sample code and exercises for readers to practice implementing different control structures in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

Comprog - Java Chap 4

The document discusses different control structures in Java programming including branching statements like if/else and switch/case statements that allow programmers to selectively execute code based on conditions, as well as looping statements that repeatedly execute code. It provides syntax examples and flowcharts to illustrate if/else, nested if, and switch/case statements. The document also includes sample code and exercises for readers to practice implementing different control structures in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

JAVA PROGRAMMING-CHAPTER 4

CONTROL STRUCTURES

There are several types of program control structures which are


common in any other programming languages. This chapter
describes the different controls structures supported by the Java
programming language.

BRANCHING STATEMENTS
Branching Statements or Decision-Making Statements describes
how to use operators in expressions (expression consist of
operand and operator and/or constant value) in your code and
how those expressions in decision-making statements allows the
programmers to select specific sections of code to be executed.

The if Construct

Syntax:

if (boolean_expression)
{
code_block;
}// end of if construct

Typically, an if-construct can be illustrated by the figure below:

False
Condition

True
True Action

Figure 11. Flowchart of If-Statement


JAVA PROGRAMMING-CHAPTER 4

The if/else Construct

Syntax:

if (boolean_expression)
{
code_block;
}// end of if construct

else
{
code_block;
}// end of else construct

Typically, an if-else construct can be illustrated by the figure


below:

False True
Condition

False Action True Action

Figure 12. Flowchart of If-Else Statement


JAVA PROGRAMMING-CHAPTER 4

Chain if/else Construct (Ladder if)

Syntax:

if (boolean_expression)
{
code_block1;
}// end of if construct

else if (boolean_expression)
{
code_block2;
}// end of else if construct

else
{
code_block3;
}// end of else construct

Typically, a Nested If construct can be illustrated by the figure


below:

Y
Condition 1 Action 1

N
Y
Condition 2 Action 2

N
Y
Condition 2 Action 3

N
Action N

Figure 13. Flowchart of Nested If-Statement


JAVA PROGRAMMING-CHAPTER 4

If-Statement

Example.

If (sexCode = ‘M’){
System.out.println(“Male”);
}

If-Else Statement
Example.

public class TestExample1


{
public static void main (String [] )
{
int score = 80;
if (score >= 75)
{
System.out.println(“CONGRATULATIONS, YOU
PASSED!);
}
else
{
System.out.println(“SORRY, YOU FAILED”);
}
}
}

In the above given examples, the value of variables


sexCode and Score were set to certain values which
could be replace anytime, the given values were set
in order to test for a true or false output.
JAVA PROGRAMMING-CHAPTER 4

Example.

public class TestExample2


{
public static void main (String [] )
{
char grade = ‘A’;

if (grade == ‘A’)
{
System.out.println(“OUTSTANDING!);
}
else if (grade == ‘B’)
{
System.out.println(“VERY GOOD!);
}
else if (grade == ‘C’)
{
System.out.println(“GOOD!);
}
else if (grade == ‘D’)
{
System.out.println(“STUDY HARD!);
}
else
{
System.out.println(“Invalid code!”);
}
}
}

You could also try the following codes:


JAVA PROGRAMMING-CHAPTER 4

The switch_case Statement

Switch is multi branch decision statements that help you avoid


confusing code because it simplifies the organization of the
various branches of code that can be executed. When a switch is
encountered, Java first evaluates the switch_expression, and
jumps to the case 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. The switch
case statement can be illustrated same with the nested-if-
statement.

Syntax:

switch (variable)
{
case literal_value:
code_block;
[break;]
case another literal_value;
code_block;
[break;]
[default:]
code_block;
}
JAVA PROGRAMMING-CHAPTER 4

The Nested if-statement test whether the


boolean_expression will likely produce a true or
false. While the switch_case statement test for
exactness of literal_value being compared.
Therefore, the switch-case statement when being
executed lessen computing time compared with
nested-if-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 an exact literal value, either
single integer or character value or series of character value.
Also, the value provided to each case statement must be
unique.
JAVA PROGRAMMING-CHAPTER 4

Flowchart switch-statement

Y Action 1
Case 1 Break

N
Y Action 2
Case 2 Break

N
Y Action 3
Case 2 Break

N
Default Block

Figure 14. Switch-Case-Statement

Examples #3.

public class CaseSample


{
public static void main (String [] )
{
char ch=’A’;
switch (ch)
{
case ‘A’:
case ‘a’:
System.out.println(“ALPHA”);
break;
case ‘B’:
case ‘b’:
System.out.pritnln(“BRAVO”);
break;

default: System.out.pritnln(“OTHER CHARACTER”);


}
}
}
JAVA PROGRAMMING-CHAPTER 4

Another point of interest is the break statement. Each


break statement terminates the enclosing switch statement.
Control flow continues with the first statement following the
switch block. The break statements are necessary because
without them, statements in switch blocks fall through: All
statements after the matching case label are executed in
sequence, regardless of the expression of subsequent case labels,
until a break statement is encountered. The program
SwitchDemoFallThrough shows statements in a switch block that
fall through. The program displays the month corresponding to the
integer month and the months that follow in the year:
JAVA PROGRAMMING-CHAPTER 4

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, and 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, otherwise, the switch-statement will have the
same effect as with the nested if.

Technically, the final break is not required because flow


falls out of the switch statement. Using a break is recommended
so that modifying the code is easier and less error prone. The
default section handles all values that are not explicitly handled
by one of the case sections.
The following code example, SwitchDemo2, shows how a
statement can have multiple case labels. The code example
calculates the number of days in a particular month:
JAVA PROGRAMMING-CHAPTER 4
JAVA PROGRAMMING-CHAPTER 4

Name: Rating:

Instructor: Time & Day:

LABORATORY EXERCISES # 4.1


Problem # 1:
Write a java code that would accept a value of a Month of the
year (January – December). Then display the corresponding
season (Winter/ Spring/ Summer/ Fall) of the given inputted
month. Also, include the error detected if in case an inputted
month is invalid or misspelled.

Sample test runs:

Input any month of the year: March

“Enjoy the beginning of SPRING SEASON!”

Input any month of the year: January

“The cold never bothered me anyway!”


Also, consider error handling, where any given month when
misspelled such as:

Input any month of the year: Augst


“Sorry, you have inputted an invalid or misspelled
value of month of the year!”
JAVA PROGRAMMING-CHAPTER 4

LOOPING STATEMENTS

Repetition control structures allows us to execute specific


sections of the code a number of times. The statements inside
your source files are generally executed from top to bottom, in
the order that they appear.
While
Do-While
For

While Loop- iterates through a code block while an expression


yields a value of true. It is a zero-to-many iteration loop, the
boolean expression part of the loop is processed before the body
of the loop, it is immediately false, then the body will not be
processed at all.
Syntax:

while (boolean_expression){
code_block;
}// end of while construct

Example.

int ctr = 0;
while (i < 5){
System.out.println(ctr);
++ ctr;
}
JAVA PROGRAMMING-CHAPTER 4

Nested while Loops


A while loop could also be nested to create a continuous loop that
generate a laderrized algorithm.
Ex.
1. Draw a figure that will look like a rectangle below:
@@@@@@@@@@
@@@@@@@@@@
@@@@@@@@@@

Keyboard the code below:


public class WhileRectangle {
public int height = 3;
public int width = 10;

public void displayRectangle() {

int colCount = 0;
int rowCount = 0;

while (rowCount < height) {


colCount = 0;

while (colCount < width) {


System.out.println(“@”);
colCount ++
}
System.out.println();
rowCount++;
}
}
}

2. Compile your program.


3. Run your program.
JAVA PROGRAMMING-CHAPTER 4

Coding do/while Loop


This is a one-to-many iterative loop: the condition is at the
bottom of the loop and is processed after the body. The body of
the loop is therefore processed at least once.
Syntax:
do {
code_block;
}
while (boolean_expression); // mandatory semi-
colon.
Ex.
int ctr = 0;
do {
System.out.println(ctr);
++ ctr;
}
while (ctr < 5);

Using the for Loop


The for-loop allows your program to make an iterations through a
sequence of statements for pre-determined number of times.
Same with the while loop, it is a zero-to-many loop just like while-
statement, but more focus on counting through a range of values.
Syntax:
for(initial_value;boolean_expression;updates){
code_block;
}
Example.
for (ctr = 0;ctr < 5; ctr ++){
System.out.println(ctr);
}
JAVA PROGRAMMING-CHAPTER 4

Always remember that a for-construct must have


three (3) vital elements: 1. an initialized value
(which could be done in multiple variables
separated by commas.) 2. the boolean_expression
that will evaluates either true or false; 3. the update section
where variables are updated (increment or decrement) separate
multiple variables with commas.
JAVA PROGRAMMING-CHAPTER 4

Name: Rating:

Instructor: Time & Day:

LABORATORY EXERCISES #4.2 & 4.3

Problem 2 & 3. Make the same square image like what you did
in WhileSquare.java, this time, develop a class by using:

a) do-while structure (Save it to DoWhileSquare.java)


b) for-structure (save it to ForSquare.java)
JAVA PROGRAMMING-CHAPTER 4

Name: Rating:

Instructor: Time & Day:

LABORATORY EXERCISES # 4.4, 4.5 & 4.6

Problem # 4,5,&6. Using any of the iteration structure, write


a class that would display the following numbers sequence:
a. 1, 3, 6, 10, 15, 21, 28, 36, 45, 55 (Sequence1.java)
b. 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 (Sequence2.java)
c. 1, 10, 2, 9, 3, 8, 4, 7, 5, 6, 6 (Sequence3.java)
JAVA PROGRAMMING-CHAPTER 4

Control flow statements are Java statements that allow us to


select and execute specific blocks of code while skipping other
sections.
Break
Continue
Return

Examples:

Using a simple break statement in Java

Break_Ex1.java

public class Break_Ex1 {


public static void main(String args[]) {
for(int i=0; i<5; i++) {
if(i == 3)
break;
System.out.println("The value is : " + i);
}
}
}

Sample Output

The value is : 0
The value is : 1
The value is : 2

Modify the code for loop

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


System.out.println("The value is : " + i);
}

Sample Output

The value is : 0
The value is : 1
The value is : 2
The value is : 3
The value is : 4
JAVA PROGRAMMING-CHAPTER 4

The continue statement skips the current iteration of a loop


(for, while, and do...whileloop).

When continue statement is executed, control of the program


jumps to the end of the loop. Then, the test expression that
controls the loop is evaluated. In case of for loop, the update
statement is executed before the test expression is evaluated.

It is almost always used with decision making statements


(if...else Statement).

It's syntax is:

continue;

How continue statement works?


JAVA PROGRAMMING-CHAPTER 4

In case of nested loops, continue skips the current iteration of


innermost loop.

Example 1: Java continue statement


class Test {
public static void main(String [] args)
for (int i = 1; i <= 10; ++i) {
if (i > 4 && i < 9) {
continue;
}
System.out.println(i);
}
}
}

When the value of [i] becomes more than 4 and less than
9, continue statement is executed, which skips the execution
of System.out.println(i); statement.

When you run the program, the output will be:

1
2
3
4
9
10
JAVA PROGRAMMING-CHAPTER 4

Returning a Value from a Method

A method returns to the code that invoked it when it

 completes all the statements in the method,


 reaches a return statement, or
 throws an exception (covered later), whichever occurs
first.

You declare a method's return type in its method declaration.


Within the body of the method, you use the return statement to
return the value.

Any method declared void doesn't return a value. It does not need
to contain a return statement, but it may do so. In such a case,
a return statement can be used to branch out of a control flow
block and exit the method and is simply used like this:

return;

If you try to return a value from a method that is declared void,


you will get a compiler error.

Any method that is not declared void must contain


a return statement with a corresponding return value, like this:

Syntax:

return returnValue;

The data type of the return value must match the method's
declared return type; you can't return an integer value from a
method declared to return a boolean.

The getArea() method in the Rectangle returns an integer:

// a method for computing the area of the


rectangle
public int getArea() {
return width * height;
}
JAVA PROGRAMMING-CHAPTER 4

Name: Rating:

Instructor: Time & Day:

Laboratory Practice Task #4.7

Machine Problem No. 7:

Write a java code that calculates the sum of maximum of 5


positive numbers entered by the user. If the user enters
negative number or zero, it is skipped from calculation.

You might also like