5 The If Statement
5 The If Statement
conditions
if (test) {
statement;
...
statement;
}
• Example:
double gpa = console.nextDouble();
if (gpa >= 2.0) { This is how the if condition looks
System.out.println("Application accepted."); in a flowchart, notice how it skips
} yes statement if it’s not true, and
continues on with the program
The if/else statement
Executes one block if a test is true, another if false
if (test) {
statement(s);
} else {
statement(s);
}
• Example:
double gpa = console.nextDouble();
if (gpa >= 2.0) {
System.out.println("Welcome to Mars University!");
} else { The else allows a second
System.out.println("Application denied."); statement to be execute if
} the Yes is not True, this is
where we see choice (this
or that)
Relational expressions
• if statements use logical tests.
• Example:
if (x > 0) {
System.out.println("Positive");
} else if (x < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
} Ifs with else ifs allows you
to check many tests. If
one is true it exits the if
Nested if/else/if Sometimes you want to
check if something is true
and have no default case,
• If it ends with else, exactly one path must be taken. no else needed then
• If it ends with if, the code might not execute any path.
if (test) {
statement(s);
} else if (test) {
statement(s);
} else if (test) {
statement(s);
}
• Example:
if (place == 1) {
System.out.println("Gold medal!");
} else if (place == 2) {
System.out.println("Silver medal!");
} else if (place == 3) {
System.out.println("Bronze medal.");
}
Path means statements to
Nested if structures be executed
• Whether you made the dean's list (GPA ≥ 3.8) or honor roll (3.5-3.8).
• (3) nested if / else if
4 87% - 94%
3+ 77% - 79%
3 73% - 76%
3- 70% - 72%
2 63% - 66%
2- 60% - 62%
1+ 57% - 59%
1 53% - 56%
1- 50% - 52%
R 0% - 49%
Example 2
• Write a program that will input 4 marks, calculate their average and
then tell you if you passed the semester or failed.
• *Hint you can use the flowchart/psuedocode you already created for
this from b4 (boom)
Example 3
• Write a program that gets 2 values from the user and then outputs
which is the bigger number of the two.
• *Hint you can use the flowchart/psuedocode you already created for
this from b4
Example 4
• Write a program that gets 3 inputs from the user (int numbers) and
then outputs the largest of the 3 numbers
• *Hint you can use the flowchart/psuedocode you already created for
this from b4
Example 4b
• Write a program that gets 3 inputs from the user (int numbers) and then
outputs the largest of the 3 numbers
• *Hint you can use the flowchart/psuedocode you already created for this
from b4
Without && and ||
Example 5
• Create the program (from your flowchart) to find the sum of first 50 natural numbers.
• Good Luck