SlideShare una empresa de Scribd logo
1 de 17
Descargar para leer sin conexión
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:

Más contenido relacionado

La actualidad más candente

Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In JavaSpotle.ai
 
PHP File Handling
PHP File Handling PHP File Handling
PHP File Handling Degu8
 
Rest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API SecurityRest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API SecurityMohammed Fazuluddin
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Type casting in java
Type casting in javaType casting in java
Type casting in javaFarooq Baloch
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging TechniquesWebStackAcademy
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and MethodsNilesh Dalvi
 
File handling in c
File handling in cFile handling in c
File handling in caakanksha s
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
External to DA, the OS X Way
External to DA, the OS X WayExternal to DA, the OS X Way
External to DA, the OS X WayStephan Borosh
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.ioNilaNila16
 

La actualidad más candente (20)

Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 
PHP File Handling
PHP File Handling PHP File Handling
PHP File Handling
 
Rest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API SecurityRest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API Security
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
 
Uploading a file with php
Uploading a file with phpUploading a file with php
Uploading a file with php
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
 
Files in php
Files in phpFiles in php
Files in php
 
HTML Tags
HTML Tags HTML Tags
HTML Tags
 
File handling
File handlingFile handling
File handling
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Type casting
Type castingType casting
Type casting
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
External to DA, the OS X Way
External to DA, the OS X WayExternal to DA, the OS X Way
External to DA, the OS X Way
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 

Similar a 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.docxtheodorelove43763
 
Hub102 - JS - Lesson3
Hub102 - JS - Lesson3Hub102 - JS - Lesson3
Hub102 - JS - Lesson3Tiể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 resultsatifmugheesv
 
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.netJaya Kumari
 
C programming perso notes
C programming perso notesC programming perso notes
C programming perso notesMelanie Tsopze
 
Sql Server Interview Question
Sql Server Interview QuestionSql Server Interview Question
Sql Server Interview Questionpukal rani
 
Literals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiersLiterals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiersTanishq 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 Examshishamrizvi
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptxRockyIslam5
 
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.docxdonnajames55
 
course31_a_ex01_task.pdf
course31_a_ex01_task.pdfcourse31_a_ex01_task.pdf
course31_a_ex01_task.pdfKentushArshe
 

Similar a 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
 
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
 
course31_a_ex01_task.pdf
course31_a_ex01_task.pdfcourse31_a_ex01_task.pdf
course31_a_ex01_task.pdf
 

Último

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 

Último (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 

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: