0% found this document useful (0 votes)
28 views52 pages

Control Structure: Branching & Repetition: Object-Oriented Programming

The document discusses different control structures for branching and repetition in programming, including the if-else statement, ternary operator, switch-case statement, for loop, while loop, and do-while loop. It provides examples of using these structures to calculate body mass index (BMI) and determine weight categories, as well as making coffee based on input levels. The objective is for students to understand and apply branching and repetition models in developing programming solutions.

Uploaded by

aska lombang
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)
28 views52 pages

Control Structure: Branching & Repetition: Object-Oriented Programming

The document discusses different control structures for branching and repetition in programming, including the if-else statement, ternary operator, switch-case statement, for loop, while loop, and do-while loop. It provides examples of using these structures to calculate body mass index (BMI) and determine weight categories, as well as making coffee based on input levels. The objective is for students to understand and apply branching and repetition models in developing programming solutions.

Uploaded by

aska lombang
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/ 52

Control Structure:

Branching & Repetition


Object-Oriented Programming

Mario Simaremare, S.Kom., M.Sc.


Program Studi Sarjana Sistem Informasi
Institut Teknologi Del
Objectives

• The objectives of this session are the following:


• The students are able to elaborate the basic concept of
branching and repetition.
• The students are able to choose the most appropriate
branching and repetition model to develop a solution.
• The students are able to develop solutions with simple and
complex cases which involve branching and repetition.

Object-Oriented Programming 2
Please see these materials first

Object-Oriented Programming 3
Outlines

1. Branching.
• The if-else, ternary, and switch-case models.
2. Repetition.
• The for and its variants, while, and do-while models.
• Breaking and skipping a loop.

Object-Oriented Programming 4
Branching

Object-Oriented Programming 5
Background

• A simple problem probably will generate a simple solution.


• A solution that might only have exactly one execution flow.

• A more complex problem might require a more


complex and sophisticated solution that takes care
alternative situations.

Object-Oriented Programming 6
A case study

• Body mass index (BMI) is a method for weight category.


• underweight, healthy weight, overweight, and obesity.
• To calculate BMI, the following formula is used:
𝑤𝑒𝑖𝑔ℎ𝑡
𝐵𝑀𝐼 =
ℎ𝑒𝑖𝑔ℎ𝑡 2
Weight is in kilogram (kg), and height in meter (m).

