Lecture 03
Lecture 03
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;
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]);
>
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]);
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
statement;
advancement
Every for loop has an equivalent while loop
Initialization
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;
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';
>java GradeLetter 12
Grade: 12 -> F
>java GradeLetter 51
Grade: 51 -> C
>java GradeLetter 75
Grade: 75 -> B
>
public class GradeLetterB{
public static void main(String[] args){
int grade = Integer.parseInt(args[0]);
char letter = 'D';
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';
>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);
}
}