SlideShare a Scribd company logo
Lab 2: Data Types and Variables
CIS 1403
Fundamentals of
Programming
201810
Introduction
This lab aims to develop the student knowledge and skills data types, required
memory storage for each data type, selection of appropriate data types, naming
variables, This lab aims to develop the student knowledge, and skills in identifying
the appropriate data-types for variables, calculate the required memory storage
for each data type, naming variables, casting of data types, and mathematic
operations. casting of data types, and athematic operations.
Skill-set
By completing this lab, the students will develop the following skills:
• Using appropriate and efficient data types to store data.
• Calculate the memory storage required for each data type
• Convert from binary to decimal systems
• Create variables that follow the rules of naming variables
• Apply correct athematic operators with the correct precedence
of operators
• Apply data type casting that does result in loss of data
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.
Why do we need data type?
In life, we are using different data type including numbers, text, and objects.
Using the appropriate data type in our human communication is essential. We
use text (String) for names and description of information and numbers for
counting and applying mathematical calculations. We also refer to objects such
as a cup, chair, people, milk, etc. All these are data types.
Using the appropriate data type in a programming language is essential for two
reasons.
• Data types help to tell the computer processor what type of
data is expected for a specific variable and what amount of
memory space to reserve for it.
• Using appropriate data type will help programmers optimize
the use of computer memory.
You will get a better understanding of the above two points throughout this lab.
Variables
You have seen in Lab 1 that computer programming languages use variable to
represent data. For example, you may use the variable price to store the price
of an item.
float price;
The above line of code is telling the computer processor to reserve a space in
computer memory for the variable price, and that the data type will be a float.
In this example, if the programmer tried to store text in price, the compiler will
generate an error that says “incompatible data types.” Try this example.
Rules for naming variables
It is recommended that you use a variable name that will indicate what data will
be stored in this variable. For example, if you want to store a student grade for an
assessment, a variable name grade or quiz is better than x.
Here are the rules that you need to follow when naming variables in Java.
1. Variable names are case-sensitive.
2. It can contain Unicode letter,Digits and Two Special Characters such as
Underscore and dollar Sign.
3. Length of Variable name can be any number.
4. Its necessary to use Alphabet at the start (however we can use underscore ,
but do not use it )
5. Some auto generated variables may contain ‘$‘ sign. But try to avoid using
Dollar Sign.
6. White space is not permitted.
7. Special Characters are not allowed.
8. Digit at start is not allowed.
9. Subsequent characters may be letters, digits, dollar signs, or underscore
characters.
10. Variable name must not be a keyword or reserved word.
Exercise o correct variable names:
Write down ten different correct variable names and discuss with your
colleagues why these names are correct or not.
How does computer store data?
Before discussing the different data types and when a particular data type should
be used we need to examine how computer stores data. We will focus here on
numerical data.
In our daily life, we use a numerical system call decimal. The decimal system is
the numbers from 0 to infinity (both positive and negative values). Example,
0,1,2,3,4,, … etc.
However, the computer understands only 0 and 1. This computer system is
called a binary system. For example, if you store the number 25 in a variable
age.
int age = 25;
The computer will store the value 11001 as binary in computer memory. 11001
in binary is equal to 25 in the decimal system.
The binary system is presented as 2 to the power n. As you know from Math,
anything to the power zero 0 is equal to 1. The table below gives an example of
how to represent a decimal number using the binary system. Let us take the
number 25.
256 128 64 32 16 8 4 2 1
1 1 0 0 1
2 = 1
0
2 = 2
1
2 = 4
2
2 = 8
3
In the above table, the blue row represents the decimal system and the second
gray row represents the binary system. By examining the above table, you can
think of computer memory as boxes that store data in 1, 2, 4, 8, 16, etc. bits. See
the decimal row. This is why when we try to buy a USB flash disk or SD we cannot
find 7 or 9 GB memory.
In the binary row of the above table, we can enter only one digit in each cell with
0 or 1. We read this table from right to left. A value of 1 in the first cell is equal
to 1, but in the second cell it is equal to 2, the third cell is 4, etc. The value of
each cell is just twice the value of the previous cell.
Decimal
Binary
256 128 64 32 16 8 4 2 1
1 1 0 0 1
2 = 1
0
2 = 2
1
2 = 4
2
2 = 8
3
1
8
16
+
+
25
Decimal
Binary
In this example, if you add values of all cells in the decimal row the values in the
binary row is 1, we get the equal decimal value to the entered binary number.
Exercises on binary system
Convert the following binary system to decimal: 11111, 101, 11000, and 101010.
You can use the above tables to
convert binary to decimal and vise
versa.
Using Java to convert binary to decimal
Try this code to convert binary to decimal:
Here is the explanation of the above code:
• Line 3: stores the binary number as String. Here you can enter the binary
number that you want to convert.
• Line 4: This line uses the object Integer and its function ParseInt to convert
the binary number of decimal the result is stored in the variable decimal as
an int.
• Line 5 and 4: Print the binary and its equivalent decimal number
When you run the above code you get the following results:
Now, you understand how the computer uses binary numbers to store
numerical data. In the next part of this lab, we will discuss all primitive/basic
data types available in Java.
Primitive Data Types
The term “Primitive Data-types” means the most basic data types available
within the Java language. There are eight primitive data types supported by
the Java Language.
The table below summarizes primitive data types support in Java Programming
Language.
There are four integer data types. An integer number is a number that does
not include and fractions (or floating point). It is a whole number. The integer
data types are a byte, short, int, and long. The main difference between these
integer data types is the size of memory space allocated to each one. Each one
has a maximum and minimum value that can be stored. For example, the byte
data type can store numbers no larger than 127 or less than -128. If you try to
store the count of students in a variable with the name nstudents and you have
more than 128 students, the following code will generate an error:
byte nstudents = 128;
The maximum and minimum values
The memory size allocated to byte data type is 8 bits. The first bit of the 8
bit is reserved for the sign (+ or ).
-2
7
128 64 32 16 8 4 2 1
1 1 1 1 1 1 1
The maximum positive number that we can store in byte as a binary is
If we go back and use our previous Java code that converts binary to decimal
and we use ”1111111” as the value for the binary, we will get 128. This
means the maximum amount is 128 – 1 = 127.
Minimum value can be stored in a byte =
The minimum negative number that we can store in byte is
= -128
2- 1
7
Maximum value can be stored in a byte =
Exercise:
Using the table below, you need to calculate the maximum and minimum values
that can be stored in short, int, and long data types.
float and double data types:
The data types float, and double are used to store data with a fraction/floating
point. The size of float is 32 bits, and double is 64 bits. This is primarily why it
called double.
Also, a double data type is more precise than a float. A double variable can
provide precision up to 15 to 16 decimal/floating points as compared
to float precision of 6 to 7 decimal digits.
char data type
The char data type stores character. It required 16 bits = 2 bytes. Each char can
hold only a single character.
boolean data type
A boolean data type is used to store data with two choices: true or
false. Here is an example.
Strings, are a sequence of characters/char. In Java programming
language, strings are treated as objects and not a primitive data type.
The Java platform provides the String class to create and manipulate strings.
char sex = “M”;
String fname = “Khalid”;
Both char and String require putting data between two quotations.
boolean isMale = true;
Casting
Casting in programming language means converting data from one type
to another.
When do you need to use casting?
Assume that you have declared price as byte and later you want to
convert it to float because the price usually contains a floating point.
What are your options?
One option is to cast byte into a float.
Write and test this code.
Line 4 perform the casting as follows:
Data type of
the new
variable
The new
variable
Casting to
float. Note
the use of
brackets
The original
variable to
be casted
Issues with casting
Casting from a lower size data type to a higher size data type does not cause
any issue.
However, casting from a higher size data type to lower size data type may
result in losing data.
Assume you have stored 200 as the price of an item in a short data type and
you are trying to cast to byte.
As you know, a byte can hold the maximum value of 127. 200 is more than
127. We will lose data.
Try and check this code:
The result
As you can see, casting from short to byte results in producing the wrong results.
You will get the correct result only when the value stored in higher data type is
within the limit of the lower data type. Try to change the 200 in line 3 to 125
and run the code. You should get:
Exercise
Discuss the table below and complete the missing information:
Description Appropriat
e variable
name
Data Type Rationale for selecting this data
type
Price of items
in a
supermarket
Number of
registered cars
in UAE
Student mark
for an exam
The balance of
a bank
account (think
of Bill Gates
account)
A student full
name
The result of a
student in an
exam as pass
or fail
A thematic Operators
To perform a mathematical calculation in programming Languages, you need
to use the appropriate arithmetic operators. You are expected to be familiar
with these athematic operators as you have used them in mathematics to do
addition, subtraction, multiplication, and division. In Java, there are specific
symbols that you have to use to perform to the correct calculation. The table
below summarizes these operators. Assume A is 10 and B is 20.
In Java, if you want to raise a number to the power of some other number, then
you need to import java.lang.Math and use the function pow. Here is an example
that raises 20 to the power 3.
Precedence of Java Operators
Operator precedence determines the sequence of expression/calculation. The
word expression refers to the calculation or the formula used to perform the
calculation. An expression may include constants, variables, operators, and
functions. The precedence of Java operators decides how an expression is
evaluated.
Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence/priority than the addition operator
−
For example, x = 20 + 4 * 2; here x is assigned 28, not 48 because operator * has
higher precedence than +, so it first gets multiplied with 4 * 2 and then adds into
20.
Here, operators with the highest precedence appear at the top of the table, those
with the lowest look at the bottom. Within an expression, higher precedence
operators will be evaluated first.
If you want to force any calculation to be performed first, then you have to
include it between brackets. Here is our same example:
x = (20+4)*2
The result will be 48. The computer will give priority for (20+4), and the result
will be multiplied by 2.
Exercises:
1. Write a program that would calculate and output the area of a triangle. Assume base and
height are initialized to 10 and 8 in the program.
Hint: area of a triangle is its base multiplied by its height divided by two.
2. Modify question 3 so that the program accepts the base and height in centimeters from the
user. The program then calculates and outputs the area of the triangle.
3. Write a program to convert Fahrenheit to Celsius temperature and output the result on the
screen.
Hint: Celsius = (Fahrenheit – 32) * 5/9
4. Write a program to prompt the user to enter a value for an amount of money in US dollar.
The program should then convert the amount entered to UAE dirham and output the result
on the screen. Assume one US dollar is AED 3.7
5. The over time rate for a company operating in the UAE is 1.5 times the normal rate. Write a
program to ask the operator to enter the normal rate in UAE dirham, the number of hours
worked at normal rate, and the number of hours worked at overtime rate. The program
should then calculate the gross salary and display the result on the screen.
6. Write a program that asks the user to enter the number of DVDs that he wishes to rent and
the charge of renting a DVD, and then calculates the total charge that he should pay.
7. Write a program that will calculate and display the average mark of 3 different tests. The
program should ask the student to enter the 3 marks first and then display the result.
8. Ahmed wishes to buy 3 books from a bookshop that offers 10% discount on books. Write a
program that asks Ahmed to enter the price of each book and then calculates and displays
the amount of money that he should pay.
9. Salem bought a laptop and printer from a shop that offers discounts on some products. The
original prices of the laptop and printer were 3900 AED and 800 AED respectively. Salem
managed to get 15% discount on the laptop and 10% discount on the printer. Write a
program to find out the amount of money that Salem paid for both items.
10. A family of 4 (husband, wife, 3 years old son and 10 months old daughter). They have
decided to visit Egypt during the Eid break. For the children he will pay 60% and 10% of the
normal ticket price for his son and daughter respectively. Write an algorithm that asks the
husband to enter the price of the air ticket and then calculates and displays the amount of
money he should pay for the 4 tickets.
Complete the following exercises:

