Introduction to Programming with Java, for Beginners - PowerPoint PPT Presentation

About This Presentation
Title:

Introduction to Programming with Java, for Beginners

Description:

An if statement is a 'flow control' control statement. It is also called a conditional, or a branch. We'll see several 'flavors' ... The infamous 'dangling else' ... – PowerPoint PPT presentation

Number of Views:2694
Avg rating:3.0/5.0
Slides: 10
Provided by: fernando8
Category:

less

Transcript and Presenter's Notes

Title: Introduction to Programming with Java, for Beginners


1
Introduction to Programmingwith Java, for
Beginners
  • Conditionals (if statements)

2
Conditionals (if statements)
  • An if statement is a flow control control
    statement
  • It is also called a conditional, or a branch
  • Well see several flavors
  • An if all by itself
  • An if with an else part
  • An if with an else if part
  • A cascading series of the above
  • First, well look at some examples then well
    look at
  • the syntax (grammar rule)

3
Examples of if statements
// assume x and max are ints if (x gt max) max x
boolean result // assume code here sets result to be true or false if (result true) // if (result) System.out.println(result is true.) else System.out.println(result is false.)
4
if statement
if (condition) statement
if (condition) statement(s)
  • If the condition is true, then the statement(s)
    will be executed.
  • Otherwise, they wont.

5
Example how to swap
int num1 40 int num2 20 // Let num1 store the smaller if (num1 gt num2) int temp 0 temp num1 num1 num2 num2 temp Heres how to swap the values of two variables by using a temporary variable. This is a common pattern used for swapping all kinds of data.
6
if-else statement
Example Syntax Explanation
int x 5 int y 10 int min -9999 if (x lt y) min x else min y if (condition) statement(s) else statements(s) If the condition is true, then the statement(s) in the if block are executed. Otherwise, if there is an else part, the statement(s) in it are executed.
7
Cascading if-else
Example
char userChoice // Ask user for input and store it in userChoice if (userChoice q) System.out.println(quitting.) else if (userChoice a) System.out.println(adding.) else if (userChoice s) System.out.println(saving.) else System.out.println(unrecognized choice.)
8
Nested if-statments
An if within an if Truth Table
if (condition1) if (condition2) statement(s) A else statement(s) B else statements(s) C What values must the conditions have in order for block A to run? B? C?
A B C
condition1 T
condition2
9
The infamous dangling else
Code Notes
if (condition 1) if (condition 2) statementA else statementB When is statementB executed? In other words, which if is the else paired with?
  • An else is paired with the last else-less if,
    regardless of spacing, unless dictate
    otherwise. A fix

if (condition 1) if (condition 2) statementA else statementB
Write a Comment
User Comments (0)
About PowerShow.com