0% found this document useful (0 votes)
3 views

Chapter 2 class slides

Chapter 2 covers data handling, including data representation in memory, variable types, and assignment of values in programming. It explains the binary and hexadecimal number systems, the ASCII and UTF-8 encoding for characters, and the distinction between primitive and reference types in .NET. The chapter also details input and output operations in console applications using C# syntax, emphasizing the importance of variable declaration and initialization.

Uploaded by

vdwaltleeann
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 2 class slides

Chapter 2 covers data handling, including data representation in memory, variable types, and assignment of values in programming. It explains the binary and hexadecimal number systems, the ASCII and UTF-8 encoding for characters, and the distinction between primitive and reference types in .NET. The chapter also details input and output operations in console applications using C# syntax, emphasizing the importance of variable declaration and initialization.

Uploaded by

vdwaltleeann
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Chapter 2

Handling Data Part 1


What you will know after this chapter

 Understand how data is represented in memory.


 Understand the concepts of variables and types.
 Know how to assign values to variables.
 Understand how variables can be cast from one type to another.
 Understand how to use arithmetic operators.
 Know how to format output.
Data representation

 Bits and Bytes


 A bit(binary digit) is the basic unit of information
in Decimal Binary
computing and telecommunications. It exists in two
distinct states, for example the two stable positions of K Kilo 1000 1024
an electrical switch,two distinct voltage or current M Mega 10002 10242
levels allowed by a circuit, two distinct levels of light G Giga 10003 10243
intensity, two directions of magnetization or
polarization, etc. The two states are often interpreted T Tera 10004 10244
as binary digits and are usually denoted by the Arabic P Peta 10005 10245
numerical digits 0 and 1 .
 A byteis an ordered collection of 8 bits, in which each
bit denotes the binary value of 1 or .0A byte can be
used to encode a character of text. Note that a
kilobyte is 1024 bytes and not 1000 bytes .
Data representation
 Representation bool
of values
 The two states of a bit can also be interpreted
logical values
, e.g.true/false or yes/no.
as

 Number
 systems
Electronic storage media are only capable to store single
computers
bits. use
the
binarnumber system where the two distinct states are represented
Therefore, . In the same
as 0 and
way
y that
1 1 and 1 use the same digits but represent different2numbers,
and 2
use
504 the same
0 450bits0 but
1100represent two different 1001
numbers.

 Think back to your grade 2 days and remember that your teacher taught you about the place
values of digits in a
number: 50 = 51 2 +0 x1 1 +4 x1 0
4 x= 50
0 + 00 +0
0 4
Data representation

 In the binary number system


, for example: X10 X2 X16
0 0000 0
1 0001 1
10110011102 = 1 x 29 + 0 x28 + 1 x 27 + 1 x 26 + 0 x25 + 0 x24 + 1 x 23 + 1 x 22 + 1 x 21 + 0 x20 2 0010 2
3 0011 3
= 512 + 0 +128 + 64 + 0 + 0 +
8 + 4 + 2 + 0 4 0100 4
= 718 (Decimal, base 10) 5 0101 5
6 0110 6
7 0111 7
 The hexadecimal system has a base of 16. This means it has
16 digits, namely0, 1, 2, 3, 8 1000 8
9 1001 9
4, 5, 6, 7, 8, 9, A, B, C, D, E,
. For
F example:
10 1010 A
11 1011 B
12 1100 C
2AB16 = 2 x162 + 10 x161 + 11 x160 13 1101 D
= 512 + 160 + 11 14 1110 E
15 1111 F
= 683(Decimal, Base 10)
0 0000 01
0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5 6
0110
6
Data representation

X10 X2 X16
 Binary numbers are difficult toandread
even small values will occupy many
digits. Thehexadecimal system provides a human friendly representation
of
binary numbers. Eachhexadecimal digit represents four bits
. For example:

1011001110
2 = 0010 1100 1110
= 2 C E
= 2 x162 + 161 + 14 x160
12 x
= 512 + 192 + 14
= 718 (Decimal, Base10)
7 0111 7
8 1000 8
9 1001 9
10 1010 A 11
1011
B 12
1100
C 13
1101
D 14
1110
E 15
1111
F
Representation of
characters
 Inorder to store characters such as 'A', '*', ' ' (space), etc. in a digital format, the American
Standards Association developed a coding scheme, the ASCII (table American
in 1968
Standard Code for Information Interchange). Since196 the standard has been revised
and extended to accommodate various characters 8 in many of the world's
. languages
Currentl , theUT-8 ( -bit Unicode Transformation Format)
standard is steadily becoming
the
y preferred F encoding
8 scheme
. In the table below,first
the four bits of every byte is
shown in the left hand column and the second four bits in the top row. Thus, the character
'A' is represented with 0100 0001or(binary)
41hex.
Understanding Variables and Types

 Primitive types
 Variables are "things" like objects but they are saved differently in the computer's memory.
Variables are saved on the stack and the variable name points to the value itself. Objects are
saved on the heap and the object name points to an address where the object is saved.

 The word type is used to indicate the kind of variable or object that is referred to.
There are three categories of types: Value types are used for variables and
reference types are used for objects and strings. Pointer types are beyond the
scope of this book. Classes and strings are reference types.
Understanding Variables and Types

 Variables are instances of predefined value types in the .NET, framework


asopposed to
objects that are instances of classes
. Thetypes are defined in the System namespace in
the .NET framework. C# has defined some aliases for the .NET types, e.g. string for String,
double for Double,
intfor Int64
.
 Each variable
has:1. a name2. a type3. content (a value)
Look at the following diagrammatic example and identify these three characteristics for
each variable.
Memory
iAge cGender sName
Variable Name
29 ‘M’ “Jay”
Memory Cell
dHeight hasDriversLicense
sStudentNumber

Value 1,78 true 214001792


mSalaray
6000
m
Understanding Variables and Types

variables
char contain
variables a series
contain single of alphanumeric
charactersand string
 The most common variable types are:
characters.
 char
int, double and decimal variables contain numeric
 string values. int variables contain whole numbers, i.e.
values with no decimal part. double variables
 int contain values which may or may not have a decimal
part. decimal variables also contain values that may
 Double have a decimal part, but they have higher precision
and are therefore more appropriate for monetary
 decimal values. (RULE OF THUMB, DEC IS FOR CURRENCY)
bool variables contain either the word true or the
 bool word false. That is, there are only two possible
values for bool variables. These values indicate if a
specific condition holds or not.
Understanding Variables and Types
 The most common variable types are:
char values are written between single quotes
 char and string values are written between double
quotes.
 string Values of
 in other
types are
 tDouble not
written
 decimal between
quotes.
 bool
As for controls, variables are named such that:
1. the name reflects the purpose of the variable and 2. indicate the type of the variable.
Note the prefixes in the examples above and identify the type of each.

C# is case sensitive. This means that iAge and iage are two different variable names.
Assignment of values

 The C# equivalent of the diagram above looks as follows.


Make sure
that you can identify the name, type and contents for each one of the
lines:
Type Variable Value Note that the declaration and
instantiation of the objects (variables)
are done all at once. Unlike other
objects, variables do not need the
stringsName = "Jay"; keyword newto be instantiated. In fact,
we could also write
char cGender = 'M';
stringsStudentNumber= "214001792"; strin sName;
g
int iAge = 29; to declare and instantiate the variable
.
double dHeight = 1.78; That is, we don't need to assign a value
to the variable upon declaration and
decimal mSalary= 6000m; we can always, at a later stage, write
bool hasDriversLicence= true;
sName = "Jay";
Assignment of values

 The C# equivalent of the diagram above looks as follows.


Make sure
that you can identify the name, type and contents for each one of the
lines:
Note that the declaration and
instantiation of the objects (variables)
are done all at once. Unlike other
objects, variables do not need the

type name value keyword new to be instantiated. In fact,


we could also write

strinsName;
g
to declare and instantiate the variable
.
declaration; initialisation That is, we don't need to assign a value
instantiation to the variable upon declaration and
we can always, at a later stage, write
Assignment of values

sName = "Jay";
 The '=' in the code above is called an assignment operator. This simply means that a value is
assigned to a variable or that the memory cell gets content. The variable name is always at
the left hand side of the assignment operator and the value always at the right hand side.
 Assigning a starting value for a variable is referred to as initialisation.
 Note that '=' does not mean "equals"!! The line of code above should be read as: "Assign the
value "Jay" to sName.".
 As an example of the possible danger that could happen if '=' was read as "equals", consider
the following:
 int iAge = 21;
 iAge = 29;
 If '=' was "equals" the second line above would mean that 21 = 29! Instead, it means that
the initial value of 21 is replaced by 29. In other words, the previous value was kicked out of
the memory cell and now the memory cell contains the value 29.
Chapter 2
Handling Data Part 2
 We use the word literal to refer to fixed values. For example 17, "Jay", 12.5 are literals.
Input in a Console Application
Input in a Console Application

 Start with a new console application.


stringsName = "Jay";
char cGender = 'M';
stringsStudentNumber= "214001792";
int iAge = 29;
double dHeight= 1.78;
decimal mSalary= 6000m;
bool hasDriversLicence
= true;
 Enter the following code in the Main() method, run the program and inspect the
output.
//Get input
Console.Writ("Name:
e ");
strinsName =Console.ReadLine(;
g )
Console.Writ("Surname:
e ");
strinsSurnam =Console.ReadLine(;
g e )
Console.Writ("Age:
e ");
in iAge=int.Pars (Console.ReadLine
() ;
t e )
//Clear console window
Console
.Clear
(;
)
Input in a Console Application

//Clear console window


Console.Clear();
//Produce output
stringsNameSurname=sName+ " " +
sSurname
;
Console.WriteLine("Good day, " +sNameSurname+ Note thecommentsin the code. It
"!"); enhances readabilityof the
Console.WriteLine("You are " +
iAge.ToString
() + " years old."); program andindicates the purpose
Console.WriteLine(); of each section of code. Also note
the use of empty lines to enhance
Console.WriteLine(); readability.
//Allow the user opportunity to read output
Console.Write("Press any key to exit ...");
Console.ReadKey();
Input in a Console Application

You will remember that we said that a method


encapsulates a piece of code that does
something. Some methods can also return a value
that can then be assigned to a variable orutilisedin
another way. TheReadLine() method is such a
method. It allows the user to enter a character
string from the keyboard and then returns it as a
string. It does not take any parameters
.

The line
stringsName = Console.ReadLine();

does several things in one line:


1. It reads a character string from the keyboard
(Right-hand side of assignment first.)
2. It declares a stringvariable, sName.
3. It assigns the character string to the
string
variable.
Input in a Console Application

Note the lines of code that prompt the user prior to


every call to theReadLine() method so that he
knows what is expected of him.
The Clear () method clears the console window.

The line
stringsNameSurname= sName + " + sSurname;
"
also does several things at once:
1. It concatenates (join head-to-tail) the string
variables sName and sSurnamewith a space
between them.
2. It declares a string variable
, sNameSurname.
3. It assigns the concatenated character string to
the string variable.
Input in a Console Application
The line
int iAge = int.Parse(Console.ReadLine() );

1. reads a character stringfrom the keyboard (brackets first


on the right-hand side of the assignment statement ).
2. The ReadLine() method returns a string value which must
be converted to int (using theParse() static method of the
int class) before
3. it can be assigned to anint variable.

The line
Console.WriteLine("Good day, " + sNameSurname+ "! );
"
1. displays a character stringthat consists of a greeting
message and the contents of the variable
sNameSurname.
2. The text between double quotes is displayed exactly as it
is typed while the content of thevariable sNameSurname
is concatenated with it.
Input in a Console Application
The line
Console.WriteLine("You are " + iAge .ToString() + " years old."
);

also displays a concatenated character string, but note that


the int variable must be converted to stringfirst before the
concatenation. (We could have omitted the ToString()
method. C# will convert theint implicitly to string prior to
concatenation, but this is not good programming. )

Note the two Console.WriteLine() statements which serve to


separate the last line of output with the message that the
user must press any key to exit the program.
Neat program
output is extremely important to enhance readability and
minimiseuser errors.
Chapter 2
Handling Data Part 3
Numeric Processing in a Console
Application
 Type
 Casts
It is sometimes necessary to change the type of a variable from one type to another. A type cast
can be done implicitly or explicitly.
 Thefollowing diagram indicates the compatibility between the numeric data types. It shows, for
example, thatinan
value can be assigneddouble
to a variable
but not the other way. round
t do a type cast by preceding a variable with the new type between brackets, for
 In the code, we
example

 will change the type of


in c
before
to assigning the value
i. to
t
The difference between 9 and '9'
The difference between 9 and '9'

 We can obtain the ASCII code for a character by castingint


to, for example
char c = 'A';
int i =(int)c;
i will now contain the value
65.
To obtain the character associated with a specific ASCII code, castint
thevalue to char:
int i =65;
char c =(char)i;
c will now contain'A';
 Write a small console application with the following code in the Main() method:
Input in Console Application

 In C#, type casting refers to converting a value from one data type to another.
Type casting can be done implicitly or explicitly.
 Explicit type casting, also known as casting or type conversion, is when you
explicitly tell the compiler to convert a value from one type to another using a cast
operator. For example, when you convert an integer value to a string, you use the
ToString() method:
int myInt = 10; string myString =
myInt.ToString();
 Here, the integer value 10 is explicitly cast to a string using the ToString() method.
 Implicit type casting, also known as type coercion, is when the compiler
automatically converts a value from one type to another without you having to
specify it. This happens when the value being assigned to a variable or passed as
an argument is compatible with the destination type. For example, when you
convert a smaller integer type to a larger integer type, such as byte to int, no cast
operator is required: Byte myByte = 10; int myInt = myByte;
 Here, the byte value 10 is implicitly cast to an int, because an int can hold a larger
range of values than a byte.
 There are two methods that we can use for formatting output. ToString() is a non-static
method that must be applied to a numeric variable. It converts the numeric value to a
string and formats it according to given parameters. The Format() method is a static
method of the String class. This means it must be called with reference to the class and
not a variable.
 The ToString() method
Arithmetic
Formattingoperators
output and operands

 The ToString() method may take a string parameter between the brackets that indicates
the way in which the output must be formatted.
Console.WriteLine("Retail price: " + mRetailPrice.ToString("0"));
Console.WriteLine("Retail price: " + mRetailPrice.ToString("0.0"));
Console.WriteLine("Retail price: " + mRetailPrice.ToString("0.00"));
 If we call the method without any parameters, no formatting is done.
Arithmetic operators and operands

Operato Operation Example Result


r
= Assignment int iResult = 3; 3
+ Addition int iResult = 3 + 4; 7
++ Increment int i = 3; int 4 (Increment before
iResult = i++; assignment)
- Subtraction int iResult = 3 – 4; -1
-- Decrement int i = 3; int 2 (Decrement before
iResult = i--; assignment)
* Multiplication int iResult = 3 * 4; 12
/ Division int iResult = 3 / 4; 0
double dResult = 3 / 0.75
4.0;
Operator Operation Example Result
int iResult = 3
% Modulus 3
% 4;
+= int iResult = 3; 7
iResult += 4;
-= int iResult = 3; -1
iResult -= 4;
*= int iResult = 3; 12
iResult *= 4;
/= int iResult = 3; 0
iResult /= 4;
Operator precedence

 Operators will be executedtop


from
to bottom
in the above table.
 Operators on the same will
levelbeexecuted from left to right or right
as to
indicated
left
in the table.
 Brackets will always be done
. Nested
first brackets will be executed starting with the
innermost set and then working outward, for example
in iResul=
t t 10;
iResul* 400 + 10 -/(25
2 2 * 4) *
t
 The = + 3;
order of operations is indicated with numbers below the expression. Do the calculation
manually– you should get 3060.

You might also like