Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views34 pages

(Lesson 3) Conditional Statements

The document provides an overview of conditional statements in programming, specifically focusing on the use of if..else and switch..case statements in Java. It explains the syntax and logic behind these statements, including examples for various scenarios such as determining if a number is positive or negative, calculating grades based on GPA, and handling user input for different conditions. Additionally, it covers the use of logical operators and the structure of nested if statements.

Uploaded by

sskx55nchb
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)
8 views34 pages

(Lesson 3) Conditional Statements

The document provides an overview of conditional statements in programming, specifically focusing on the use of if..else and switch..case statements in Java. It explains the syntax and logic behind these statements, including examples for various scenarios such as determining if a number is positive or negative, calculating grades based on GPA, and handling user input for different conditions. Additionally, it covers the use of logical operators and the structure of nested if statements.

Uploaded by

sskx55nchb
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/ 34

Conditional Statements

Dr. Ali Allam Introduction to Programming (BIS227E)


Conditional Statements:
using if..else
Conditional Statements

 Conditional statements are used to select a choice or take a decision


upon a given condition.
 IF statements are based on a condition whose result is either true or
false.
 This condition statement simply compares two values to each other.
 The main logical operators used to compare values are:
> >= < <= == !=
Greater than Greater than Less than Less than or Equals Not equal to
or equals equals
Overview on Conditional Statements

 The two values compared to each other can be either a variable,


an expression, or a constant.
Example Operands used in comparison Explanation
X>0 Variable and Constant Check if X is greater than 0
Y <= X Variable and Variable Check if Y is less than or equal to X
X == Z*10 Variable and Expression Check if X is equal to Z*10
60 != A+B*2 Constant and Expression Check if A+B*2 is not equal to 60
A%B < Y – X Expression and Expression Check if A%B is less than Y – X
Overview on Conditional Statements

 In some cases, you may need to write an IF statement having more


than one condition.
 Multiple conditions are made using either:
 condition1 && condition2 → AND
 condition1 || condition2 → OR
IF Statements: Java Syntax

In short, Java has the three following kinds of IF statements:


1. if statement (without else): executes some statement(s) if one condition is
true.
2. if..else statement: executes some statement(s) if a condition is true, and
executes other else statement(s) if that condition is false.
3. if..else if statement: executes different statement(s) for more than two
conditions.
Conditional Statements: if
1. if statement (without else): executes statement(s) if the condition is true.
if (condition)
{
Syntax
statement(s) executed if condition is true;
}
int mark = Integer.parseInt(JOptionPane.showInputDialog("Enter a number:"));
Example if (mark == 100)
JOptionPane.showMessageDialog(null, "You got the full mark");
Very Important Notes:
 The if (condition) is NEVER followed by a semi-colon.
 The curly brackets { } that follow the if condition, are mandatory if there is more
than one statement to be executed. These curly brackets are optional and can be
omitted in case there is only one single statement to be executed.
Conditional Statements: if/else
2. (if..else) statement: executes some statement(s) if a condition is true, and
other else statement(s) are executed if that condition is false.
if (condition) { Note:
statement(s) executed if the condition is true; } Curly brackets are
else { mandatory in this
statement(s) executed if the condition was false; } example because
there are two
float mark = Float.parseFloat(JOptionPane.showInputDialog("Enter a number:")); print statements to
if (mark >= 50) { be executed. So,
System.out.println("Your mark is " + mark); this block of
System.out.println("You passed."); } statements are
else { included in
System.out.println("Your mark is “ + mark); between the curly
System.out.println("You failed."); } brackets.
Conditional Statements: if/else if
3. (if..else if) statement: specifies a new condition to test, if the first condition is false.
if (condition1) {
statement(s) executed if condition1 is true; }
else if (condition2) {
Syntax
statement(s) executed if condition1 was false but condition2 is true; }
else {
statement(s) executed if all previous conditions were false; }
double x = Double.parseDouble(JOptionPane.showInputDialog("Enter a number:"));
if (x > 0)
System.out.println(x+" is a positive number");
Example else if (x < 0)
System.out.println(x+" is a negative number");
else
System.out.println(x+" is a neutral number");
Example (1): Decide whether a number is positive,
negative, or zero (three choices/options)
import javax.swing.*;
public class Prog1
{
public static void main(String[ ] args)
{
double x = Double.parseDouble(JOptionPane.showInputDialog("Enter a number:"));
if (x > 0)
JOptionPane.showMessageDialog(null, x + " is a positive number");
else if (x < 0)
JOptionPane.showMessageDialog(null, x + " is a negative number");
else
JOptionPane.showMessageDialog(null, x + " is a neutral number");
}
}
Example (1): Decide whether a number is positive,
negative, or zero (three choices/options)
 What would the Java program print in the following cases:
If the user inputs 0.5 If the user inputs -6.2 If the user inputs 0
Example (2): Decide whether a number is either
even or odd (two choices/options)

import javax.swing.*;
public class Prog2
{
public static void main(String[ ] args)
{
int x = Integer.parseInt(JOptionPane.showInputDialog("Enter a number:"));
if (x%2==0)
JOptionPane.showMessageDialog(null, x + " is an even number");
else
JOptionPane.showMessageDialog(null, x + " is an odd number");
}
}
Example (2): Decide whether a number is either
even or odd (two choices/options)
 What would the Java program print in the following cases:

If the user inputs 5

If the user inputs 12


Example (3): Get the maximum value of two
numbers
import javax.swing.*;
public class Prog3
{
public static void main(String[ ] args)
{
int x = Integer.parseInt(JOptionPane.showInputDialog("Enter the first number:"));
int y = Integer.parseInt(JOptionPane.showInputDialog("Enter another number:"));
if (x > y)
JOptionPane.showMessageDialog(null, "The maximum is " + x);
else if (y > x)
JOptionPane.showMessageDialog(null, "The maximum is " + y);
else
JOptionPane.showMessageDialog(null, "The two numbers are equal to " + x);
}
}
Example (3): Get the maximum value of two
numbers
Example (4): Print the corresponding grade of the
GPA entered by the user

Input: GPA Output: Corresponding Grade


3.5 – 4.0 Excellent
3 – 3.49 Very Good
2.5 – 2.99 Good
2.0 – 2.49 Pass
0.0 – 1.99 Fail
Otherwise Invalid GPA
import javax.swing.*;
public class Prog4
{
public static void main(String[ ] args)
{
double x = Double.parseDouble(JOptionPane.showInputDialog("Enter your GPA:"));
if (x>=3.5 && x<=4.0)
JOptionPane.showMessageDialog(null, "Excellent");
else if (x>=3 && x<3.5)
JOptionPane.showMessageDialog(null, "Very Good");
else if (x>=2.5 && x<3)
JOptionPane.showMessageDialog(null, "Good");
else if (x>=2.0 && x<2.5)
JOptionPane.showMessageDialog(null, "Pass");
else if (x>=0 && x<2)
JOptionPane.showMessageDialog(null, "Fail");
else
JOptionPane.showMessageDialog(null, "Invalid GPA");
}
}
Example (5): Print the corresponding season of the
month entered by the user

Input: month Output: Season


3, 4, 5 Spring
6, 7, 8 Summer
9, 10, 11 Autumn
12, 1, 2 Winter
Otherwise Invalid month
import javax.swing.*;
public class Prog5
{
public static void main(String[ ] args)
{
int m = Integer.parseInt(JOptionPane.showInputDialog("Enter the month number: "));
if(m>=3 && m<=5)
JOptionPane.showMessageDialog(null, "It's Spring!");
else if(m>=6 && m<=8)
JOptionPane.showMessageDialog(null, "It's Summer!");
else if(m>=9 && m<=11)
JOptionPane.showMessageDialog(null, "It's Autumn!");
else if(m==12 || m==1 || m==2)
JOptionPane.showMessageDialog(null, "It's Winter!");
else
JOptionPane.showMessageDialog(null, "Invalid Month!");
}
}
Example (6): Print the net salary after deducting
the taxes, according to the income

Input: basic salary Taxes


Salary < 2000 No Taxes
2000  Salary < 6000 Deduct 5%
Salary  6000 Deduct 10%
import javax.swing.*;
public class Prog6 {
public static void main(String[] args) {
int salary = Integer.parseInt(JOptionPane.showInputDialog("Enter your salary:"));
double net;
double tax;
if (salary<=2000)
net = salary;
else if(salary>2000 && salary<=6000) {
tax = salary * 0.05;
net = salary - tax;
}
else {
tax = salary * 0.1;
net = salary - tax;
}
JOptionPane.showMessageDialog(null,"Basic Salary: "+salary+"\nNet Salary: "+net);
}
}
Example (7): Calculate the total charge of an
online order based on the address (nested-if)
 Calculate the total to charge for an order from an online store in Egypt
 Ask the user what country they are from and their order total
 If the order is from inside of Egypt, ask which governate
 If the order is from outside of Egypt, the user is charged 500 pounds
delivery fees with no charged taxes.
 If the order was placed in Egypt the user is charged 14% VAT (value-
added tax), and the delivery fee is based on the governate:
 Cairo or Giza → free delivery charges
 Suez or Ismaileya → charge 100 pounds
 All other governates → 200 pounds
 Tell the user the total cost including any taxes or delivery charges.
import javax.swing.*;
public class Prog7
{
public static void main(String [] args)
{
double price = Double.parseDouble ( JOptionPane.showInputDialog("Enter your order price: "));
String country = JOptionPane.showInputDialog("Enter your country: ");
double totalPrice;
if (country.equalsIgnoreCase("Egypt"))
{
String gov = JOptionPane.showInputDialog("Enter your governate:");
if (gov.equalsIgnoreCase("Cairo") || gov.equalsIgnoreCase("Giza") )
totalPrice = price + price * 0.14;
else if(gov.equalsIgnoreCase("Ismaileya") || gov.equalsIgnoreCase("Suez"))
totalPrice = price + price * 0.14 + 100;
else
totalPrice = price + price * 0.14 + 200;
}
else
totalPrice = price + 500;
JOptionPane.showMessageDialog(null,"Your order total charge is: " +totalPrice);
}
}
Conditional Statements:
using switch..case
Conditional Statements: switch-case

Instead of writing many if..else statements, you can use the switch..case
statement. The switch selects one of many code blocks to be executed:
switch(expression)
{
case val1: // when the expression matches the value val1
code block to be executed
break; //escape from the other following cases
Syntax case val2: // when the expression matches the value val2
code block to be executed
break; //escape from the other following cases
default: //the default case, when all previous cases do not match the expression
// code block to be executed
}
Conditional Statements: switch-case

 Explanation:
 The expression given in the switch statement is evaluated.
 The value of that expression is compared with the values of each
case.
 If there is a match, the associated block of code is executed.
 The break exits/escapes from the switch-case structure; this
prevents all the other cases from being executed.
 The default is the case that shall be executed when none of the
cases match the expression.
 The break and default keywords are optional.
Example (8): Print the name of the day for a
number entered by the user.

Input: Day number Output: Day name


1 Saturday
2 Sunday
3 Monday
4 Tuesday
5 Wednesday
6 Thursday
7 Friday
Otherwise Invalid Day
import javax.swing.*;
public class Prog8
{
public static void main(String[] args)
{
int day = Integer.parseInt(JOptionPane.showInputDialog("Enter the day number:"));
switch(day)
{
case 1: JOptionPane.showMessageDialog(null, "Saturday"); break;
case 2: JOptionPane.showMessageDialog(null, "Sunday"); break;
case 3: JOptionPane.showMessageDialog(null, "Monday"); break;
case 4: JOptionPane.showMessageDialog(null, "Tuesday"); break;
case 5: JOptionPane.showMessageDialog(null, "Wednesday"); break;
case 6: JOptionPane.showMessageDialog(null, "Thursday"); break;
case 7: JOptionPane.showMessageDialog(null, "Friday"); break;
default: JOptionPane.showMessageDialog(null, "Invalid Day");
}
}
}
Example (9): Decide whether the day is a weekday
or a weekend.

Input: Day number Output: Day name


1 Weekend
2 Weekday
3 Weekday
4 Weekday
5 Weekday
6 Weekday
7 Weekend
Otherwise Invalid Day
Example (9): Decide whether the day is a weekday
or a weekend.

import javax.swing.*;
public class Prog8
{
public static void main(String[] args)
{
int day = Integer.parseInt(JOptionPane.showInputDialog("Enter the day number:"));
switch(day)
{
case 1, 7: JOptionPane.showMessageDialog(null, "Weekend"); break;
case 2, 3, 4, 5, 6: JOptionPane.showMessageDialog(null, "Weekday"); break;
default: JOptionPane.showMessageDialog(null, "Invalid Day");
}
}
}
Example (10): Print the Grade equivalent to the
letter grade entered by the user.

Input: Letter Grade Output:


A+ , A , A- Excellent
B+ , B , B- Very Good
C+ , C , C- Good
D+ , D Satisfactory
F Fail
I Incomplete
U Ungraded
T Transferred
import javax.swing.*;
public class Prog10
{
public static void main(String[] args)
{
String grade = JOptionPane.showInputDialog("Enter your letter grade:");
switch(grade)
{
case "A+", "A", "A-": JOptionPane.showMessageDialog(null, "Excellent"); break;
case "B+", "B", "B-": JOptionPane.showMessageDialog(null, "Very Good"); break;
case "C+", "C", "C-": JOptionPane.showMessageDialog(null, "Good"); break;
case "D+", "D": JOptionPane.showMessageDialog(null, "Satisfactory"); break;
case "F": JOptionPane.showMessageDialog(null, "Fail"); break;
case "I": JOptionPane.showMessageDialog(null, "Incomplete"); break;
case "U": JOptionPane.showMessageDialog(null, "Ungraded"); break;
case "T": JOptionPane.showMessageDialog(null, "Transferred"); break;
default: JOptionPane.showMessageDialog(null, "Invalid Grade");
}
}
}
Example (11): Decide whether a number is either
even or odd (two choices/options)
import javax.swing.*;
public class Prog10
{
public static void main(String[] args)
{
int x = Integer.parseInt(JOptionPane.showInputDialog("Enter a number:"));
switch(x%2)
{
case 0: JOptionPane.showMessageDialog(null, x+" is an even number"); break;
case 1: JOptionPane.showMessageDialog(null, x+" is an odd number"); break;
}
}
}
Example (11): Decide whether a number is either
even or odd (two choices/options)
 What would the Java program print in the following cases:

If the user inputs 5

If the user inputs 12

You might also like