Control Flow
Program with linear control flow
• Statements executed in sequence
Statement 1
• Linear flow
Statement 2
• No jumping
Statement 3 • No looping
Statement 4
Statement n
Program with non-linear control flow
Statement 1 • Possible control flows:
false
boolean 1
• 1,2,4,5,6,4,5,6,7
Statement 2
true
Statement 3
Statement 4 true
false
Statement 5 boolean 1
Statement 6
Statement 7
Program with non-linear control flow
Statement 1 • Possible control flows:
false
boolean 1
• 1,2,4,5,6,4,5,6,7
Statement 2
• 1,3,4,5,6,7
true
Statement 3
Statement 4 true
false
Statement 5 boolean 1
Statement 6
Statement 7
Program with non-linear control flow
Statement 1 • Possible control flows:
false
boolean 1
• 1,2,4,5,6,4,5,6,7
Statement 2
• 1,3,4,5,6,7
true • etc
Statement 3
Statement 4 true
false
Statement 5 boolean 1
Statement 6
Statement 7
if statement true false
bool_expr
• Syntax:
statement
if (bool_expr)
statement;
if (bool_expr)
statement1;
true false
else bool_expr
statement2;
statement1 statement2
Example: computing the absolute value
• Solution
• If the value is negative, multiply by -1 true false
val < 0
• if value is non-negative, leave it
val = -val;
int val = Integer.parseInt(args[0]);
if (val < 0)
val = -val;
System.out.println(val);
Example: maximum of two integers
• Solution: true
a>b
false
• Say the integers are a and b
• if a > b, max is a max = a; max = b;
• Otherwise max is b
if (a > b)
max = a;
else
max = b;
Example: Simulating tossing a coin
• Solution: >java CoinToss
• Generate a random number, r, between 0 and 1 Tails
• If r >= 0.5 heads
• Otherwise tails >java CoinToss
Heads
public class CoinToss{
public static void main(String[] args){ >java CoinToss
double r = Math.random(); Tails
if ( r >= 0.5)
System.out.println("Heads"); >java CoinToss
else Tails
System.out.println("Tails");
} >
}
Blocks
• A sequence of statement enclosed in { }
• A block is treated as a single statement
• So, the statement in if-else can be a block!
Example: Sorting two integers
• Solution:
• Given two integers, a and b, in that order
• If a > b, swap their values
Example: Sorting two integers
public class TwoSort{
public static void main(String[] args){
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
if (a > b){// swap Block
{// swap
int temp = a;
int temp = a;
a = b;
a = b;
b = temp;
b = temp;
}
}
System.out.println(a + ", " + b);
}
}
Use if-else statement to check errors
public class DivErrorChk{
public static void main(String[] args){
double total = Double.parseDouble(args[0]);
int count = Integer.parseInt(args[1]);
System.out.println("Average = " + total/count);
}
}
>java DivErrorChk 32.3 0
Average = Infinity
>
Use if-else statement to check errors
public class DivErrorChk{
public static void main(String[] args){
double total = Double.parseDouble(args[0]);
int count = Integer.parseInt(args[1]);
if (count != 0)
System.out.println("Average = " + total);
else
System.out.println("Error. Division by 0");
}
}
Use if-else statement to check errors
public class DivErrorChk{
public static void main(String[] args){
double total = Double.parseDouble(args[0]);
int count = Integer.parseInt(args[1]);
>java DivErrorChk 32.3 0
if (count != 0)
Error. Division by 0
System.out.println("Average = " + total);
else
>java DivErrorChk 32.3 10
System.out.println("Error. Division by 0");
Average = 3.2299999999999995
}
}
>
The while loop
• Syntax: true
bool_expr
false
while (bool_exp) Normally a
statement; block
statement
1. Evaluate bool_exp
2. If true execute statement and go
back to 1.
3. If false, exit the loop and proceed with
the next statement
Example: Counting
• Problem: Write a program that count from 1 to n.
• Solution:
1. Initialize integer count to 0
2. While count < n
count = count + 1
print count
Example: Counting
public class Counting{
public static void main(String[] args){ true false
count < n
int n = Integer.parseInt(args[0]);
count = count +1;
int count = 0;
System.out.println(count);
while (count < n){
count = count + 1;
System.out.println(count);
}
}
}
Example: Counting
public class Counting{
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
>javac Counting.java
int count = 0;
>java Counting 5
while (count < n){ 1
count = count + 1; 2
System.out.println(count); 3
} 4
} 5
}
>
Example: Counting
public class Counting{
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
int count = 0; Get the value of count, add
1 to it and store the result
while (count < n){ back in count
count = count + 1;
System.out.println(count);
}
}
}
Example: Counting
public class Counting{
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
int count = 0;
Shorthand for count = count +1
– compound addition assignment
while (count < n){
count += 1;
System.out.println(count);
}
} In General x = x + expression
} can be written as x += expression
Example: Counting
public class Counting{
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
int count = 0;
Shorthand for count = count +1
– increment operator
while (count < n){
count++;
System.out.println(count);
}
}
}
Other compound assignments
Operation Name Meaning
x += expression Compound addition assignment x = x + expression
x -= expression Compound subtraction assignment x = x - expression
x *= expression Compound multiplication assignment x = x * expression
x /= expression Compound division assignment x = x / expression
Increment/Decrement Operators
Operation Name Meaning
x++ Increment x=x+1
X-- Decrement x=x-1
• Both have prefix and postfix variants
• Postfix: x++ - fetch the current value of x, use it in the expression before
finally increment x
• Prefix: ++x – first increment the value of x before using it in an expression
Increment/Decrement Operators
public class Increment{
public static void main(String[] args){
int val = 10;
System.out.println(val++); // postfix
System.out.println(val);
System.out.println(++val); // prefix
}
}
Increment/Decrement Operators
public class Increment{ >javac Increment.java
public static void main(String[] args){
int val = 10; >java Increment
System.out.println(val++); // postfix 10
System.out.println(val); 11
System.out.println(++val); // prefix 12
}
} >
Example: computing the first n powers of 2
public class PowersOfTwo{
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
int i = 0;
int val = 1; // 2 to the power 0
while (i <= n){
System.out.println(val);
i++;
val *=2; // val = val / 2
}
}
}
Example: computing the first n powers of 2
public class PowersOfTwo{ i val i < n
public static void main(String[] args){
0 1 true
int n = Integer.parseInt(args[0]);
int i = 0; 1 2 true
int val = 1; // 2 to the power 0 2 4 true
3 8 true
while (i <= n){
4 16 true
System.out.println(val);
i++; 5 32 true
val *=2; // val = val / 2 6 64 false
}
}
}
Example: computing the first n powers of 2
public class PowersOfTwo{
public static void main(String[] args){ >javac PowersOfTwo.java
int n = Integer.parseInt(args[0]);
int i = 0; >java PowersOfTwo 5
int val = 1; // 2 to the power 0 1
while (i <= n){
2
System.out.println(val); 4
i++; 8
val *=2; // val = val * 2 16
} 32
}
}
>
The for statement
Typically initializes an int Typically increments
• Syntax: the controlled variable
variable – the controlled
variable
for (initialization; condition; advancement)
statement; Initialization, condition
and advancement are all
optional!
Typically a compound
statement A boolean
expression
The for loop
initialization;
• Syntax:
for (initialization; condition; advancement)
statement; true false
condition
statement;
advancement
Every for loop has an equivalent while loop
Initialization
int i= 1; for(int i = 1; i < n; i++){
System.out.println(i);
while (i< n){ boolean expression
}
System.out.println(i);
i= i+ 1; Advancement (increment)
}
Example: Computing the sum of the first n
natural numbers
public class ArithmeticSum{ i sum
public static void main(String[] args){ 1 1
int n = Integer.parseInt(args[0]);
2 3
int sum = 0;
3 6
for (int i = 1; i <= n; i++) 4 10
sum+=i;
System.out.println(sum);
}
}
Example: computing factorial
public class Factorial{
public static void main(String[] args){ i product
int n = Integer.parseInt(args[0]); 1 1
long product = 1; 2 2
3 6
for (int i = 1; i <= n; i++)
product*=i; 4 24
System.out.println(product);
}
}
Nesting
• Any statement within a conditional or a loop may be another
conditional or loop
Example: nesting
While loop nested inside for
for (int t = 0; t < trials; t++){ loop
int cash = stake;
while (cash > 0 && cash < goal)
if (Math.random() < 0.5)
if-else nested inside while
cash++;
loop, which in turn is
else
nested within for loop
cash--;
if (cash == goal)
wins++;
if nested inside for
}
Example: computing grade letters
• 0 – 49: F
• 50 – 59: C
• 60 – 79: B
• 80 – 100: A
public class GradeLetter{
public static void main(String[] args){
int grade = Integer.parseInt(args[0]);
char letter = 'D';
if (grade >= 80)
letter = 'A';
else{
if (grade >= 60)
letter = 'B';
else{
if (grade >= 50)
letter = 'C';
else
letter = 'F';
}
}
System.out.println("Grade: " + grade + " -> " + letter);
}
}
>javac GradeLetter.java
>java GradeLetter 12
Grade: 12 -> F
>java GradeLetter 51
Grade: 51 -> C
>java GradeLetter 100
Grade: 100 -> A
>java GradeLetter 75
Grade: 75 -> B
>
public class GradeLetterB{
public static void main(String[] args){
int grade = Integer.parseInt(args[0]);
char letter = 'D';
if (grade >= 80) What is wrong with this
letter = 'A'; code?
if (grade >= 60)
letter = 'B';
consider case when grade == 90
if (grade >= 50)
letter = 'C';
else
letter = 'F';
All these evaluate to true. Therefore " + grade + " -> " + letter);
System.out.println("Grade:
} the final value of letter is 'C'
}
public class GradeLetterC{
public static void main(String[] args){
int grade = Integer.parseInt(args[0]);
char letter = 'D';
if (grade >= 80)
letter = 'A';
else if (grade >= 60)
letter = 'B';
else if (grade >= 50)
letter = 'C';
else
letter = 'F';
System.out.println("Grade: " + grade + " -> " + letter);
}
}
>javac GradeLetterC.java
>java GradeLetterC 90
Grade: 90 -> A
>java GradeLetterC 70
Grade: 70 -> B
>java GradeLetterC 60
Grade: 60 -> B
>java GradeLetterC 55
Grade: 55 -> C
>java GradeLetterC 27
Grade: 27 -> F
>
Example: gamblers ruin problem
• Game with 50% chance of winning – eg tossing a coin
• Bet K1000 per toss
• Heads wins you K1000
• Tails loses you K1000
• Starting with Kx,000, can you reach a target of Ky,000
• Two possible solutions
• Find closed-form solution
• Simulation Let’s try this
public class Gambler{
public static void main(String[] args){
int stake = Integer.parseInt(args[0]);
int goal = Integer.parseInt(args[1]);
int trials = Integer.parseInt(args[2]);
int wins = 0;
for (int t = 0; t < trials; t++){
int cash = stake;
while (cash > 0 && cash < goal){
if (Math.random() < 0.5)
cash +=1000;
else
cash -= 1000;
}
if (cash == goal) wins++;
}
System.out.println(wins + " wins of " + trials);
}
}