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

M3 Statements FlowControl

Uploaded by

Justin Reynolds
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)
20 views

M3 Statements FlowControl

Uploaded by

Justin Reynolds
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/ 48

Statements and flow

control
Programming 1

-1-
Contents
1. Expressions and statements
2. Conditional execution
3. Loops

-2-
Deege U Java lesson 016

Expressions and
Statements
Expression

An expression is a construct made up of


literals, variables, operators, and/or method
calls, that evaluates to a single value

a = 15 * b + c;

When evaluated, the expression


will be replaced by its single
if (a < 120) {… value (= result)

Expression with single value


(=result) true of false…

-4-
Statement

Basic instruction

double a; Declaration statement

a = 15 * Math.PI; Assignment statement

if (a < 120) { if statement


A compound
System.out.println(a); Method statement:
call contains another
} statement

Single statements are terminated with a ;

-5-
Statement types

• Declaration
int a;
• Assignment
a = a + 1;
• Method call
System.out.println(a);
• Compound statements (flow control)
– Logical: if, switch
– Loop: while, for

-6-
Grouping statements: {block}
• A block is a group of statements enclosed
within {a pair of curly braces}
if (b < 12) { Bloc that groups
int a = 10; t o state ents
System.out.println(a + b);
}

• A block can be used anywhere a simple


statement is allowed

-7-
Quiz

HowMany.java
public static void main(String[] args) {
int guess; -How many expressions?
int secret = 56;
int counter = 0;
-How many statements?
-How many code blocks?
Scanner keyboard = new Scanner(System.in);
while (guess != secret) {
System.out.print("Enter a number: ");
guess = keyboard.nextInt();
counter++;
if (guess < secret) System.out.print("Higher! ");
if (guess > secret) System.out.print("Lower! ");
} //end while
System.out.print("Congratulations, you used " + counter
+ " guesses to find the right number!");
keyboard.close();
}//end main

-8-
Code convention: Indent blocks

HowMany.java
public static void main(String[] args) {
int guess;
int secret = 56;
int counter = 0;

Scanner keyboard = new Scanner(System.in);


while (guess != secret) {
System.out.print("Enter a number: ");
guess = keyboard.nextInt();
counter++;
if (guess < secret) System.out.print("Higher! ");
if (guess > secret) System.out.print("Lower! ");
} //end while
System.out.print("Congratulations, you used " + counter
+ " guesses to find the right number!");
keyboard.close();
}//end main

-9-
Code convention: Indent code
•Indent statements an extra level within each
new code block
•Indent when continuing a statement on a new
line

Menu: Code > Reformat Code

Shortcut Ctrl-Alt-L

- 10 -
Code blocks and variable scope
•A variable is only known within the block it is
declared… and in nested code blocks
•Scope = the program region where the
variable is known, where it can be used
– Starts from the line where it is declared
– Ends at the closing curly brace of the code
block in which it is declared

- 11 -
Quiz

•What is the output of this program?


Scope.java

bool
public static void main(String[] args) {
boolean bool = false;
outer int outer = 100;
if (!bool) {
inner
int inner = 10;
System.out.println(outer + inner);
}
bool = true;
inner if (bool) {
int inner = 42;
System.out.println(outer + inner);
}
System.out.println(outer);
}
Can o add here int outer = 200;?

Can o print here inner + outer?


- 12 -
Quiz
•Spot the errors
public static void main(String[] args) {
boolean bool = false;
int outer = 100; Wh is this code not co piling?
if (!bool) {
int inner = 10;
int value = 100; What do you need to modif
int outer = 50; to rod ce the expected
System.out.println(outer + inner + value); out t:
}
bool = true;
210
if (bool) {
102
int inner = 42;
360
outer = 60;
value = 200;
System.out.println(outer + inner + value);
}
inner = 121;
int value = 300;
System.out.println(outer + value);
}

- 13 -
Conditional
execution
Flow control
•Statements are executed in sequence
•Flow control statements modify the sequential
sequence
– conditional execution
▪if...else
▪switch
– repeated execution
▪while
▪for

- 15 -
if statement 4.5

•Only execute code if test succeeds


if (score >= 10) {
System.out.println("success");
}
The loc is exec ted i the (ex ression) is
true (if score is at least 10)

Deege U Java lesson 017


- 16 -
if syntax

if(condition)statement;

[condition == true]

Best practice:
always use a
{code block}
after an if statements

- 17 -
if…else statement 4.6

•Only execute if block if test is true


•Only execute else block if test is false
if (score >= 10) {
System.out.println("succes");
} else {
System.out.println("fail");
}

- 18 -
if…else syntax

if(condition)statement;
else statement;
[else] [condition == true]

Best practice:
always use a else if
statements statements
{code block}
after an if
and else

- 19 -
Exercise

Implement this algorithm in Java:


• Ask a score and calculate the grade
○ grade >= 90? write "A"
○ 90 > grade >= 80? write "B"
○ 80 > grade >= 70? write "C"
○ 70 > grade >= 60? write "D"
○ 60 > grade? write "E"

- 20 -
Nested if

if (grade >= 90) {


System.out.println("A");
Complex structure!
} else { Deep nesting
if (grade >= 80) {
System.out.println("B");
} else {
if (grade >= 70) {
System.out.println("C");
} else {
if (grade >= 60) {
System.out.println("D");
} else {
System.out.println("E");
}
}
}
}
- 21 -
if … else if

if (grade >= 90) {


System.out.println("A"); Simpler structure!
} else if (grade >= 80) { best practice:
System.out.println("B"); Use a simple statement
} else if (grade >= 70) {
(no block) when an
else is followed by a
System.out.println("C");
single if statement
} else if (grade >= 60) {
System.out.println("D");
} else {
System.out.println("E");
}

- 22 -
Conditional operator 4.6.4

Ternary operators

Operator Usage Result


If op1 is true then it yields the value of op2
?: op1 ? op2 : op3 else it yields the value op3. op1 must be a
boolean expression

The conditional operator works like an if?then:else.


Major difference: the expression with the conditional
operator returns a value.
An if () then else statement does not.

condition true false


System.out.println("BMI is " + ((bmi > 25) ? "too high" : "ok"));

if then else
1. returns "too high"or "ok"
2. concatenates returned value ith "BMI is "
- 23 -
switch statement 5.6

•To test equality against multiple values


Switch.java printDay
switch (day) {
case 0: System.out.println("monday"); break;
case 1: System.out.println("tuesday"); break;
case 2: System.out.println("wednesday"); break;
case 3: System.out.println("thursday"); break;
case 4: System.out.println("friday"); break;
case 5: System.out.println("saturday"); break;
case 6: System.out.println("sunday"); break;
}

Can o i ple ent this


al orith wit o t a s itc ?

Deege U Java lesson 018


- 24 -
switch statement syntax

Upon a atc (e.g. literal1)


integral (int, long…) t pe or String statements are e ecuted until the next
break. Witho t a break, statements o
literal2 would be exec ted as well.
switch (value) {
case literal1: statements; break;
case literal2: statements; break;

default: statements;
}
If no case matches, the (optional)
default:statements are e ecuted.

- 25 -
switch statement
•Fall through (until a break)
Switch.java printSeason
switch(month) {
case "march":
case "april":
case "may": System.out.println("spring");
break;
case "june":
case "july":
case "august": System.out.println("summer");
break;
case "september":
case "october":
case "november": System.out.println("autumn");
break;
case "december":
case "january":
case "february": System.out.println("winter");
break;
default: System.out.println("invalid month");
}
- 26 -
Simplified switch expression

since Java 14 multiple alues per case


switch (month) {
no reak necessary (and no fall through)
case "march", "april", "may" -> -> (instead o :)
System.out.println("spring");
case "june", "july", "august" ->
System.out.println("summer");
case "september", "october", "november" ->
System.out.println("autumn");
case "december", "january", "february" ->
System.out.println("winter");
default ->
System.out.println("invalid month");
}

- 27 -
Simplified switch expression
s itch can e used as an ex ression
since Java 14 (so, returns a alue)
String seasonName = switch (month) {
case "march", "april", "may" -> "spring";
case "june", "july", "august" -> "summer";
case "september", "october", "november" -> "autumn";
case "december", "january", "february" -> "winter";
default -> "invalid month";
}; If ou se a s itch ex ression
System.out.println(seasonName); and all ossi le cases are not
covered, then default is
mandator

Now, wh did the ake


default mandator here?
- 28 -
Simplified switch expression with {block}

Switch.java printSeasonYield
String seasonName = switch (month) {
case "march", "april", "may" -> "spring";
case "june", "july", "august" -> "summer";
case "september", "october", "november" -> "autumn";
case "december", "january", "february" -> "winter";
default -> {
System.out.println(
">>> Please use lower case english month names");
yield "invalid month"; When usin a {block ith m lti le statements}
} in a si plified s itch e pression
}; precede t e val e to be returned wit yield
System.out.println(seasonName);

- 29 -
Exercises
•Ex 03.01 Age
•Ex 03.02 Scrabble

- 30 -
Loops
while loop 4,7

•Repeats a codeblok while an kee ltipl ing


expression is true until product is
int product = 10; more than 100
while (product <= 100) {
product = product * 3;
} [else]

•A code block that is executed


repeatedly is [condition == true]

called a loop or iteration


statements

Deege U Java lesson 019


- 32 -
while syntax

while (condition) {
statements;
}

Processing:
1. check condition
○ If true: execute code block
(statements )and return to 1
(check again)
○ If false: end loop and continue
with the statement after the
codeblock
- 33 -
while loop

int counter = 10; Infinite loop!


Program never
int product = 1; finishes.
while (counter < 100) {
product = product * counter;
}

How would you solve this?

- 34 -
while loop
• The {curly braces} are not necessary if the
while statement is covering a single
statement int counter = 10;
while (counter < 100)
System.out.println(counter++);

Best practice: always use a {codeblock}


with a while for clarity

int counter = 10;


while (counter < 100) {
System.out.println(counter++);
}

- 35 -
break 5.7

Using break, you can exit a loop:


int counter = 10;
while (true) { // BAD coding practice!
System.out.println(counter++);
if (counter > 100) {break;}
}
System.out.println("After a while");

Best practice: Testing with while (condition)


is generally clearer to end the loop, than using
break

- 36 -
continue

continue stops the current iteration


and continues with the next while
iteration
Continue.java

int counter = 0;
while (++counter < 10) {
if (counter % 3 == 0) {continue;}
System.out.print(counter + " ");
}
// 1 2 4 5 7 8

- 37 -
do..while loop 5.5

•Repeat a codeblock while (post)condition is


true: block is executed one or more times
int counter= 0;
do {
System.out.print(++counter + " ");
} while (counter < 10);
statements

[else]
[condition == true]

- 38 -
do..while syntax

do {
statements;
} while (condition);

Processing:
1. execute code block (statements)
2. check condition
○ If true: go to 1
○ If false: end loop and continue with
the statement after the codeblock

- 39 -
Exercises
•Ex 03.03 Loops
– Task 1 & 2

- 40 -
for loop: count from 0 to 9 5.3

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


System.out.print(i + " ");
}
Variable declaration. i is initialised to 0.
Initialisation Executed first and only once

Test before each execution of the code block. If the


Condition test is false (when i == 10) , the loop terminates

After each execution of the code block this


Modification statement is executed: i is incremented

- 41 -
for loop

initialisation

Deege U Java
[else] lesson 020

code block
[condition == true]

Modification

- 42 -
for loop
•Compact syntax for repeating actions a
number of times
•Syntax
for (initialisation; condition; modification){
statements;
}

•Order of execution:

- 43 -
Comparing for and while loop

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


System.out.println(i);
}

int i = 0;
while(i < 10) {
System.out.println(i);
i++;
}

- 44 -
Remarks

for(initialisation; condition; modification){


statements;
}
• Initialisation, condition and modification
– The scope of the variables declared in the initialisation is
limited to the for loop
– Each part is optional, semicolons are mandatory
– Can contain multiple statements separated by comma’s

Best practice: keep it simple

- 45 -
Quiz
•What is the outcome of these for loops?
for (int i = 0; i < 10; i++) {
System.out.println(i);
}

for (int i = 1000; i > 0; i--) {


System.out.println(i);
}

for (int i = 0; i <= 100; i += 2) {


System.out.println(i); Keep it simple!
}

for (int i = 0,j = 10; i < 10; i++,j--) {


System.out.println(i*j);
}

- 46 -
Exercises
•Ex 03.03 Loops
– Task 3
•Ex 03.04-03.12

- 47 -
Review
1. Expressions and statements
2. Conditional execution
3. Loops

- 48 -

You might also like