CPG101 - Java Programming: Lesson 5: Program Flow
CPG101 - Java Programming: Lesson 5: Program Flow
Selection Statements
Based on the user input, decision making will take place. It involves choosing between two alternative courses of action. Java supports two kinds of selection statements
The if, if..else or nested if statement The switch statement
Selection Statements
The if structure
A single-alternate if as it only performs an action based on one alternative.
Selection Statements
The Nested if structure
An if within another if statement. Nested if statements are useful when two conditions must be met before some action is taken.
Iteration Statements
A structure that allows a block of statements to be executed repeatedly depending on the evaluation of the boolean expression. A loop that never ends is called a endless loop or infinite loop. A loop within a loop is called a nested loop. Java supports three kinds of iteration statements
The while loop The do..while loop The for loop
6
Iteration Statements
The while loop
Used to repeat a statement or block only if the condition is true.
Iteration Statements
The testing of the condition is placed differently
while loop test the condition first, then execute the body of statements. do.. while execute the body of statements before testing the condition.
Iteration Statements
The for loop Allows the statements in the loop body to be executed a specific number of times.
Programming Exercises
Write a Java program to capture the users name and age and display a message based on the following information: if age > 65 display retired if age is between 22 to 65 display working if age is between 7 to 21 display studying if age < 7 display playing The user will be prompted to enter another name and age. If the user decides not to enter another name, the program will terminate.
10
The End
11