SlideShare a Scribd company logo
Slide 1 of
Lecture C
Lesson 3: Conditions and Loops
Unit 1: The if Statement
Slide 2 of
Lecture C
The if Statement
• The Java if statement has the following syntax:
if (boolean-condition)
statement;
• If the Boolean condition is true, the statement is
executed; if it is false, the statement is skipped
• This provides basic decision making capabilities
Slide 3 of
Lecture C
Tempreture
class Temperature {
static final int THRESHOLD = 65;
public static void main(String[] args) {
InputRequestor input = new InputRequestor();
int temperature =
input.requestInt(“Enter the temperature:”);
System.out.println(“Current temperature “+
temperature);
if (temperature < THRESHOLD)
System.out.println(“It’s cold in here!”);
}
}
Slide 4 of
Lecture C
If statement flow diagram
if (condition)
statement;
condition
statement
true
Slide 5 of
Lecture C
Boolean Expressions
• The condition of an if statement must evaluate to a true
or false result
• Java has several equality and relational operators:
• More complex Boolean expressions are also possible
Operator
Meaning
==
equal to
!=
not equal to
<
less than
<=
less than or equal to
>
greater than
>=
greater than or equal to
Slide 6 of
Lecture C
Block Statements
• Several statements can be grouped together into a block
statement
• Blocks are delimited by braces
• A block statement can be used wherever a statement is
called for in the Java syntax
if (boolean-condition){
statement1;
statement2;
…
}
Slide 7 of
Lecture C
Example - Temperature2
class Temperature2 {
static final int THRESHOLD = 65;
public static void main(String[] args) {
InputRequestor input = new InputRequestor();
int temperature =
input.requestInt(“Enter the temperature:”);
System.out.println(“Current temperature “+
temperature);
if (temperature < THRESHOLD) {
System.out.println(“It’s cold in here!”);
System.out.println(“But we’ll survive.”);
}
}
}
Slide 8 of
Lecture C
If .. Else Statement
• An else clause can be added to an if statement to
make it an if-else statement:
if (condition)
statement1;
else
statement2;
• If the condition is true, statement1 is executed; if the
condition is false, statement2 is executed
Slide 9 of
Lecture C
Example - Temperature3
class Temperature3 {
static final int FREEZING_POINT = 32;
public static void main(String[] args) {
InputRequestor input = new InputRequestor();
int temperature =
input.requestInt(“Enter temperature:”);
if (temperature <= FREEZING_POINT)
System.out.println(“It’s freezing!”);
else
System.out.println(“Above freezing.”);
}
}
Slide 10 of
Lecture C
If/else flow diagram
if (condition)
statement1;
else
statement2;
condition
statement2
true
statement1
Slide 11 of
Lecture C
Nested If statements
• Since an “If” statement is a statement, it can appear inside
another if statement.
if (condition1)
if (condition2)
statement;
• It can also appear in an “else” clause
if (condition1)
statement1;
else if (condition2)
statement2;
Slide 12 of
Lecture C
Nested If Example
// Reads 2 integers and compares them
class CompareExample {
public static void main(String[] args) {
InputRequestor input = new InputRequestor();
int a = input.requestInt(“First number:”);
int b = input.requestInt(“Second number:”);
if (a != b){
if (a > b)
System.out.println(a+” is greater”);
else
System.out.println(b+” is greater”);
}else
System.out.println(“the numbers are equal”);
}
}
Slide 13 of
Lecture C
Checking your Input
• When requesting input from the user, keep in mind that the input may be invalid.
• It is good practice to check the validity of user input
int numberOfItems =
input.requestInt(“Enter number of items:”);
if (numberOfItems < 0) {
System.out.println(
“Number of items must be positive!”);
} else {
double price = numberOfItems * ITEM_PRICE;
System.out.println(“The total price is:“ +price);
}
Slide 14 of
Lecture C
Lesson 3: Conditions and Loops
Unit 2: Boolean Expressions
Slide 15 of
Lecture C
Logical Operators
• Boolean expressions may be combined using logical
operators
• There are three logical operators in Java:
• They all take Boolean operands and produce Boolean
results
• Logical NOT is unary (one operand), but logical AND and
OR are binary (two operands)
Operator
Operation
!
Logical NOT
&&
Logical AND
||
Logical OR
Slide 16 of
Lecture C
Logical NOT
• The logical NOT is also called logical negation or logical
complement
• If a is true, !a is false; if a is false, then !a is true
• Logical expressions can be shown using truth tables
a
!a
false
true
true
false
Slide 17 of
Lecture C
Logical AND
• The expression a && b is true if both a and b are true,
and false otherwise
• Truth tables show all possible combinations of all terms
a
b
a && b
false
false
false
false
true
false
true
false
false
true
true
true
Slide 18 of
Lecture C
Logical OR
• The expression a || b is true if a or b or both are true,
and false otherwise
a
b
a || b
false
false
false
false
true
true
true
false
true
true
true
true
Slide 19 of
Lecture C
Logical Operators
• Logical operators are used to form more complex logical
expressions
• Logical operators have precedence relationships between
themselves and other operators
if (a<1 || a%2!=0)
System.out.println(
“The input should be an even even number!”);
Slide 20 of
Lecture C
Logical Operators
• Full expressions can be evaluated using truth tables
a < 1
a%2!=0
a<1 || a%2=0
false
false
false
false
true
false
true
false
false
true
true
true
Slide 21 of
Lecture C
Boolean variables
• Boolean expressions can be assigned to Boolean
variables
• Boolean variables are Boolean expressions
boolean b, c;
b = (x > 17);
c = (x>17) && (x<60);
boolean b, c;
b = (x > 17);
c = b && (x<60);
if (c)
System.out.println(“x is in range”);
Slide 22 of
Lecture C
Example - RightTriangle
// Receives the length of the edges of a triangle
// and determine if this is a right triangle
class RightTriangle {
public static void main(String[] args) {
InputRequestor input = new InputRequestor();
float a = input.requestInt(“Edge1:”);
float b = input.requestInt(“Edge2:”);
float c = input.requestInt(“Hypotenuse:”);
boolean test = a*a+b*b == c*c;
if (test)
System.out.println(“It’s a right triangle”);
else
System.out.println(“It’s not a right triangle”);
}
}
Slide 23 of
Lecture C
Lesson 3: conditions and loops
Unit C3: The while Statement
Slide 24 of
Lecture C
The while statement
• A while statement has the following syntax:
while (condition)
statement;
• If the condition is true, the statement is executed; then
the condition is evaluated again
• The statement is executed over and over until the
condition becomes false
• If the condition of a while statement is false initially, the
statement is never executed
• Therefore, we say that a while statement executes zero
or more times
Slide 25 of
Lecture C
While statement flow diagram
while (condition)
statement;
condition
statement
true
Slide 26 of
Lecture C
Example - Counter
// Counts from 1 to 5
class Counter {
static final int LIMIT = 5;
public static void main(String[] args) {
int count = 1;
while (count <= LIMIT) {
System.out.println(count);
count = count + 1;
}
System.out.println(“done”);
}
}
Slide 27 of
Lecture C
Examples - Factors
// Gets an integer and prints its factors
class FactorsExample {
public static void main(String[] args) {
InputRequestor input = new InputRequestor();
int a = input.requestInt(“Enter a number:”);
int i = 1;
System.out.println(“The divisors of “+a+” are:”);
while (i <= a) {
if (a%i == 0) {
System.out.println(i);
}
i = i + 1;
}
}
}
Slide 28 of
Lecture C
Infinite Loops
• The body of a while loop must eventually make the
condition false
• If not, it is an infinite loop, which will execute until the user
interrupts the program
• This is a common type of logical error -- always double
check that your loops will terminate normally
Slide 29 of
Lecture C
Example - Forever
// This program contains an infinite loop
class Forever {
static final int LIMIT = 25;
public static void main(String[] args) {
int count = 1;
while (count <= LIMIT) {
System.out.println(count);
count = count - 1;
}
}
}
Slide 30 of
Lecture C
Lesson 3: conditions and loops
Unit 4: More conditionals
Slide 31 of
Lecture C
The Conditional Operator
• Java has a conditional operator that evaluates a Boolean
condition that determines which of two expressions is
evaluated
• The result of the chosen expression is the result of the
entire conditional operator
• Its syntax is:
condition ? expression1 :
expression2
• If the condition is true, expression1 is evaluated; if it is
false, expression2 is evaluated
Slide 32 of
Lecture C
The Conditional Operator
• It is similar to an if-else statement, except that it is an
expression that returns a value
• For example:
• If a is greater that b, then a is assigned to max;
otherwise, b is assigned to max
• The conditional operator is ternary, meaning it requires
three operands
int max = (a > b) ? a : b;
Slide 33 of
Lecture C
The Conditional Operator
• Another example:
• If count equals 1, "Dime" is printed, otherwise
"Dimes" is printed
System.out.println ("Your change is " + count +
((count == 1) ? "Dime" : "Dimes”));
Slide 34 of
Lecture C
Another Selection Statement
• The if and the if-else statements are selection
statements, allowing us to select which statement to
perform next based on some Boolean condition
• Another selection construct, called the switch statement,
provides another way to choose the next action
• The switch statement evaluates an expression, then
attempts to match the result to one of a series of values
• Execution transfers to statement list associated with the
first value that matches
Slide 35 of
Lecture C
The switch Statement
• The syntax of the switch statement is:
switch (expression) {
case value1:
statement-list1
case value2:
statement-list2
case …
}
Slide 36 of
Lecture C
The switch Statement
• The expression must evaluate to an integral value, such
as an integer or character
• The break statement is usually used to terminate the
statement list of each case, which causes control to jump
to the end of the switch statement
• A default case can be added to the end of the list of
cases, and will execute if no other case matches
Slide 37 of
Lecture C
The switch Statement
/**
* A client that enables you to connect to the
* bank server and make remote banking operations...
*/
public class BankClient {
public static final int VIEW_BALANCE = 1;
public static final int VIEW_SAVINGS = 2;
public static final int CASH_TRANSFER = 3;
public static final int VIEW_LAST_OPERATIONS = 4;
// ...
Slide 38 of
Lecture C
The switch Statement
// Inside the main loop of the client:
int option =
InputRequestor.requentInt(“Enter your choice:”);
switch(option) {
case VIEW_BALANCE:
showBalance();
break;
case VIEW_SAVINGS:
showSavings();
break;
default:
output.showMessage(“No such option!”);
}
Slide 39 of
Lecture C
Lesson 3: conditions and loops
Unit 5: Shorthand Operators
Slide 40 of
Lecture C
Shorthand Operators
• Many operations are very commonly used
• Java has shorthand notations for these
 increment and decrement operators
 assignment operators
x = x + 1;
sum = sum + x;
Slide 41 of
Lecture C
The Increment and Decrement Operators
• The increment operator (++) adds one to its integer or
floating point operand
• The decrement operator (--) subtracts one
• The statement
is essentially equivalent to
count++;
count = count + 1;
Slide 42 of
Lecture C
The Increment and Decrement Operators
• The increment and decrement operators can be applied
in prefix (before the variable) or postfix (after the variable)
form
• When used alone in a statement, the prefix and postfix
forms are basically equivalent. That is,
is equivalent to
count++;
++count;
Slide 43 of
Lecture C
The Increment and Decrement Operators
• When used in a larger expression, the prefix and postfix
forms have a different effect
• In both cases the variable is incremented (decremented)
• But the value used in the larger expression depends on
the form
Expressions
Operation
Value Of expression
count++
add 1
old value
++count
add 1
new value
count--
subtract 1
old value
--count
subtract 1
new value
Slide 44 of
Lecture C
The Increment and Decrement Operators
• If count currently contains 45, then
assigns 45 to total and 46 to count
• If count currently contains 45, then
assigns the value 46 to both total and count
total = count++;
total = ++count;
Slide 45 of
Lecture C
The Increment and Decrement Operators
• If sum contains 25, what does this statement print?
• Prints the following result:
25 27 27 27
• sum contains 26 after the line is complete
System.out.println (sum++ + " " +
++sum + " " +
sum + " " +
sum--);
Slide 46 of
Lecture C
Assignment Operators
• Often we perform an operation on a variable, then store
the result back into that variable
• Java provides assignment operators that simplify that
process
• For example, the statement
is equivalent to
sum += value;
sum = sum + value;
Slide 47 of
Lecture C
Assignment Operators
• There are many such assignment operators, always
written as op= , such as:
Operator
Example
Equivalent to
+=
x+=y
x = x + y
-=
x-=y
x = x - y
*=
x*=y
x = x * y
/=
x/=y
x = x / y
%=
x%=y
x = x % y
Slide 48 of
Lecture C
Assignment Operators
• The right hand side of an assignment operator can be a
complete expression
• The entire right-hand expression is evaluated first, then
combined with the additional operation
• Therefore
result /= total-MIN;
is equivalent to
result /= total-MIN;
result = result / (total-MIN);
Slide 49 of
Lecture C
Lesson 3: conditions and loops
Unit C6: More Repetition
Slide 50 of
Lecture C
More Repetition Constructs
• In addition to while loops, Java has two other
constructs used to perform repetition:
 the do statement
 the for statement
• Each loop type has its own unique characteristics
• You must choose which loop type to use in each situation
Slide 51 of
Lecture C
The do Statement
• The do statement has the following syntax:
do
statement
while (condition);
• The statement is executed until the condition becomes
false
• It is similar to a while statement, except that its
termination condition is evaluated after the loop body
Slide 52 of
Lecture C
The do Statement
• The key difference between a do loop and a while loop
is that the body of the do loop will execute at least once
• If the condition of a while loop is false initially, the body
of the loop is never executed
• Another way to put this is that a while loop will execute
zero or more times and a do loop will execute one or
more times
Slide 53 of
Lecture C
Do Statement Example
// Gets an integer and prints its factors
class AvgExample {
public static void main(String[] args){
InputRequestor input = new InputRequestor();
double x, sum=0, count=-1;
do {
x = input.RequestDouble(“Next number:”);
sum += x;
count++;
} while (x != 0);
// 0 is a flag indicating end of input
System.out.println(“The average is “+sum/count);
}
}
Slide 54 of
Lecture C
The do Statement flow diagram
statement
condition
false
true
Slide 55 of
Lecture C
The for Statement
• Many loops have a common pattern, captured by the for
statement
• The syntax of the for loop is
for (intialization; condition; increment)
statement;
• This is equivalent to
initialization;
while (condition) {
statement;
increment;
}
Slide 56 of
Lecture C
The for Statement: examples
• Examples:
for (int count=1; count < 75; count++) {
System.out.println (count);
}
for (int num=1; num <= max; num = num * 2) {
System.out.println (“Next power of 2: “ + num);
}
Slide 57 of
Lecture C
The for Statement
• The initialization is always performed once
• The condition of a for statement is tested prior to
executing the loop body (like in the while statement)
• Therefore, a for loop will execute zero or more times
• For loops are well suited for cases where the number of
iterations is known beforehand
• The increment is executed after each iteration of the loop
Slide 58 of
Lecture C
Omitting parts in a for Statement
• Each expression in the header of a for loop is optional
 If the initialization is left out, no initialization is performed
 If the condition is left out, it is always considered to be true, and
therefore makes an infinite loop
 If the increment is left out, no increment operation is performed
• Both semi-colons are always required
for (;;) {// an infinite loop
System.out.println (“beep”);
}
// compute a value count
for (; count < max ; count ++ ) {
System.out.println (count);
}
Slide 59 of
Lecture C
The for Statement flow diagram
statement
condition
false
true
initialization
increment
Slide 60 of
Lecture C
Multiplication Table Example
class MultiplicationTable {
public static void main(String[] args){
for(int j=1 ; j <= 10 ; j++) {
for(int k=1 ; k <= 10 ; k++)
System.out.print(j*k);
System.out.println();
}
}
}
Slide 61 of
Lecture C
The break and continue statements
• The break statement, which we used with switch
statements, can also be used inside a loop
• When the break statement is executed, control jumps to
the statement after the loop (the condition is not
evaluated again)
• A similar construct, the continue statement, can also be
executed in a loop
• When the continue statement is executed, control
jumps to the end of the loop and the condition is
evaluated
Slide 62 of
Lecture C
Break and Continue Example
class AvgExample2 {
public static void main(String[] args){
InputRequestor in = new InputRequestor();
double x, sum = 0; count = 0;
while(true){
x = in.RequestDouble();
if (x == 0)
break;
if (x < 0) {
System.out.println(“Only positive numbers!”);
continue;
}
sum += x ;
count ++ ;
} // continued on next page
Slide 63 of
Lecture C
Break and Continue Example (2)
System.out.println(“The average is “+sum/count);
}
}
Slide 64 of
Lecture C
Why do We Need Indentation?
class Mystery {
public static void main(String[] args) {
InputRequestor in = new InputRequestor();
int dimension =
in.requestInt(“Please enter the dimension”);
for (int j = 0; j < dimension; j++) {
for (int k = 1; k < dimension - j; k++) {
System.out.print(" ");
}
for (int k = 0; k < j; k++) {
System.out.print("*");
}
System.out.println();
}}}

More Related Content

PPT
2621008 - C++ 2
PDF
Control statements anil
PPT
Java Programmin: Selections
PDF
PPTX
Basics of Control Statement in C Languages
PDF
Python Unit 3 - Control Flow and Functions
PDF
ICP - Lecture 7 and 8
PDF
controlflowwSoftware Development Fundamentals (SDF) – I ODD 2024 Jaypee Insti...
2621008 - C++ 2
Control statements anil
Java Programmin: Selections
Basics of Control Statement in C Languages
Python Unit 3 - Control Flow and Functions
ICP - Lecture 7 and 8
controlflowwSoftware Development Fundamentals (SDF) – I ODD 2024 Jaypee Insti...

Similar to Control structure and Looping statements (20)

PPT
Lecture 3
PDF
Python for Machine Learning
PDF
Conditional Statements
PPT
Control structures in C++ Programming Language
PPS
02 iec t1_s1_oo_ps_session_02
PDF
csj-161127083146power point presentation
PPTX
CH-4 (1).pptx
PPTX
Control and conditional statements
PPTX
Control Statements in Java
PPTX
Control Structures.pptx
PPT
Visula C# Programming Lecture 3
PPT
PPTX
Ch5 Selection Statements
PPTX
05. Conditional Statements
PDF
PPTX
Control Structures in C
PPS
C programming session 02
PPTX
Control Flow Statements
Lecture 3
Python for Machine Learning
Conditional Statements
Control structures in C++ Programming Language
02 iec t1_s1_oo_ps_session_02
csj-161127083146power point presentation
CH-4 (1).pptx
Control and conditional statements
Control Statements in Java
Control Structures.pptx
Visula C# Programming Lecture 3
Ch5 Selection Statements
05. Conditional Statements
Control Structures in C
C programming session 02
Control Flow Statements
Ad

More from BalaKrishnan466 (15)

PPT
Switch and control statement for c language
PPT
c-Looping-Statements-P-Suman statement for c
PPT
Switch and control looping statement for C
PPT
Switch and looping statement for c language
PPT
C language Looping and conditional statement
PDF
Control structure and Looping statements
PPT
Control structure and Looping statements
PPT
Decision making in C(2020-2021) statements
PPT
C array and Initialisation and declaration
PPTX
Basic operators and it's types in c languages
PPTX
Queues operation using data structure in c
PPT
Stack operation in data structure in c language
PPTX
Flow chart and algorithm working progress
PPT
Algorithms and Flowchart usages in C laguage
PPT
Data types and it's usage in c languages
Switch and control statement for c language
c-Looping-Statements-P-Suman statement for c
Switch and control looping statement for C
Switch and looping statement for c language
C language Looping and conditional statement
Control structure and Looping statements
Control structure and Looping statements
Decision making in C(2020-2021) statements
C array and Initialisation and declaration
Basic operators and it's types in c languages
Queues operation using data structure in c
Stack operation in data structure in c language
Flow chart and algorithm working progress
Algorithms and Flowchart usages in C laguage
Data types and it's usage in c languages
Ad

Recently uploaded (20)

PPTX
master seminar digital applications in india
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Cell Types and Its function , kingdom of life
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PDF
Trump Administration's workforce development strategy
PDF
Weekly quiz Compilation Jan -July 25.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PDF
RMMM.pdf make it easy to upload and study
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
Anesthesia in Laparoscopic Surgery in India
master seminar digital applications in india
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Complications of Minimal Access Surgery at WLH
Cell Types and Its function , kingdom of life
Orientation - ARALprogram of Deped to the Parents.pptx
Trump Administration's workforce development strategy
Weekly quiz Compilation Jan -July 25.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Practical Manual AGRO-233 Principles and Practices of Natural Farming
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
RMMM.pdf make it easy to upload and study
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
Final Presentation General Medicine 03-08-2024.pptx
What if we spent less time fighting change, and more time building what’s rig...
Anesthesia in Laparoscopic Surgery in India

Control structure and Looping statements

  • 1. Slide 1 of Lecture C Lesson 3: Conditions and Loops Unit 1: The if Statement
  • 2. Slide 2 of Lecture C The if Statement • The Java if statement has the following syntax: if (boolean-condition) statement; • If the Boolean condition is true, the statement is executed; if it is false, the statement is skipped • This provides basic decision making capabilities
  • 3. Slide 3 of Lecture C Tempreture class Temperature { static final int THRESHOLD = 65; public static void main(String[] args) { InputRequestor input = new InputRequestor(); int temperature = input.requestInt(“Enter the temperature:”); System.out.println(“Current temperature “+ temperature); if (temperature < THRESHOLD) System.out.println(“It’s cold in here!”); } }
  • 4. Slide 4 of Lecture C If statement flow diagram if (condition) statement; condition statement true
  • 5. Slide 5 of Lecture C Boolean Expressions • The condition of an if statement must evaluate to a true or false result • Java has several equality and relational operators: • More complex Boolean expressions are also possible Operator Meaning == equal to != not equal to < less than <= less than or equal to > greater than >= greater than or equal to
  • 6. Slide 6 of Lecture C Block Statements • Several statements can be grouped together into a block statement • Blocks are delimited by braces • A block statement can be used wherever a statement is called for in the Java syntax if (boolean-condition){ statement1; statement2; … }
  • 7. Slide 7 of Lecture C Example - Temperature2 class Temperature2 { static final int THRESHOLD = 65; public static void main(String[] args) { InputRequestor input = new InputRequestor(); int temperature = input.requestInt(“Enter the temperature:”); System.out.println(“Current temperature “+ temperature); if (temperature < THRESHOLD) { System.out.println(“It’s cold in here!”); System.out.println(“But we’ll survive.”); } } }
  • 8. Slide 8 of Lecture C If .. Else Statement • An else clause can be added to an if statement to make it an if-else statement: if (condition) statement1; else statement2; • If the condition is true, statement1 is executed; if the condition is false, statement2 is executed
  • 9. Slide 9 of Lecture C Example - Temperature3 class Temperature3 { static final int FREEZING_POINT = 32; public static void main(String[] args) { InputRequestor input = new InputRequestor(); int temperature = input.requestInt(“Enter temperature:”); if (temperature <= FREEZING_POINT) System.out.println(“It’s freezing!”); else System.out.println(“Above freezing.”); } }
  • 10. Slide 10 of Lecture C If/else flow diagram if (condition) statement1; else statement2; condition statement2 true statement1
  • 11. Slide 11 of Lecture C Nested If statements • Since an “If” statement is a statement, it can appear inside another if statement. if (condition1) if (condition2) statement; • It can also appear in an “else” clause if (condition1) statement1; else if (condition2) statement2;
  • 12. Slide 12 of Lecture C Nested If Example // Reads 2 integers and compares them class CompareExample { public static void main(String[] args) { InputRequestor input = new InputRequestor(); int a = input.requestInt(“First number:”); int b = input.requestInt(“Second number:”); if (a != b){ if (a > b) System.out.println(a+” is greater”); else System.out.println(b+” is greater”); }else System.out.println(“the numbers are equal”); } }
  • 13. Slide 13 of Lecture C Checking your Input • When requesting input from the user, keep in mind that the input may be invalid. • It is good practice to check the validity of user input int numberOfItems = input.requestInt(“Enter number of items:”); if (numberOfItems < 0) { System.out.println( “Number of items must be positive!”); } else { double price = numberOfItems * ITEM_PRICE; System.out.println(“The total price is:“ +price); }
  • 14. Slide 14 of Lecture C Lesson 3: Conditions and Loops Unit 2: Boolean Expressions
  • 15. Slide 15 of Lecture C Logical Operators • Boolean expressions may be combined using logical operators • There are three logical operators in Java: • They all take Boolean operands and produce Boolean results • Logical NOT is unary (one operand), but logical AND and OR are binary (two operands) Operator Operation ! Logical NOT && Logical AND || Logical OR
  • 16. Slide 16 of Lecture C Logical NOT • The logical NOT is also called logical negation or logical complement • If a is true, !a is false; if a is false, then !a is true • Logical expressions can be shown using truth tables a !a false true true false
  • 17. Slide 17 of Lecture C Logical AND • The expression a && b is true if both a and b are true, and false otherwise • Truth tables show all possible combinations of all terms a b a && b false false false false true false true false false true true true
  • 18. Slide 18 of Lecture C Logical OR • The expression a || b is true if a or b or both are true, and false otherwise a b a || b false false false false true true true false true true true true
  • 19. Slide 19 of Lecture C Logical Operators • Logical operators are used to form more complex logical expressions • Logical operators have precedence relationships between themselves and other operators if (a<1 || a%2!=0) System.out.println( “The input should be an even even number!”);
  • 20. Slide 20 of Lecture C Logical Operators • Full expressions can be evaluated using truth tables a < 1 a%2!=0 a<1 || a%2=0 false false false false true false true false false true true true
  • 21. Slide 21 of Lecture C Boolean variables • Boolean expressions can be assigned to Boolean variables • Boolean variables are Boolean expressions boolean b, c; b = (x > 17); c = (x>17) && (x<60); boolean b, c; b = (x > 17); c = b && (x<60); if (c) System.out.println(“x is in range”);
  • 22. Slide 22 of Lecture C Example - RightTriangle // Receives the length of the edges of a triangle // and determine if this is a right triangle class RightTriangle { public static void main(String[] args) { InputRequestor input = new InputRequestor(); float a = input.requestInt(“Edge1:”); float b = input.requestInt(“Edge2:”); float c = input.requestInt(“Hypotenuse:”); boolean test = a*a+b*b == c*c; if (test) System.out.println(“It’s a right triangle”); else System.out.println(“It’s not a right triangle”); } }
  • 23. Slide 23 of Lecture C Lesson 3: conditions and loops Unit C3: The while Statement
  • 24. Slide 24 of Lecture C The while statement • A while statement has the following syntax: while (condition) statement; • If the condition is true, the statement is executed; then the condition is evaluated again • The statement is executed over and over until the condition becomes false • If the condition of a while statement is false initially, the statement is never executed • Therefore, we say that a while statement executes zero or more times
  • 25. Slide 25 of Lecture C While statement flow diagram while (condition) statement; condition statement true
  • 26. Slide 26 of Lecture C Example - Counter // Counts from 1 to 5 class Counter { static final int LIMIT = 5; public static void main(String[] args) { int count = 1; while (count <= LIMIT) { System.out.println(count); count = count + 1; } System.out.println(“done”); } }
  • 27. Slide 27 of Lecture C Examples - Factors // Gets an integer and prints its factors class FactorsExample { public static void main(String[] args) { InputRequestor input = new InputRequestor(); int a = input.requestInt(“Enter a number:”); int i = 1; System.out.println(“The divisors of “+a+” are:”); while (i <= a) { if (a%i == 0) { System.out.println(i); } i = i + 1; } } }
  • 28. Slide 28 of Lecture C Infinite Loops • The body of a while loop must eventually make the condition false • If not, it is an infinite loop, which will execute until the user interrupts the program • This is a common type of logical error -- always double check that your loops will terminate normally
  • 29. Slide 29 of Lecture C Example - Forever // This program contains an infinite loop class Forever { static final int LIMIT = 25; public static void main(String[] args) { int count = 1; while (count <= LIMIT) { System.out.println(count); count = count - 1; } } }
  • 30. Slide 30 of Lecture C Lesson 3: conditions and loops Unit 4: More conditionals
  • 31. Slide 31 of Lecture C The Conditional Operator • Java has a conditional operator that evaluates a Boolean condition that determines which of two expressions is evaluated • The result of the chosen expression is the result of the entire conditional operator • Its syntax is: condition ? expression1 : expression2 • If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated
  • 32. Slide 32 of Lecture C The Conditional Operator • It is similar to an if-else statement, except that it is an expression that returns a value • For example: • If a is greater that b, then a is assigned to max; otherwise, b is assigned to max • The conditional operator is ternary, meaning it requires three operands int max = (a > b) ? a : b;
  • 33. Slide 33 of Lecture C The Conditional Operator • Another example: • If count equals 1, "Dime" is printed, otherwise "Dimes" is printed System.out.println ("Your change is " + count + ((count == 1) ? "Dime" : "Dimes”));
  • 34. Slide 34 of Lecture C Another Selection Statement • The if and the if-else statements are selection statements, allowing us to select which statement to perform next based on some Boolean condition • Another selection construct, called the switch statement, provides another way to choose the next action • The switch statement evaluates an expression, then attempts to match the result to one of a series of values • Execution transfers to statement list associated with the first value that matches
  • 35. Slide 35 of Lecture C The switch Statement • The syntax of the switch statement is: switch (expression) { case value1: statement-list1 case value2: statement-list2 case … }
  • 36. Slide 36 of Lecture C The switch Statement • The expression must evaluate to an integral value, such as an integer or character • The break statement is usually used to terminate the statement list of each case, which causes control to jump to the end of the switch statement • A default case can be added to the end of the list of cases, and will execute if no other case matches
  • 37. Slide 37 of Lecture C The switch Statement /** * A client that enables you to connect to the * bank server and make remote banking operations... */ public class BankClient { public static final int VIEW_BALANCE = 1; public static final int VIEW_SAVINGS = 2; public static final int CASH_TRANSFER = 3; public static final int VIEW_LAST_OPERATIONS = 4; // ...
  • 38. Slide 38 of Lecture C The switch Statement // Inside the main loop of the client: int option = InputRequestor.requentInt(“Enter your choice:”); switch(option) { case VIEW_BALANCE: showBalance(); break; case VIEW_SAVINGS: showSavings(); break; default: output.showMessage(“No such option!”); }
  • 39. Slide 39 of Lecture C Lesson 3: conditions and loops Unit 5: Shorthand Operators
  • 40. Slide 40 of Lecture C Shorthand Operators • Many operations are very commonly used • Java has shorthand notations for these  increment and decrement operators  assignment operators x = x + 1; sum = sum + x;
  • 41. Slide 41 of Lecture C The Increment and Decrement Operators • The increment operator (++) adds one to its integer or floating point operand • The decrement operator (--) subtracts one • The statement is essentially equivalent to count++; count = count + 1;
  • 42. Slide 42 of Lecture C The Increment and Decrement Operators • The increment and decrement operators can be applied in prefix (before the variable) or postfix (after the variable) form • When used alone in a statement, the prefix and postfix forms are basically equivalent. That is, is equivalent to count++; ++count;
  • 43. Slide 43 of Lecture C The Increment and Decrement Operators • When used in a larger expression, the prefix and postfix forms have a different effect • In both cases the variable is incremented (decremented) • But the value used in the larger expression depends on the form Expressions Operation Value Of expression count++ add 1 old value ++count add 1 new value count-- subtract 1 old value --count subtract 1 new value
  • 44. Slide 44 of Lecture C The Increment and Decrement Operators • If count currently contains 45, then assigns 45 to total and 46 to count • If count currently contains 45, then assigns the value 46 to both total and count total = count++; total = ++count;
  • 45. Slide 45 of Lecture C The Increment and Decrement Operators • If sum contains 25, what does this statement print? • Prints the following result: 25 27 27 27 • sum contains 26 after the line is complete System.out.println (sum++ + " " + ++sum + " " + sum + " " + sum--);
  • 46. Slide 46 of Lecture C Assignment Operators • Often we perform an operation on a variable, then store the result back into that variable • Java provides assignment operators that simplify that process • For example, the statement is equivalent to sum += value; sum = sum + value;
  • 47. Slide 47 of Lecture C Assignment Operators • There are many such assignment operators, always written as op= , such as: Operator Example Equivalent to += x+=y x = x + y -= x-=y x = x - y *= x*=y x = x * y /= x/=y x = x / y %= x%=y x = x % y
  • 48. Slide 48 of Lecture C Assignment Operators • The right hand side of an assignment operator can be a complete expression • The entire right-hand expression is evaluated first, then combined with the additional operation • Therefore result /= total-MIN; is equivalent to result /= total-MIN; result = result / (total-MIN);
  • 49. Slide 49 of Lecture C Lesson 3: conditions and loops Unit C6: More Repetition
  • 50. Slide 50 of Lecture C More Repetition Constructs • In addition to while loops, Java has two other constructs used to perform repetition:  the do statement  the for statement • Each loop type has its own unique characteristics • You must choose which loop type to use in each situation
  • 51. Slide 51 of Lecture C The do Statement • The do statement has the following syntax: do statement while (condition); • The statement is executed until the condition becomes false • It is similar to a while statement, except that its termination condition is evaluated after the loop body
  • 52. Slide 52 of Lecture C The do Statement • The key difference between a do loop and a while loop is that the body of the do loop will execute at least once • If the condition of a while loop is false initially, the body of the loop is never executed • Another way to put this is that a while loop will execute zero or more times and a do loop will execute one or more times
  • 53. Slide 53 of Lecture C Do Statement Example // Gets an integer and prints its factors class AvgExample { public static void main(String[] args){ InputRequestor input = new InputRequestor(); double x, sum=0, count=-1; do { x = input.RequestDouble(“Next number:”); sum += x; count++; } while (x != 0); // 0 is a flag indicating end of input System.out.println(“The average is “+sum/count); } }
  • 54. Slide 54 of Lecture C The do Statement flow diagram statement condition false true
  • 55. Slide 55 of Lecture C The for Statement • Many loops have a common pattern, captured by the for statement • The syntax of the for loop is for (intialization; condition; increment) statement; • This is equivalent to initialization; while (condition) { statement; increment; }
  • 56. Slide 56 of Lecture C The for Statement: examples • Examples: for (int count=1; count < 75; count++) { System.out.println (count); } for (int num=1; num <= max; num = num * 2) { System.out.println (“Next power of 2: “ + num); }
  • 57. Slide 57 of Lecture C The for Statement • The initialization is always performed once • The condition of a for statement is tested prior to executing the loop body (like in the while statement) • Therefore, a for loop will execute zero or more times • For loops are well suited for cases where the number of iterations is known beforehand • The increment is executed after each iteration of the loop
  • 58. Slide 58 of Lecture C Omitting parts in a for Statement • Each expression in the header of a for loop is optional  If the initialization is left out, no initialization is performed  If the condition is left out, it is always considered to be true, and therefore makes an infinite loop  If the increment is left out, no increment operation is performed • Both semi-colons are always required for (;;) {// an infinite loop System.out.println (“beep”); } // compute a value count for (; count < max ; count ++ ) { System.out.println (count); }
  • 59. Slide 59 of Lecture C The for Statement flow diagram statement condition false true initialization increment
  • 60. Slide 60 of Lecture C Multiplication Table Example class MultiplicationTable { public static void main(String[] args){ for(int j=1 ; j <= 10 ; j++) { for(int k=1 ; k <= 10 ; k++) System.out.print(j*k); System.out.println(); } } }
  • 61. Slide 61 of Lecture C The break and continue statements • The break statement, which we used with switch statements, can also be used inside a loop • When the break statement is executed, control jumps to the statement after the loop (the condition is not evaluated again) • A similar construct, the continue statement, can also be executed in a loop • When the continue statement is executed, control jumps to the end of the loop and the condition is evaluated
  • 62. Slide 62 of Lecture C Break and Continue Example class AvgExample2 { public static void main(String[] args){ InputRequestor in = new InputRequestor(); double x, sum = 0; count = 0; while(true){ x = in.RequestDouble(); if (x == 0) break; if (x < 0) { System.out.println(“Only positive numbers!”); continue; } sum += x ; count ++ ; } // continued on next page
  • 63. Slide 63 of Lecture C Break and Continue Example (2) System.out.println(“The average is “+sum/count); } }
  • 64. Slide 64 of Lecture C Why do We Need Indentation? class Mystery { public static void main(String[] args) { InputRequestor in = new InputRequestor(); int dimension = in.requestInt(“Please enter the dimension”); for (int j = 0; j < dimension; j++) { for (int k = 1; k < dimension - j; k++) { System.out.print(" "); } for (int k = 0; k < j; k++) { System.out.print("*"); } System.out.println(); }}}