More Related Content

What's hot

Parsing in Compiler Design
Parsing in Compiler DesignParsing in Compiler Design
Parsing in Compiler Design
Akhil Kaushik
 
Clock synchronization in distributed system
Clock synchronization in distributed systemClock synchronization in distributed system
Clock synchronization in distributed system
Sunita Sahu
 
Chapter18
Chapter18Chapter18
Chapter18
gourab87
 
Bayesian learning
Bayesian learningBayesian learning
Bayesian learning
Vignesh Saravanan
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
Mukesh Tekwani
 
Logic programming (1)
Logic programming (1)Logic programming (1)
Logic programming (1)
Nitesh Singh
 
Pass by value and pass by reference
Pass by value and pass by reference Pass by value and pass by reference
Pass by value and pass by reference
TurnToTech
 
Timestamp protocols
Timestamp protocolsTimestamp protocols
Timestamp protocols
Prashant Saini
 
cpu scheduling
cpu schedulingcpu scheduling
cpu scheduling
hashim102
 
Classification using back propagation algorithm
Classification using back propagation algorithmClassification using back propagation algorithm
Classification using back propagation algorithm
KIRAN R
 
Introduction to matplotlib
Introduction to matplotlibIntroduction to matplotlib
Introduction to matplotlib
Piyush rai
 
3.9 external sorting
3.9 external sorting3.9 external sorting
3.9 external sorting
Krish_ver2
 
Merge sort algorithm power point presentation
Merge sort algorithm power point presentationMerge sort algorithm power point presentation
Merge sort algorithm power point presentation
University of Science and Technology Chitttagong
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
swapnac12
 
9 virtual memory management
9 virtual memory management9 virtual memory management
9 virtual memory management
Dr. Loganathan R
 
Learning set of rules
Learning set of rulesLearning set of rules
Learning set of rules
swapnac12
 
Chapter 6 intermediate code generation
Chapter 6   intermediate code generationChapter 6   intermediate code generation
Chapter 6 intermediate code generation
Vipul Naik
 
Bayesian networks in AI
Bayesian networks in AIBayesian networks in AI
Bayesian networks in AI
Byoung-Hee Kim
 
Segmentation in operating systems
Segmentation in operating systemsSegmentation in operating systems
Segmentation in operating systems
Dr. Jasmine Beulah Gnanadurai
 
weak slot and filler structure
weak slot and filler structureweak slot and filler structure
weak slot and filler structure
Amey Kerkar
 

What's hot (20)

Parsing in Compiler Design
Parsing in Compiler DesignParsing in Compiler Design
Parsing in Compiler Design
 
Clock synchronization in distributed system
Clock synchronization in distributed systemClock synchronization in distributed system
Clock synchronization in distributed system
 
Chapter18
Chapter18Chapter18
Chapter18
 
Bayesian learning
Bayesian learningBayesian learning
Bayesian learning
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
 
Logic programming (1)
Logic programming (1)Logic programming (1)
Logic programming (1)
 
Pass by value and pass by reference
Pass by value and pass by reference Pass by value and pass by reference
Pass by value and pass by reference
 
Timestamp protocols
Timestamp protocolsTimestamp protocols
Timestamp protocols
 
cpu scheduling
cpu schedulingcpu scheduling
cpu scheduling
 
Classification using back propagation algorithm
Classification using back propagation algorithmClassification using back propagation algorithm
Classification using back propagation algorithm
 
Introduction to matplotlib
Introduction to matplotlibIntroduction to matplotlib
Introduction to matplotlib
 
3.9 external sorting
3.9 external sorting3.9 external sorting
3.9 external sorting
 
Merge sort algorithm power point presentation
Merge sort algorithm power point presentationMerge sort algorithm power point presentation
Merge sort algorithm power point presentation
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
 
9 virtual memory management
9 virtual memory management9 virtual memory management
9 virtual memory management
 
Learning set of rules
Learning set of rulesLearning set of rules
Learning set of rules
 
Chapter 6 intermediate code generation
Chapter 6   intermediate code generationChapter 6   intermediate code generation
Chapter 6 intermediate code generation
 
Bayesian networks in AI
Bayesian networks in AIBayesian networks in AI
Bayesian networks in AI
 
Segmentation in operating systems
Segmentation in operating systemsSegmentation in operating systems
Segmentation in operating systems
 
weak slot and filler structure
weak slot and filler structureweak slot and filler structure
weak slot and filler structure
 

Similar to CIS 1403 Lab 2- Data Types and Variables

Data Type is a basic classification which identifies.docx
Data Type is a basic classification which identifies.docxData Type is a basic classification which identifies.docx
Data Type is a basic classification which identifies.docx
theodorelove43763
 
M C6java2
M C6java2M C6java2
M C6java2
mbruggen
 
Variable
VariableVariable
Data types
Data typesData types
Data types
Dr. Rupinder Singh
 
JAVA LESSON-01.pptx
JAVA LESSON-01.pptxJAVA LESSON-01.pptx
JAVA LESSON-01.pptx
StephenOczon1
 
Hub102 - JS - Lesson3
Hub102 - JS - Lesson3Hub102 - JS - Lesson3
Hub102 - JS - Lesson3
Tiểu Hổ
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
Neeru Mittal
 
variablesfinal-170820055428 data type results
variablesfinal-170820055428 data type resultsvariablesfinal-170820055428 data type results
variablesfinal-170820055428 data type results
atifmugheesv
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.net
Jaya Kumari
 
C++ data types
C++ data typesC++ data types
C++ data types
pratikborsadiya
 
C programming perso notes
C programming perso notesC programming perso notes
C programming perso notes
Melanie Tsopze
 
data science with python_UNIT 2_full notes.pdf
data science with python_UNIT 2_full notes.pdfdata science with python_UNIT 2_full notes.pdf
data science with python_UNIT 2_full notes.pdf
mukeshgarg02
 
Sql Basics And Advanced
Sql Basics And AdvancedSql Basics And Advanced
Sql Basics And Advanced
rainynovember12
 
Numerical data.
Numerical data.Numerical data.
Numerical data.
Adewumi Ezekiel Adebayo
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
Mohammed Khan
 
Sql Server Interview Question
Sql Server Interview QuestionSql Server Interview Question
Sql Server Interview Question
pukal rani
 
Literals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiersLiterals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiers
Tanishq Soni
 
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board ExamsC++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
hishamrizvi
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptx
RockyIslam5
 
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxCOMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
donnajames55
 

Similar to CIS 1403 Lab 2- Data Types and Variables (20)

Data Type is a basic classification which identifies.docx
Data Type is a basic classification which identifies.docxData Type is a basic classification which identifies.docx
Data Type is a basic classification which identifies.docx
 
M C6java2
M C6java2M C6java2
M C6java2
 
Variable
VariableVariable
Variable
 
Data types
Data typesData types
Data types
 
JAVA LESSON-01.pptx
JAVA LESSON-01.pptxJAVA LESSON-01.pptx
JAVA LESSON-01.pptx
 
Hub102 - JS - Lesson3
Hub102 - JS - Lesson3Hub102 - JS - Lesson3
Hub102 - JS - Lesson3
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
 
variablesfinal-170820055428 data type results
variablesfinal-170820055428 data type resultsvariablesfinal-170820055428 data type results
variablesfinal-170820055428 data type results
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.net
 
C++ data types
C++ data typesC++ data types
C++ data types
 
C programming perso notes
C programming perso notesC programming perso notes
C programming perso notes
 
data science with python_UNIT 2_full notes.pdf
data science with python_UNIT 2_full notes.pdfdata science with python_UNIT 2_full notes.pdf
data science with python_UNIT 2_full notes.pdf
 
Sql Basics And Advanced
Sql Basics And AdvancedSql Basics And Advanced
Sql Basics And Advanced
 
Numerical data.
Numerical data.Numerical data.
Numerical data.
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Sql Server Interview Question
Sql Server Interview QuestionSql Server Interview Question
Sql Server Interview Question
 
Literals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiersLiterals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiers
 
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board ExamsC++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptx
 
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxCOMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
 

Recently uploaded

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Zilliz
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 

Recently uploaded (20)

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 

CIS 1403 Lab 2- Data Types and Variables

  • 1. Lab 2: Data Types and Variables CIS 1403 Fundamentals of Programming 201810
  • 2. Introduction This lab aims to develop the student knowledge and skills data types, required memory storage for each data type, selection of appropriate data types, naming variables, This lab aims to develop the student knowledge, and skills in identifying the appropriate data-types for variables, calculate the required memory storage for each data type, naming variables, casting of data types, and mathematic operations. casting of data types, and athematic operations. Skill-set By completing this lab, the students will develop the following skills: • Using appropriate and efficient data types to store data. • Calculate the memory storage required for each data type • Convert from binary to decimal systems • Create variables that follow the rules of naming variables • Apply correct athematic operators with the correct precedence of operators • Apply data type casting that does result in loss of data 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.
  • 3. Why do we need data type? In life, we are using different data type including numbers, text, and objects. Using the appropriate data type in our human communication is essential. We use text (String) for names and description of information and numbers for counting and applying mathematical calculations. We also refer to objects such as a cup, chair, people, milk, etc. All these are data types. Using the appropriate data type in a programming language is essential for two reasons. • Data types help to tell the computer processor what type of data is expected for a specific variable and what amount of memory space to reserve for it. • Using appropriate data type will help programmers optimize the use of computer memory. You will get a better understanding of the above two points throughout this lab. Variables You have seen in Lab 1 that computer programming languages use variable to represent data. For example, you may use the variable price to store the price of an item. float price; The above line of code is telling the computer processor to reserve a space in computer memory for the variable price, and that the data type will be a float. In this example, if the programmer tried to store text in price, the compiler will generate an error that says “incompatible data types.” Try this example.
  • 4. Rules for naming variables It is recommended that you use a variable name that will indicate what data will be stored in this variable. For example, if you want to store a student grade for an assessment, a variable name grade or quiz is better than x. Here are the rules that you need to follow when naming variables in Java. 1. Variable names are case-sensitive. 2. It can contain Unicode letter,Digits and Two Special Characters such as Underscore and dollar Sign. 3. Length of Variable name can be any number. 4. Its necessary to use Alphabet at the start (however we can use underscore , but do not use it ) 5. Some auto generated variables may contain ‘$‘ sign. But try to avoid using Dollar Sign. 6. White space is not permitted. 7. Special Characters are not allowed. 8. Digit at start is not allowed. 9. Subsequent characters may be letters, digits, dollar signs, or underscore characters. 10. Variable name must not be a keyword or reserved word. Exercise o correct variable names: Write down ten different correct variable names and discuss with your colleagues why these names are correct or not.
  • 5. How does computer store data? Before discussing the different data types and when a particular data type should be used we need to examine how computer stores data. We will focus here on numerical data. In our daily life, we use a numerical system call decimal. The decimal system is the numbers from 0 to infinity (both positive and negative values). Example, 0,1,2,3,4,, … etc. However, the computer understands only 0 and 1. This computer system is called a binary system. For example, if you store the number 25 in a variable age. int age = 25; The computer will store the value 11001 as binary in computer memory. 11001 in binary is equal to 25 in the decimal system. The binary system is presented as 2 to the power n. As you know from Math, anything to the power zero 0 is equal to 1. The table below gives an example of how to represent a decimal number using the binary system. Let us take the number 25. 256 128 64 32 16 8 4 2 1 1 1 0 0 1 2 = 1 0 2 = 2 1 2 = 4 2 2 = 8 3 In the above table, the blue row represents the decimal system and the second gray row represents the binary system. By examining the above table, you can think of computer memory as boxes that store data in 1, 2, 4, 8, 16, etc. bits. See the decimal row. This is why when we try to buy a USB flash disk or SD we cannot find 7 or 9 GB memory. In the binary row of the above table, we can enter only one digit in each cell with 0 or 1. We read this table from right to left. A value of 1 in the first cell is equal to 1, but in the second cell it is equal to 2, the third cell is 4, etc. The value of each cell is just twice the value of the previous cell. Decimal Binary
  • 6. 256 128 64 32 16 8 4 2 1 1 1 0 0 1 2 = 1 0 2 = 2 1 2 = 4 2 2 = 8 3 1 8 16 + + 25 Decimal Binary In this example, if you add values of all cells in the decimal row the values in the binary row is 1, we get the equal decimal value to the entered binary number. Exercises on binary system Convert the following binary system to decimal: 11111, 101, 11000, and 101010. You can use the above tables to convert binary to decimal and vise versa.
  • 7. Using Java to convert binary to decimal Try this code to convert binary to decimal: Here is the explanation of the above code: • Line 3: stores the binary number as String. Here you can enter the binary number that you want to convert. • Line 4: This line uses the object Integer and its function ParseInt to convert the binary number of decimal the result is stored in the variable decimal as an int. • Line 5 and 4: Print the binary and its equivalent decimal number When you run the above code you get the following results: Now, you understand how the computer uses binary numbers to store numerical data. In the next part of this lab, we will discuss all primitive/basic data types available in Java.
  • 8. Primitive Data Types The term “Primitive Data-types” means the most basic data types available within the Java language. There are eight primitive data types supported by the Java Language. The table below summarizes primitive data types support in Java Programming Language. There are four integer data types. An integer number is a number that does not include and fractions (or floating point). It is a whole number. The integer data types are a byte, short, int, and long. The main difference between these integer data types is the size of memory space allocated to each one. Each one has a maximum and minimum value that can be stored. For example, the byte data type can store numbers no larger than 127 or less than -128. If you try to store the count of students in a variable with the name nstudents and you have more than 128 students, the following code will generate an error: byte nstudents = 128; The maximum and minimum values
  • 9. The memory size allocated to byte data type is 8 bits. The first bit of the 8 bit is reserved for the sign (+ or ). -2 7 128 64 32 16 8 4 2 1 1 1 1 1 1 1 1 The maximum positive number that we can store in byte as a binary is If we go back and use our previous Java code that converts binary to decimal and we use ”1111111” as the value for the binary, we will get 128. This means the maximum amount is 128 – 1 = 127. Minimum value can be stored in a byte = The minimum negative number that we can store in byte is = -128 2- 1 7 Maximum value can be stored in a byte =
  • 10. Exercise: Using the table below, you need to calculate the maximum and minimum values that can be stored in short, int, and long data types.
  • 11. float and double data types: The data types float, and double are used to store data with a fraction/floating point. The size of float is 32 bits, and double is 64 bits. This is primarily why it called double. Also, a double data type is more precise than a float. A double variable can provide precision up to 15 to 16 decimal/floating points as compared to float precision of 6 to 7 decimal digits. char data type The char data type stores character. It required 16 bits = 2 bytes. Each char can hold only a single character. boolean data type A boolean data type is used to store data with two choices: true or false. Here is an example. Strings, are a sequence of characters/char. In Java programming language, strings are treated as objects and not a primitive data type. The Java platform provides the String class to create and manipulate strings. char sex = “M”; String fname = “Khalid”; Both char and String require putting data between two quotations. boolean isMale = true;
  • 12. Casting Casting in programming language means converting data from one type to another. When do you need to use casting? Assume that you have declared price as byte and later you want to convert it to float because the price usually contains a floating point. What are your options? One option is to cast byte into a float. Write and test this code. Line 4 perform the casting as follows: Data type of the new variable The new variable Casting to float. Note the use of brackets The original variable to be casted
  • 13. Issues with casting Casting from a lower size data type to a higher size data type does not cause any issue. However, casting from a higher size data type to lower size data type may result in losing data. Assume you have stored 200 as the price of an item in a short data type and you are trying to cast to byte. As you know, a byte can hold the maximum value of 127. 200 is more than 127. We will lose data. Try and check this code: The result As you can see, casting from short to byte results in producing the wrong results. You will get the correct result only when the value stored in higher data type is within the limit of the lower data type. Try to change the 200 in line 3 to 125 and run the code. You should get:
  • 14. Exercise Discuss the table below and complete the missing information: Description Appropriat e variable name Data Type Rationale for selecting this data type Price of items in a supermarket Number of registered cars in UAE Student mark for an exam The balance of a bank account (think of Bill Gates account) A student full name The result of a student in an exam as pass or fail
  • 15. A thematic Operators To perform a mathematical calculation in programming Languages, you need to use the appropriate arithmetic operators. You are expected to be familiar with these athematic operators as you have used them in mathematics to do addition, subtraction, multiplication, and division. In Java, there are specific symbols that you have to use to perform to the correct calculation. The table below summarizes these operators. Assume A is 10 and B is 20. In Java, if you want to raise a number to the power of some other number, then you need to import java.lang.Math and use the function pow. Here is an example that raises 20 to the power 3.
  • 16. Precedence of Java Operators Operator precedence determines the sequence of expression/calculation. The word expression refers to the calculation or the formula used to perform the calculation. An expression may include constants, variables, operators, and functions. The precedence of Java operators decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence/priority than the addition operator − For example, x = 20 + 4 * 2; here x is assigned 28, not 48 because operator * has higher precedence than +, so it first gets multiplied with 4 * 2 and then adds into 20. Here, operators with the highest precedence appear at the top of the table, those with the lowest look at the bottom. Within an expression, higher precedence operators will be evaluated first. If you want to force any calculation to be performed first, then you have to include it between brackets. Here is our same example: x = (20+4)*2 The result will be 48. The computer will give priority for (20+4), and the result will be multiplied by 2.
  • 17. Exercises: 1. Write a program that would calculate and output the area of a triangle. Assume base and height are initialized to 10 and 8 in the program. Hint: area of a triangle is its base multiplied by its height divided by two. 2. Modify question 3 so that the program accepts the base and height in centimeters from the user. The program then calculates and outputs the area of the triangle. 3. Write a program to convert Fahrenheit to Celsius temperature and output the result on the screen. Hint: Celsius = (Fahrenheit – 32) * 5/9 4. Write a program to prompt the user to enter a value for an amount of money in US dollar. The program should then convert the amount entered to UAE dirham and output the result on the screen. Assume one US dollar is AED 3.7 5. The over time rate for a company operating in the UAE is 1.5 times the normal rate. Write a program to ask the operator to enter the normal rate in UAE dirham, the number of hours worked at normal rate, and the number of hours worked at overtime rate. The program should then calculate the gross salary and display the result on the screen. 6. Write a program that asks the user to enter the number of DVDs that he wishes to rent and the charge of renting a DVD, and then calculates the total charge that he should pay. 7. Write a program that will calculate and display the average mark of 3 different tests. The program should ask the student to enter the 3 marks first and then display the result. 8. Ahmed wishes to buy 3 books from a bookshop that offers 10% discount on books. Write a program that asks Ahmed to enter the price of each book and then calculates and displays the amount of money that he should pay. 9. Salem bought a laptop and printer from a shop that offers discounts on some products. The original prices of the laptop and printer were 3900 AED and 800 AED respectively. Salem managed to get 15% discount on the laptop and 10% discount on the printer. Write a program to find out the amount of money that Salem paid for both items. 10. A family of 4 (husband, wife, 3 years old son and 10 months old daughter). They have decided to visit Egypt during the Eid break. For the children he will pay 60% and 10% of the normal ticket price for his son and daughter respectively. Write an algorithm that asks the husband to enter the price of the air ticket and then calculates and displays the amount of money he should pay for the 4 tickets. Complete the following exercises: