SlideShare une entreprise Scribd logo
1  sur  18
Télécharger pour lire hors ligne
CIS 1403
Fundamentals of
Programming
Lab 4: Selection
1
Introduction
This lab discusses selections and provides examples of if statement, nested if, and
switch. It also covers logical operators and relational operators. It gives many
examples to help the student develop logical think and structure computer logic.
Skill-set
By completing this lab, the students will develop the following skills:
• Build accurate, simple and nested if statement
• Use appropriate logical and relational operators to solve
programming problems that require the use of selection
• Develop a user menu using a combination of a switch and
while loop
How to use this lab?
Follow the lab instruction in step by step and complete all exercises. Watch
the associated videos.
Modify the examples to and exercises to experiment with different scenarios
to solve a similar problem.
Click the QR code to access the videos and PowerPoint icon to access the
associated PowerPoints.
3
Why selection is needed?
In our life, we are required to make decision-based on certain conditions. For
example, if you are on the road and find the intersection, you decide to go right,
left or straight based on your destination and the fast or less traffic road.
In programming, there are situations when you need to apply a specific process
when a condition is true and another process when it is false.
The Java Language uses two essential commands to allow us to select what
process should be executed in case of one or more conditions are met. These
two commands are: if ... else and switch.
A simple if statement structure
Here is a simple structure of an if statement|:
If
(condition)
Process1
Process2
The rest of the
code
true
false
In the above structure, when the condition is met (true), the first process is
executed. When the condition is false, process 2 is executed. A process can be
one or more lines of call. You may also call another function/method as part of
your process or perform some calculations.
4
Building conditions
The condition involved comparing values. Here is a simple example:
Line 3 declares and initiates x as 100.
In line 4 we have the condition x>5, which can be read as
Is x more than 50?.
The answer in this case is true. X is 100, which is more than 50. Therefor the
program will go to line 5 and display
Change line 3 to be int x = 45; What output will you get in this case? Explain briefly
what has happened?
Exercise
5
Use of brackets if statement
• The condition should be included between two brackets of this type ( )
• An opened and closed braces { } should follow the condition. The process
that must be executed in case the condition is true should be included
between these two braces. See line 4 to line 6. When there is only one
line needed for the process, these two braces become optional.
• The same applies to the else block.
Indentation
Using consistent and appropriate indentation will improve the readability of
your code.
• In the above example, please note that line 4 is pushed to the right to
show that it is part of the process that will be executed when the condition
is met. The same for line 8.
• Also, lines from 3 to 9 are pushed/indented to right to show they are all
part of the main function.
Indentation is optional for Java Language. However, it is must for some other
languages including Python.
Here is another example:
6
The Relational Operators
When comparing two variables, you need to use a rational operator. All
programming languages use complete relationship operators. The table below
summarizes the relational operators available in the Java Language.
• It is important to note that to compare if two values are equal,
then you use == and not only =.
• A single = is used only to assign a value to the variable, == is used
to compare or check the value of a variable.
Also, note >= is correct by => is incorrect.
7
Exercise
What will be the result of this code and why?
Change x value in line 3 to 20. What will be the result and why?
If you need to check if y is true, then you need an if statement. See line 5 of
this code.
Line 5 is using the condition in line 4 to check the value of y. When y is true,
the message “Y is equal to 50.” is displayed, else “Y is NOT equal to 50.” is
displayed.
8
Logical Operators
When you have more than one condition, then you need to link them using
logical operators. We will use only 3 logical operators that are AND, OR,
and NOT.
Assume we have two conditions.
• If both conditions must be met, then we use and. The symbol for and is
&&
• If we need at least one of the two conditions to be met, then we use or.
The symbol for or ||
• If we want to reverse the logic, then we use logical not, The symbol is !
The operator (! logical not) has a limited use cases. Therefore, we will focus
on && and ||.
In the following table, assume boolean variables A holds true and variable
B holds false
9
An Example
Assume there is an insurance company that provides a rate of 3.5% for cars
with price value more than or equal 10,000 and model of 2015 or above.
Other cars have to pay 4.5% rate to be insured by this company.
Here is the code to solve this problem.
• Please focus on line 13. You will notice that we have used && to ensure
that both conditions are met to provide a 3.5% rate.
• If the answer is true, then line 14 is executed. For any car that does not
meet this condition, line 18 is executed.
• Line 20 is outside the if statement and executed after the calculation of
insurance value.
• You are expected to be familiar with the rest of the code.
10
Exercise
What is the output of this code and why?
Change line 4 to int y = 20; What is the output in this case any why?
11
Exercise
What is the output of this code and why?
Change line 4 to int y = 50; What is the output in this case any why?
12
Examine this code carefully. How many conditions do we have?
Line 7 requires that x to be more than 70 and either x<5 or y<40. If x is not
more than 10, the rest of the conditions are ignored.
What is the result of this code?
What will happen if you change x value in line 3 to 11?
13
Nested if statement
Condition
1
Condition
2Process 1
The rest of code
Process 2 Process 3
true
true
false
false
When you have an if statement inside another if statement, this is referred to as
nested if. Nested if is a very common in programming to deal with more complex
conditions. However, they are logical, easy to follow and implement. Here is an
example of nested if structure.
• Process 1 is executed when the result of condition1 is true. In this case,
condition2 is ignored.
• However, if the result of condition1 is false, condition2 is checked. If
condition 2 is true, process 2 is executed.
• If both condition1 and condition2 are false, then process 3 is executed.
14
An example - nested if statement
Examine this code. What do you think the result in this case?
• Given that x = 5 and y=30, the result of line 8 is false. Simply the
condition y<30 is not met as y=30 and not less than 30. In this case, the
execution is moved to line 11.
• The result of line 11 is also false, because y is not less than 5 or more
than or equal 35. Basically 3 is not less than 5 and 30 is not more than
or equal 35. None of these conditions is met
• The last option is line 16. The result is 3 * 5 = 150.
15
An exercise - nested if statement
Examine this code. What do you think the result in this case?
16
switch in Java
If you need to select between discrete values for example 1, 2, 3, 4, etc. Or “A”, “B”, “C”,
etc., then switch is a good option.
Here is an example that allow the user to enter a number and check:
• If the entered number is 1, then the message “You have entered 1” will be
displayed.
• If the number is 2 the message “You have enter 2” is displayed
• However, if user enters a different number apart of 1 and 2, the messaged “You
entered an invalid number” will be displayed.
The switch structure has 5 main components that are:
1. The switch command (line 8),
2. The switch parameter (in this example the variable option),
3. A case for every option (lines 9 and 12)
4. A default which is executed if the entered value is not one the option
(line 15).
5. It is important to have the keyword break at the end of each case
including the default option.
One of the common use cases of switch is creating user-menu.
17
switch and while
To create a user menu, you need include the switch inside a while loop as in
this example.
The while command in line 8 repeats all lines from 9 to 29 while the user did
not enter 3. As soon as the user enter 3 the program stops and the message
“This is the end.” is displayed.
18
1. Develop a Java program that reads an integer number and determines if the number entered is
'positive', 'negative', or 'zero' and outputs the result on the screen.
2. Develop a Java program that reads an integer number, determines if the number is odd or even
and outputs a message on the screen indicating the number is odd or even.
3. Develop a Java program that will accept marks in the range of 0 to 100 and will determine the
grade according to data given in the table below:
00 – 59 F
60 – 64 D
65 – 74 C
75 – 89 B
90 – 100 A
Your program should output an error message if the user enters a mark that is outside the range 0 –
100.
4. Write a Java program that will receive two integer numbers and display their sum, difference,
product, and quotient. The quotient (first integer divided by second integer) is only to be
performed if the second integer does not equal zero
5. A program is required to read a customer’s name, a purchase amount and a discount code. The
discount code will be one of the following:
A no discount (0%)
B small discount (3%)
C medium discount (12%)
D big discount (20%)
The program must then compute the discount amount and the sales total and then print the
customer’s name, purchase amount, discount amount and the total due.
6. Develop a program that asks the user about his grade and displays a message based on the grade
entered. The program should display “Excellent” for an A, “Very Good” for a B, “Good” for a C,
“Acceptable” for a D, and “Failed you have to repeat the course” for a F. The case of grade entered
should not matter. For example capital “A” or small “a” are similar.
7. UAE post office charges parcels per kilogram. If the parcel is 5 kilos or less it charges AED 10 per
kilogram. If the parcel is 10 kilos or less but greater than 5 kilos it charges AED 8 per kilogram. If the
parcel is more than 10 kilos it charges AED 5 per kilogram. Develop a program that asks the user to
enter the weight and displays the weight and charge on the screen.
Exercises

Contenu connexe

Tendances

03a control structures
03a   control structures03a   control structures
03a control structuresManzoor ALam
 
Decision statements in vb.net
Decision statements in vb.netDecision statements in vb.net
Decision statements in vb.netilakkiya
 
Operator Precedence and Associativity
Operator Precedence and AssociativityOperator Precedence and Associativity
Operator Precedence and AssociativityNicole Ynne Estabillo
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming LanguageAhmad Idrees
 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityAakash Singh
 
Object oriented programming16 boolean expressions and selection statements
Object oriented programming16 boolean expressions and selection statementsObject oriented programming16 boolean expressions and selection statements
Object oriented programming16 boolean expressions and selection statementsVaibhav Khanna
 
If and select statement
If and select statementIf and select statement
If and select statementRahul Sharma
 
Variable, constant, operators and control statement
Variable, constant, operators and control statementVariable, constant, operators and control statement
Variable, constant, operators and control statementEyelean xilef
 
Pairwise testing technique-Made easy
Pairwise testing technique-Made easyPairwise testing technique-Made easy
Pairwise testing technique-Made easySamee Ahmed Indikar
 
Data types and operators in vb
Data types and operators  in vbData types and operators  in vb
Data types and operators in vballdesign
 
Control structures i
Control structures i Control structures i
Control structures i Ahmad Idrees
 
Type conversion, precedence, associativity in c programming
Type conversion, precedence, associativity in c programmingType conversion, precedence, associativity in c programming
Type conversion, precedence, associativity in c programmingDhrumil Panchal
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
Aae oop xp_04
Aae oop xp_04Aae oop xp_04
Aae oop xp_04Niit Care
 

Tendances (20)

03a control structures
03a   control structures03a   control structures
03a control structures
 
Decision statements in vb.net
Decision statements in vb.netDecision statements in vb.net
Decision statements in vb.net
 
Operator Precedence and Associativity
Operator Precedence and AssociativityOperator Precedence and Associativity
Operator Precedence and Associativity
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and Associativity
 
Object oriented programming16 boolean expressions and selection statements
Object oriented programming16 boolean expressions and selection statementsObject oriented programming16 boolean expressions and selection statements
Object oriented programming16 boolean expressions and selection statements
 
If and select statement
If and select statementIf and select statement
If and select statement
 
Variable, constant, operators and control statement
Variable, constant, operators and control statementVariable, constant, operators and control statement
Variable, constant, operators and control statement
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Pairwise testing technique-Made easy
Pairwise testing technique-Made easyPairwise testing technique-Made easy
Pairwise testing technique-Made easy
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Data types and operators in vb
Data types and operators  in vbData types and operators  in vb
Data types and operators in vb
 
Control structures i
Control structures i Control structures i
Control structures i
 
CPU
CPUCPU
CPU
 
Type conversion, precedence, associativity in c programming
Type conversion, precedence, associativity in c programmingType conversion, precedence, associativity in c programming
Type conversion, precedence, associativity in c programming
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
Operators
OperatorsOperators
Operators
 
Aae oop xp_04
Aae oop xp_04Aae oop xp_04
Aae oop xp_04
 
Control Structures: Part 1
Control Structures: Part 1Control Structures: Part 1
Control Structures: Part 1
 

Similaire à CIS 1403 lab 4 selection

Advanced Computer Programming..pptx
Advanced Computer Programming..pptxAdvanced Computer Programming..pptx
Advanced Computer Programming..pptxKrishanthaRanaweera1
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Blue Elephant Consulting
 
Fundamentals of Programming Lecture #1.pptx
Fundamentals of Programming Lecture #1.pptxFundamentals of Programming Lecture #1.pptx
Fundamentals of Programming Lecture #1.pptxEyasu46
 
Testcase design techniques final
Testcase design techniques finalTestcase design techniques final
Testcase design techniques finalshraavank
 
Ch5 Selection Statements
Ch5 Selection StatementsCh5 Selection Statements
Ch5 Selection StatementsSzeChingChen
 
4. decision making and some basic problem
4. decision making and some basic problem4. decision making and some basic problem
4. decision making and some basic problemAlamgir Hossain
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)It Academy
 
Cprogrammingprogramcontrols
CprogrammingprogramcontrolsCprogrammingprogramcontrols
Cprogrammingprogramcontrolsteach4uin
 
Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Blue Elephant Consulting
 
Java Programming - Conditional Statements (Switch).pdf
Java Programming - Conditional Statements (Switch).pdfJava Programming - Conditional Statements (Switch).pdf
Java Programming - Conditional Statements (Switch).pdfROWELL MARQUINA
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2yasir_cesc
 
Lecture 01 - Introduction and Review.ppt
Lecture 01 - Introduction and Review.pptLecture 01 - Introduction and Review.ppt
Lecture 01 - Introduction and Review.pptMaiGaafar
 

Similaire à CIS 1403 lab 4 selection (20)

Conditional Statements
Conditional StatementsConditional Statements
Conditional Statements
 
Advanced Computer Programming..pptx
Advanced Computer Programming..pptxAdvanced Computer Programming..pptx
Advanced Computer Programming..pptx
 
Ch04
Ch04Ch04
Ch04
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2
 
Ch05.pdf
Ch05.pdfCh05.pdf
Ch05.pdf
 
Using decision statements
Using decision statementsUsing decision statements
Using decision statements
 
slides03.ppt
slides03.pptslides03.ppt
slides03.ppt
 
Fundamentals of Programming Lecture #1.pptx
Fundamentals of Programming Lecture #1.pptxFundamentals of Programming Lecture #1.pptx
Fundamentals of Programming Lecture #1.pptx
 
Testcase design techniques final
Testcase design techniques finalTestcase design techniques final
Testcase design techniques final
 
Ch5 Selection Statements
Ch5 Selection StatementsCh5 Selection Statements
Ch5 Selection Statements
 
4. decision making and some basic problem
4. decision making and some basic problem4. decision making and some basic problem
4. decision making and some basic problem
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)
 
Cprogrammingprogramcontrols
CprogrammingprogramcontrolsCprogrammingprogramcontrols
Cprogrammingprogramcontrols
 
Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Java Programming - Conditional Statements (Switch).pdf
Java Programming - Conditional Statements (Switch).pdfJava Programming - Conditional Statements (Switch).pdf
Java Programming - Conditional Statements (Switch).pdf
 
Testing techniques
Testing techniquesTesting techniques
Testing techniques
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
Lecture 01 - Introduction and Review.ppt
Lecture 01 - Introduction and Review.pptLecture 01 - Introduction and Review.ppt
Lecture 01 - Introduction and Review.ppt
 

Dernier

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 

Dernier (20)

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

CIS 1403 lab 4 selection

  • 2. Introduction This lab discusses selections and provides examples of if statement, nested if, and switch. It also covers logical operators and relational operators. It gives many examples to help the student develop logical think and structure computer logic. Skill-set By completing this lab, the students will develop the following skills: • Build accurate, simple and nested if statement • Use appropriate logical and relational operators to solve programming problems that require the use of selection • Develop a user menu using a combination of a switch and while loop How to use this lab? Follow the lab instruction in step by step and complete all exercises. Watch the associated videos. Modify the examples to and exercises to experiment with different scenarios to solve a similar problem. Click the QR code to access the videos and PowerPoint icon to access the associated PowerPoints.
  • 3. 3 Why selection is needed? In our life, we are required to make decision-based on certain conditions. For example, if you are on the road and find the intersection, you decide to go right, left or straight based on your destination and the fast or less traffic road. In programming, there are situations when you need to apply a specific process when a condition is true and another process when it is false. The Java Language uses two essential commands to allow us to select what process should be executed in case of one or more conditions are met. These two commands are: if ... else and switch. A simple if statement structure Here is a simple structure of an if statement|: If (condition) Process1 Process2 The rest of the code true false In the above structure, when the condition is met (true), the first process is executed. When the condition is false, process 2 is executed. A process can be one or more lines of call. You may also call another function/method as part of your process or perform some calculations.
  • 4. 4 Building conditions The condition involved comparing values. Here is a simple example: Line 3 declares and initiates x as 100. In line 4 we have the condition x>5, which can be read as Is x more than 50?. The answer in this case is true. X is 100, which is more than 50. Therefor the program will go to line 5 and display Change line 3 to be int x = 45; What output will you get in this case? Explain briefly what has happened? Exercise
  • 5. 5 Use of brackets if statement • The condition should be included between two brackets of this type ( ) • An opened and closed braces { } should follow the condition. The process that must be executed in case the condition is true should be included between these two braces. See line 4 to line 6. When there is only one line needed for the process, these two braces become optional. • The same applies to the else block. Indentation Using consistent and appropriate indentation will improve the readability of your code. • In the above example, please note that line 4 is pushed to the right to show that it is part of the process that will be executed when the condition is met. The same for line 8. • Also, lines from 3 to 9 are pushed/indented to right to show they are all part of the main function. Indentation is optional for Java Language. However, it is must for some other languages including Python. Here is another example:
  • 6. 6 The Relational Operators When comparing two variables, you need to use a rational operator. All programming languages use complete relationship operators. The table below summarizes the relational operators available in the Java Language. • It is important to note that to compare if two values are equal, then you use == and not only =. • A single = is used only to assign a value to the variable, == is used to compare or check the value of a variable. Also, note >= is correct by => is incorrect.
  • 7. 7 Exercise What will be the result of this code and why? Change x value in line 3 to 20. What will be the result and why? If you need to check if y is true, then you need an if statement. See line 5 of this code. Line 5 is using the condition in line 4 to check the value of y. When y is true, the message “Y is equal to 50.” is displayed, else “Y is NOT equal to 50.” is displayed.
  • 8. 8 Logical Operators When you have more than one condition, then you need to link them using logical operators. We will use only 3 logical operators that are AND, OR, and NOT. Assume we have two conditions. • If both conditions must be met, then we use and. The symbol for and is && • If we need at least one of the two conditions to be met, then we use or. The symbol for or || • If we want to reverse the logic, then we use logical not, The symbol is ! The operator (! logical not) has a limited use cases. Therefore, we will focus on && and ||. In the following table, assume boolean variables A holds true and variable B holds false
  • 9. 9 An Example Assume there is an insurance company that provides a rate of 3.5% for cars with price value more than or equal 10,000 and model of 2015 or above. Other cars have to pay 4.5% rate to be insured by this company. Here is the code to solve this problem. • Please focus on line 13. You will notice that we have used && to ensure that both conditions are met to provide a 3.5% rate. • If the answer is true, then line 14 is executed. For any car that does not meet this condition, line 18 is executed. • Line 20 is outside the if statement and executed after the calculation of insurance value. • You are expected to be familiar with the rest of the code.
  • 10. 10 Exercise What is the output of this code and why? Change line 4 to int y = 20; What is the output in this case any why?
  • 11. 11 Exercise What is the output of this code and why? Change line 4 to int y = 50; What is the output in this case any why?
  • 12. 12 Examine this code carefully. How many conditions do we have? Line 7 requires that x to be more than 70 and either x<5 or y<40. If x is not more than 10, the rest of the conditions are ignored. What is the result of this code? What will happen if you change x value in line 3 to 11?
  • 13. 13 Nested if statement Condition 1 Condition 2Process 1 The rest of code Process 2 Process 3 true true false false When you have an if statement inside another if statement, this is referred to as nested if. Nested if is a very common in programming to deal with more complex conditions. However, they are logical, easy to follow and implement. Here is an example of nested if structure. • Process 1 is executed when the result of condition1 is true. In this case, condition2 is ignored. • However, if the result of condition1 is false, condition2 is checked. If condition 2 is true, process 2 is executed. • If both condition1 and condition2 are false, then process 3 is executed.
  • 14. 14 An example - nested if statement Examine this code. What do you think the result in this case? • Given that x = 5 and y=30, the result of line 8 is false. Simply the condition y<30 is not met as y=30 and not less than 30. In this case, the execution is moved to line 11. • The result of line 11 is also false, because y is not less than 5 or more than or equal 35. Basically 3 is not less than 5 and 30 is not more than or equal 35. None of these conditions is met • The last option is line 16. The result is 3 * 5 = 150.
  • 15. 15 An exercise - nested if statement Examine this code. What do you think the result in this case?
  • 16. 16 switch in Java If you need to select between discrete values for example 1, 2, 3, 4, etc. Or “A”, “B”, “C”, etc., then switch is a good option. Here is an example that allow the user to enter a number and check: • If the entered number is 1, then the message “You have entered 1” will be displayed. • If the number is 2 the message “You have enter 2” is displayed • However, if user enters a different number apart of 1 and 2, the messaged “You entered an invalid number” will be displayed. The switch structure has 5 main components that are: 1. The switch command (line 8), 2. The switch parameter (in this example the variable option), 3. A case for every option (lines 9 and 12) 4. A default which is executed if the entered value is not one the option (line 15). 5. It is important to have the keyword break at the end of each case including the default option. One of the common use cases of switch is creating user-menu.
  • 17. 17 switch and while To create a user menu, you need include the switch inside a while loop as in this example. The while command in line 8 repeats all lines from 9 to 29 while the user did not enter 3. As soon as the user enter 3 the program stops and the message “This is the end.” is displayed.
  • 18. 18 1. Develop a Java program that reads an integer number and determines if the number entered is 'positive', 'negative', or 'zero' and outputs the result on the screen. 2. Develop a Java program that reads an integer number, determines if the number is odd or even and outputs a message on the screen indicating the number is odd or even. 3. Develop a Java program that will accept marks in the range of 0 to 100 and will determine the grade according to data given in the table below: 00 – 59 F 60 – 64 D 65 – 74 C 75 – 89 B 90 – 100 A Your program should output an error message if the user enters a mark that is outside the range 0 – 100. 4. Write a Java program that will receive two integer numbers and display their sum, difference, product, and quotient. The quotient (first integer divided by second integer) is only to be performed if the second integer does not equal zero 5. A program is required to read a customer’s name, a purchase amount and a discount code. The discount code will be one of the following: A no discount (0%) B small discount (3%) C medium discount (12%) D big discount (20%) The program must then compute the discount amount and the sales total and then print the customer’s name, purchase amount, discount amount and the total due. 6. Develop a program that asks the user about his grade and displays a message based on the grade entered. The program should display “Excellent” for an A, “Very Good” for a B, “Good” for a C, “Acceptable” for a D, and “Failed you have to repeat the course” for a F. The case of grade entered should not matter. For example capital “A” or small “a” are similar. 7. UAE post office charges parcels per kilogram. If the parcel is 5 kilos or less it charges AED 10 per kilogram. If the parcel is 10 kilos or less but greater than 5 kilos it charges AED 8 per kilogram. If the parcel is more than 10 kilos it charges AED 5 per kilogram. Develop a program that asks the user to enter the weight and displays the weight and charge on the screen. Exercises