Object-Oriented Programming 7
// File: BMICalculator.java
package example.branching;
Body Mass Index (BMI)
public class BMICalculator {
public static float calculate(int _weight, int _height) {
float height_m = (float) _height / 100; // in m
return (_weight / (height_m * height_m)); BMI implementation in a class-level behavior.
} Why not object level?

// File: Driver.java 29.75


package example.branching;

public class Driver {


public static void main(String[] args) {
int weight = 87; // in kg
Use the BMI implementation.
int height = 171; // in cm

float bmi = BMICalculator.calculate(weight, height);

System.out.printf("%.2f\n", bmi);
}
}

Object-Oriented Programming 8
Branching: key concept

• A branching provides at least two possible execution paths.


• At runtime, a decision point is required to decide which path
should be executed.

• A conditional expression is used as the basis to decide


where the program should go.

Object-Oriented Programming 9
Branching in Java

• Java has a number of branching statements that are


equivalent to those in C/C++.
• Similar statements are also found in other languages
like C#, PHP, etc.

• Branching statements:
• the if-else statement; and
• the switch-case statement.

Object-Oriented Programming 10
Conditional expression

• In Java, a conditional expression is an expression that returns


a Boolean value, either true or false.
• Can be generated from either relational and logical operations.

• Some conditional expressions:


• x > 3
• (x != 0) && (y == 0)
• (y % x) > 0
• true
• !(x.equals(y))

Object-Oriented Programming 11
The if-else Model

Object-Oriented Programming 12
The if-else model

• It creates at least two possible execution paths.


• elseif and else – are optional.

• It is possible to have a branching that:


• consists of multiple alternative flows;
• is designed in a nested fashion. if(conditional-expression) {
// alternative flow
} else if(conditional-expression) {
// alternative flow
if(conditional-expression) { } else {
// alternative flow // alternative flow
} }

Object-Oriented Programming 13
package example.branching;

public class Driver {

Body Mass Index (BMI)


public static void main(String[] args) {
int weight = 87; // in kg
int height = 171; // in cm

float bmi = BMICalculator.calculate(weight, height);

System.out.printf("%.2f\n", bmi);

short bmiLevel = 0; // assume normality


Maps the BMI level, a 0 means normal,
if (bmi < 16.0) {
a negative value means thinness, and
bmiLevel = -3;
} else if (16.0 <= bmi && bmi < 17.0) { a positive value implies obesity.
bmiLevel = -2;
} else if (17.0 <= bmi && bmi < 18.5) {
bmiLevel = -1;
} else if (25.0 <= bmi && bmi < 30.0) { 29.75
bmiLevel = 1; 1
} else if (30.0 <= bmi && bmi < 35.0) {
bmiLevel = 2;
} else if (35.0 <= bmi && bmi < 40.0) {
bmiLevel = 3;
} else if (40.0 < bmi) {
bmiLevel = 4;
}

System.out.printf("%h\n", bmiLevel);
}
}

Object-Oriented Programming 14
The Ternary Model

Object-Oriented Programming 15
The ternary model

• It is a short version of if-else model.


• It uses ?: operator, a ternary operator.

type v;
if(conditional-expression) {
v = expression1;
} else { equivalent
v = expression2;
}

type v;
v = (conditional-expression)? expression1 : expression2;

Object-Oriented Programming 16
package example.branching;

public class Driver {

public static void main(String[] _args) { Body Mass Index (BMI)


int weight = 87; // in kg
int height = 171; // in cm

float bmi = BMICalculator.calculate(weight, height);

System.out.printf("%.2f\n", bmi);

boolean normal_bmi = true;


boolean normal_bmi = ((18.5 > bmi || bmi > 25.0))? false : true;
if (18.5 > bmi || bmi > 25.0) {
normal_bmi = false;
}

// use level for next processing


System.out.printf("%b\n", normal_bmi);
}

Object-Oriented Programming 17
The switch-case Model

Object-Oriented Programming 18
The switch-case model

• A multi-alternative flows.
• An expression is tested to a list of labels.
• Possible labels:
• Constant expression of type char, byte, short, and int;
• Enumerated constants; or
• String literals. switch (expression) {
• When the expression matches to a label: case constant1:
• the program execution continues ... statements
execution
there downwardly. case constant2:
• Otherwise: ... statements
• If the default case does exist, ... // more cases
the execution continues there. default: // optional
... statements
• Else, no action at all.
}

Object-Oriented Programming 19
package example.branching;

import java.util.Scanner;

public class CoffeeExample { A case that suits


public static void main(String[] _args) {
Scanner scanner = new Scanner(System.in); switch-case scenario
short level = 0; // 2 the highest
level = scanner.nextShort(); 2
add creamer
switch (level) { add sugar
case 2:
add coffee
System.out.printf("add creamer\n");
starts here add boiling water
case 1:
System.out.printf("add sugar\n"); then goes downwardly
default: // other choice
System.out.printf("add coffee\n"); 1
System.out.printf("add boiling water\n"); add sugar
} add coffee
add boiling water
scanner.close();
}

} 0
add coffee
add boiling water

Object-Oriented Programming 20
package example.branching;

public class Driver {

Body Mass Index (BMI)


public static void main(String[] args) {
int weight = 87; // in kg
int height = 171; // in cm

float bmi = BMICalculator.calculate(weight, height);

System.out.printf("%.2f\n", bmi);
29.75
short bmiLevel = 0; // assume normality 1
obese class iii Incorrect, why?
if (bmi < 16.0) {
bmiLevel = -3;
} else if (16.0 <= bmi && bmi < 17.0) {
bmiLevel = -2;
} else if (17.0 <= bmi && bmi < 18.5) { String strBmiLevel = null;
bmiLevel = -1;
} else if (25.0 <= bmi && bmi < 30.0) { switch (bmiLevel) {
bmiLevel = 1; case -3:
} else if (30.0 <= bmi && bmi < 35.0) { strBmiLevel = "severe thinness";
bmiLevel = 2; case -2:
} else if (35.0 <= bmi && bmi < 40.0) { strBmiLevel = "moderate thinness";
bmiLevel = 3; case -1:
} else if (40.0 < bmi) { strBmiLevel = "mild thinness";
bmiLevel = 4; case 0:
} ...
case 4:
System.out.printf("%h\n", bmiLevel); strBmiLevel = "obese class iii";
} }
}
System.out.printf("%s\n", strBmiLevel);

Object-Oriented Programming 21
Breaking the switch-case

• Cases serve as labels, from where the program execution will go.
• The execution then to be continued from that point downwardly.
• To escape, break or return keyword is used.
switch (expression) {
case label1:
... statements
execution
break;
case label2:
... statements
break;
... // more cases
default: // optional
... statements
}

Object-Oriented Programming 22
package example.branching;

public class Driver {

Body Mass Index (BMI)


public static void main(String[] args) {
int weight = 87; // in kg
int height = 171; // in cm

float bmi = BMICalculator.calculate(weight, height);

System.out.printf("%.2f\n", bmi); 29.75


1
short bmiLevel = 0; // assume normality overweight
if (bmi < 16.0) {
bmiLevel = -3;
} else if (16.0 <= bmi && bmi < 17.0) {
bmiLevel = -2; String strBmiLevel = null;
} else if (17.0 <= bmi && bmi < 18.5) {
bmiLevel = -1; switch (bmiLevel) {
} else if (25.0 <= bmi && bmi < 30.0) { case -3:
bmiLevel = 1; strBmiLevel = "severe thinness";
} else if (30.0 <= bmi && bmi < 35.0) { break;
bmiLevel = 2; ....
} else if (35.0 <= bmi && bmi < 40.0) { case 0:
bmiLevel = 3; strBmiLevel = "normal";
} else if (40.0 < bmi) { break;
bmiLevel = 4; case 1:
} strBmiLevel = "overweight";
break;
System.out.printf("%h\n", bmiLevel); ....
} case 4:
} strBmiLevel = "obese class iii";
}

Object-Oriented Programming 23
Repetition

Object-Oriented Programming 24
Repetition

• As its name suggests, a repetition repeats a sequence


of statements.
• When the repetition happens?

• The decision to repeat the sequence is made based on


the fulfilment of a condition.
• When the condition is checked?

• A repetition is also called as a loop.

Object-Oriented Programming 25
Repetition in Java

• The decision to repeat the sequence is based on the result of


an evaluation of the conditional expression.
• A conditional expression produces a Boolean-typed value.

• The for and its variants, while and do-while forms.


• for – suitable for a deterministic situation or a range value.
• Capable to iterate collection-typed objects like arrays, lists, sets, etc.
• while – suitable for a non-deterministic situation.
• do-while – similar to the while form, the condition is evaluated later.

Object-Oriented Programming 26
Repetition models

Characteristic for while do-while


Evaluation beginning beginning end
Case suitability deterministic, range non-deterministic non-deterministic
Min. #of iteration 0 0 1

Object-Oriented Programming 27
The for Loop &
Its Variants

Object-Oriented Programming 28
The for loop: suitable cases

• Characteristics for for

• Deterministic. ... ...

• Range values.
done done
sheet
jump 1 to 10
1 to 20

• Sample cases: next next

• Jump 10 times.
jumping grading

• Grade 20 answer sheets. ... ...

• For each students,


do a given question. ... ...

Object-Oriented Programming 29
The for loop statement

• In Java, a for loop statement consists of: for

• A watch variable (sentinel) declaration and initialization. ...

• A conditional expression used to determine whether


the loop should go or stop. done
jump 1 to 10

• The test should be based on the watch variable.


next
• The loop will stop when the expression returns false. jumping

• A statement to either step up or step down the watch


variable towards the boundary. ...

...
for(decl-init statement; cond-expr; incr-decr statement) {
// repetition body
}

Object-Oriented Programming 30
The for loop statement
An statement to declare and initialize A conditional expression to decide should
the watch variable (sentinel). the repetition body be executed or not.
This statement will be executed once, This expression will be executed right before
before any other instructions. the repetition body.

for(decl-init statement; cond-expr; incr-decr statement) {


// repetition body
}

A statement to change the watch variable either


with increment or decrement approach.
This statement will be executed right after
the repetition body is fully executed.

Object-Oriented Programming 31
package example.repetition;

The for loop statement


public class JumpingExample {

public static void main(String[] _args) {


short nrJumping = 10;

for (short c = 0; c < nrJumping; c++) {


System.out.printf("Jumping #%d\n", c + 1); Jumping #1
} Jumping #2
} Jumping #3
} Jumping #4
Jumping #5
Jumping #6
Jumping #7
Jumping #8
package example.repetition; Jumping #9
Jumping #10
public class JumpingExample {

public static void main(String[] _args) {


short nrJumping = 10;

for (short c = 1; c <= nrJumping; c++) {


System.out.printf("Jumping #%d\n", c);
}
}
}

Object-Oriented Programming 32
The for loop statement to
iterate a collection object
The to-be iterated collection.
An element, retrieved from the collection.

for(Type element : collection) {


// repetition body
}

Object-Oriented Programming 33
package example.repetition;

import java.util.Collection;
import java.util.LinkedList;
The for loop statement to
iterate a collection object
public class ForCollection {

public static void main(String[] _args) {


Collection<String> names
= new LinkedList<String>(); package example.repetition;

names.add("Jaka Sembung"); public class ForArray {


names.add("Milkyman");
names.add("Wiro Sableng"); public static void main(String[] _args) {
String[] names = new String[3];
for (String name : names) {
System.out.println(name); names[0] = "Jaka Sembung";
} names[2] = "Wiro Sableng";
}
} for (String name : names) {
System.out.println(name);
Jaka Sembung }
Milkyman }
Wiro Sableng }

Jaka Sembung
null
Wiro Sableng

Object-Oriented Programming 34
The while Loop

Object-Oriented Programming 35
The while loop: suitable cases

• Characteristics: while while

• Non-deterministic. ... ...

false false

• Sample cases:
still day any sheet?

• Jump ‘til sun sets.


true true

jumping grading

• Grade all the answer sheets.


... ...

... ...

Object-Oriented Programming 36
The while loop statement

• In Java, a while loop statement consists


while
of: while

• A conditional expression to make decision. ... ...

• The loop will keep going when the conditional expression


returns a true value. Otherwise,
falseit stops. false
still day any sheet?
• Sometime in the future, the conditional expression must fail
and return a false value. true true

• If this never happens, the loop will repeat infinitely.


jumping grading

... ...

... ...
while(conditional-expression) {
// repetition body
}

Object-Oriented Programming 37
The while loop statement

A conditional expression to decide should


the repetition body be executed or not.
This expression will be executed before
the repetition body.

while(conditional expression) {
// repetition body
}

It has to be guaranteed that, sometime in the future, the conditional


expression will eventually fail and return a false.

Object-Oriented Programming 38
package example.repetition;

The while loop statement


public class GradingExample {

public static void main(String[] _args) {


short nrAnswerSheet = 12;
short grading = 0;

while (grading < nrAnswerSheet) { This is the way to make the conditional expression fail sometime
++grading; in the future.
System.out.printf("grading #%d\n", grading);
}
}
}

grading
grading
#1
#2
Can you develop the same solution
grading #3 with a decrement operation?
grading #4
grading #5
grading #6
grading #7
grading #8
grading #9
grading #10
grading #11
grading #12

Object-Oriented Programming 39
The do-while Loop

Object-Oriented Programming 40
The do-while loop: suitable cases

• Characteristics: do-while do-while

• Non-deterministic. ... ...

• Executed at least happens once. guessing collecting

... ...

• Sample cases:
• A random number is generated. incorrect
more hobby?

Guess the number!


true guessing? true

false false

• Say, everyone has at least a hobby.


Some even have more.
... ...

Object-Oriented Programming 41
The do-while loop statement

• In Java, a do-while loop statement consists of: do-while

• A body that will be executed at least once. ...

• A conditional expression to make decision. guessing

• The loop will keep going when the conditional expression


returns a true value. Otherwise, it stops. ...

• Sometime in the future, the conditional expression must fail


and return a false value.
incorrect
• If this never happens, the loop will repeat infinitely. true guessing?

false

...
do {
// repetition body
} while(conditional-expression);

Object-Oriented Programming 42
The do-while loop statement

The repetition body will be executed at least once.

do {
// repetition body
} while(conditional expression);

A conditional expression to decide should the statement repeat.


This expression will be executed after the repetition body.

Object-Oriented Programming 43
package example.repetition;
import java.util.Scanner;

The do-while loop statement


public class GuessingGameExample {

public static void main(String[] _args) {


Scanner scanner = new Scanner(System.in);
short randomNumber = (short) ((Math.random() * (4)) + 1);
short guess = 0;

do { Generating a random number 1 – 5.


System.out.printf("What's your guess?\n");
guess = scanner.nextShort();
} while (guess != randomNumber);

System.out.printf("Horray, your guess is correct. The number is %d\n", randomNumber);


scanner.close();
}

What's your guess?


4
What's your guess?
5
What's your guess?
2
Horray, your guess is correct. The number is 2

Object-Oriented Programming 44
Exiting and Skipping Loop

Object-Oriented Programming 45
Exiting from a loop

• Sometimes, during the loop execution, we need to stop


the loop and exit from it immediately.
• To do so, use the break keyword.

• This approach forces the loop to end abnormally.


• The conditional expression should be the only one mechanism
to decide the loop’s lifecycle.

• Use it with extra care.

Object-Oriented Programming 46
package example.repetition;

public class BreakingLoopExample {

public static void main(String[] _args) {


char c = 'A'; Change two sentinels at once.
Exiting from a loop
for (short i = 0; i < 20; ++i, c++) {
if (c == 'K') {
break;
} The loop will be immediately exited.
System.out.printf("%c ", c);
}
System.out.printf("\n%c\n", c);
}

A B C D E F G H I J
K

Object-Oriented Programming 47
Skipping a loop cycle

• Sometimes, during the loop execution, we need to skip all


the instructions in the loop and go to the next one.
• To do so, use the continue keyword.

• This approach may confuse other developers.

• Use it with extra care.

Object-Oriented Programming 48
package example.repetition;

public class BreakingLoopExample {

public static void main(String[] _args) {


char c = 'A';
Skipping a loop cycle
for (short i = 0; i < 20; ++i, c++) {
if (c == 'K') {
continue;
} This exact loop cycle will be skipped.
System.out.printf("%c ", c);
}
System.out.printf("\n%c", c);
}

A B C D E F G H I J L M N O P Q R S T
U

Object-Oriented Programming 49
Todo

• Try to fully implement the BMI calculator.


• Make it cleaner with more constructs?

• Try to generate problems that utilize


repetitions in the solutions.

Object-Oriented Programming 50
References

• Cay Horstman. Core Java.


• Matt Weisfeld. The Object-Oriented Thought Process.

Object-Oriented Programming 51
Thank
you

Object-Oriented Programming 52

You might also like