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

Java-Conditionals-Loops-Emoon

KAIST Data Structure ppt

Uploaded by

[HA] Nights
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)
33 views

Java-Conditionals-Loops-Emoon

KAIST Data Structure ppt

Uploaded by

[HA] Nights
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/ 22

Basic building blocks

• Built-in types of data


• Conditionals and loops
• Functions objects
• OOP functions
• Data Abstraction
conditionals and loops

text I/O

built-in data types assignment statements

1
Building blocks of
Java
Conditionals and Loops
▪ The if Statement
▪ Loops: the while statement
▪ An alternative: the for loop
▪ Nesting
https://introcs.cs.princeton.edu/java/13flow/
2
Conditionals and Loops
Control flow
• The sequence of statements that are actually executed in a program.
• Conditionals and loops enable us to choreograph control flow.

true boolean 1
statement 1

false
statement 2 statement 1

boolean 2 true statement 2


statement 3

false

statement 4
statement 3

straight-line control flow control flow with conditionals and a loop


[ previous lecture ] [this lecture]
3

Robert Sedgewick | Kevin Wayne


The if statement
Execute certain statements depending on the values of certain variables.
• Evaluate a Boolean expression.
• If true, execute a statement.
• The else option: If false, execute a different statement.
if (<Boolean expression>) { <statements T> }
else { <statements F> }
Example: if (x < 0) x = -x; Example: if (x > y) max = x;
else max = y;

true x< 0? false true x>y? false

x = -x; max = x; max = y;

Replaces x with the absolute value of x Computes the maximum of x and y 4

Robert Sedgewick | Kevin Wayne


Example of if statement use:
simulate a coin flip

public class Flip {

public static void main(String[] args) {


//simulate a fair coin flip.
if(Math.random() < 0.5)
System.out.println("Heads");
else System.out.println("Tails");
Heads
}
Heads
}
Tails

Flip

Heads

Robert Sedgewick | Kevin Wayne elice>Week 1-2> Simulate a coin flip


Example of if statement use: 2-sort
Q. What does this program do?

import java.util.Scanner;

public class TwoSort {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int a;
int b; 100
a = input.nextInt(); 99
b//implement here.
= input.nextInt(); 99
100
if(b < a) {
a sequence of -20
int temp = a;
a = b; statements 30
b = temp; within the -20
} curly braces. 30
System.out.println(a);
System.out.println(b);
}
} A. Reads two integers at runtime, then prints them out in ascending order.
6

Robert Sedgewick | Kevin Wayne elice>Week 1-2> Sort two integers


Example of if statement use: error checks
import java.util.Scanner;

public class IntOpsCheck {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int a = input.nextInt();
int b = input.nextInt();

int sum = a + b;
int prod = a * b;
System.out.println(a + " + " + b + " = " + sum);
System.out.println(a + " * " + b + " = " + prod);

if(b==0) System.out.print("Division by zero.");


else { 5 0
int quot = a / b; 5 + 0 = 5
int rem = a % b; 5 * 0 = 0
System.out.println(a + " / " + b + " = " + quot); Division by zero.
System.out.println(a + " % " + b + " = " + rem);
System.out.println(a + " = " + quot + " * " + b + " + " + rem);
}
}
}

Good programming practice. Use conditionals to check for and avoid runtime errors. 7

Robert Sedgewick | Kevin Wayne elice>Week 1-2> Error check for int operations
if-elseif
The following program assigns a grade based on the value of a test score:
import java.util.Scanner; Testscore Grade
public class LetterGrade {
public static void main(String[] args) { >=90 A
Scanner input = new Scanner(System.in);
Double testscore = input.nextDouble(); >=80 B
char grade;
>=70 C
if (testscore >= 90) >=60 D
grade = 'A';
else if (testscore >= 80) < 60 F
grade = 'B';
//implement here.
else if (testscore >= 70)
grade = 'C';
96
else if (testscore >= 60) Grade = A
grade = 'D';
else
grade = 'F';

System.out.println("Grade = " + grade);


}
} 8

Robert Sedgewick | Kevin Wayne


https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
elice>Week 1-2> *Exercise: Test score
Building blocks of
Java
Conditionals and Loops
▪ The if Statement
▪ Loops: the while statement
▪ An alternative: the for loop
▪ Nesting

10

https://introcs.cs.princeton.edu/java/13flow/
The while loop
Execute certain statements repeatedly until certain conditions are met.
• Evaluate a booleanexpression. i = 0;
• If true, execute a sequence of statements.
• Repeat. v = 1;

i <= n ? false
Example:
int i = 0;
int v = 1; true

while (i <= n)
System.out.println(v);
{
System.out.println(v); i
= i + 1; i = i + 1;

v= 2 v;
} v=2 v;

Prints the powers of two from 2 0 to 2 n .


[stay tuned for a trace]
11

Robert Sedgewick | Kevin Wayne


Computing Powers of 2
Enter an integer of your interest to print a table of the powers of 2:
6
0 1
1 2
2 4
3 8
4 16
5 32
6 64

Print the powers of two from 2 0 to 2 n .

12

Robert Sedgewick | Kevin Wayne


Example of while loop use:
print powers of two
A trace is a table of variable values after each statement.
Import java.util.*; i power i <= n
public class PowersOfTwo {
0 1 true
public static void main(String[] args) {
System.out.println("Enter an integer of your 1 2 true
interest to print a table of the powers of 2:
"); 2 4 true
Scanner input = new Scanner(System.in);
int n = input.nextInt(); 3 8 true
int power = 1;
4 16 true
int i=0;
5 32 true
while(i<=n) {
System.out.println(i+" "+power); 6 64 true
power = power * 2; //Compute the next one
i = i+1; //increment the loop control counter. 7 128 false
}

}
n Loop termination value
}
i Loop control counter
power Current power of 2
Prints the powers of two from 2 0 to 2 n .
13

Robert Sedgewick | Kevin Wayne elice>Week 1-2> Powers of two


Pop quiz on while loop
Q. Anything wrong with the following code?

import java.util.Scanner;

public class PQWhile {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int i = 0;
int v = 1;

while (i <= n)
System.out.println(v);
i = i + 1;
v = 2 * v;
}
}

14

Robert Sedgewick | Kevin Wayne


while vs. do-while

A do-while loop is almost the same as a while loop except that the
loop-continuation condition is omitted the first time through the loop.
16

The statements
Robert Sedgewick within the do block are always executed at least once.
| Kevin Wayne
Building blocks of
Java
Conditionals and Loops
▪ The if Statement
▪ Loops: the while statement
▪ An alternative: the for loop
▪ Nesting

https://introcs.cs.princeton.edu/java/13flow/
17
The for loop
An alternative repetition structure. Why? Can provide code that is more
• Evaluate an initialization statement. compact and understandable.
• Evaluate a b o o l e a n expression.
• If true, execute a sequence of statements,
then execute an increment statement.
• Repeat.

Every for loop has an equivalent while loop:


int v = 1;
int i = 0;
while ( i <= n; )
{
System.out.println( i + " " + v );
v=2 v;
i++;
}

Prints the powers of two from 2 0 to 2 n 18

Robert Sedgewick | Kevin Wayne


Examples of for loop use
sum i
int sum = 0; 1 1
for (int i = 1; i <= N; i++)
3 2
sum += i; trace at end of loop for N = 4
6 3
System.out.println(sum);
10 4
Compute sum (1 + 2 + 3 + . . . + N)
product i

long product = 1; 1 1
for (int i = 1; i <= N; i++) 2 2
product = i; 6 3
System.out.println(product); 24 4

Compute N! = 1 * 2 * 3 * . . . * N k
2* Math.PI* k/N

0 0
1 1.57079632...
for (int k = 0; k <= N; k++)
2 3.14159265...
System.out.println(k + " " + 2* Math.PI* k/N);
3 4.71238898...
Print a table of function values 4 6.28318530...

int v = 1; 2
while (v <= N/2) 4
v = 2* v; 8
System.out.println(v); 16 trace at end of loop for N = 2 3
Print largest power of 2 less than or equal to N
19

Robert Sedgewick | Kevin Wayne


Example of for loop use:
subdivisions of a ruler
Create subdivisions of a ruler to 1/N inches.
• Initialize rulerto one space.
• For each value i from 1 to N:
sandwich i between two copies of ruler.
i ruler
1 " 1"
public class Ruler{ 2 "1 2 1 "
public static void main(String[] args){ 3 "1 2 1 3 1 2 1 "
Scanner input = new Scanner(System.in); 4 "1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 "
int N = input.nextInt();
End-of-loop trace
String ruler = " ";
for (int i = 1; i <= N; i++)
ruler = ruler + i + ruler; java Ruler 4
System.out.println(ruler); 121312141213121
}
}
100
Exception in thread "main"
java.lang.OutOfMemoryError: Java heap space

Note: Small program can produce huge amount of output.


2 1 0 0 − 1 integers in output (!)
20
24

Robert Sedgewick | Kevin Wayne elice>Week 1-2> Ruler using a loop


Building blocks of
Java
Conditionals and Loops
▪ The if Statement
▪ Loops: the while statement
▪ An alternative: the for loop
▪ Nesting

21

https://introcs.cs.princeton.edu/java/13flow/
Nesting conditionals and loops
Nesting
• Any “statement” within a conditional or loop
may itself be a conditional or a loop statement.
• Enables complex control flows.
• Adds to challenge of debugging.

• In particular, we can use one or more of if, 5


while, and for statements in the body of * * * * * 1
another statement to make compound * * * 2
statements. * * 3
• To emphasize the nesting, we use indentation * * * 4
in the program code. * * 5

Write the code that prints an n-by-n table


with an asterisk in row i and column j
if either i divides j or j divides i. 22

Robert Sedgewick | Kevin Wayne elice>Week 1-2> *Exercise: Divisor Pattern


Pop Quiz on nested if statements

Goal. Given income, calculate proper tax rate.

Q. Anything wrong with the following code?

import java.util.Scanner;

public class TaxRate {


public static void main(String[] args){
Scanner input = new Scanner(System.in);
double income = input.nextDouble(); income rate
double rate = 0.35;
0 – $47,450 22%
if (income < 47450) rate = 0.22; $47,450 – $114,649 25%
if (income < 114650) rate = 0.25;
if (income < 174700) rate = 0.28; $114,650 – $174,699 28%
if (income < 311950) rate = 0.33;
System.out.println(rate); $174,700 – $311,949 33%
}
} $311,950 + 35%
25

Robert Sedgewick | Kevin Wayne elice>Week 1-2> Tax rate


Switch statement
NameOfDay.java converts a day of the week (0 to 6) to the corresponding name
(Sunday to Saturday).

import java.util.Scanner; 5
public class NameOfDay {
Friday
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int day = input.nextInt();
switch (day) {
case 0: System.out.println("Sunday"); break;
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
default: System.out.println("invalid day"); break;
}
}
}
27

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Robert Sedgewick | Kevin Wayne
elice>Week 1-2> Name of day

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy