0% found this document useful (0 votes)
14 views71 pages

Inf1030 02 Data Types and Expressions

Uploaded by

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

Inf1030 02 Data Types and Expressions

Uploaded by

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

2 Data Types

and
Expressions

1
Objectives
• Examine how computers represent data
• Declare memory locations for data
• Explore the relationship between
classes, objects, and types
• Use predefined data types
• Use integral data types

2
Objectives (continued)

• Use floating-point types


• Learn about the decimal data type
• Declare Boolean variables
• Declare and manipulate strings
• Work with constants

3
Objectives (continued)

• Write assignment statements using


arithmetic operators
• Learn about the order of operations
• Learn special formatting rules for
currency

4
Data Representation

• Bits
– Bit – "Binary digIT"
– Binary digit can hold 0 or 1
– 1 and 0 correspond to on and off,
respectively
• Bytes
– Combination of 8 bits
– Represent one character, such as the
letter A
– To represent data, computers use the
base-2 number system, or binary 5
number system
Binary Number System

Figure 2-1 Base-10 positional notation of 1326


6
Binary Number System
(continued)

Figure 2-2 Decimal equivalent of 01101001


7
Data Representation
(continued)

Table 2-1
Binary
equivalent
of selected
decimal
values

8
Data Representation
(continued)
• Character sets
– With only 8 bits, can represent 28, or
256, different decimal values ranging
from 0 to 255; this is 256 different
characters
• Unicode – character set used by C#
(pronounced C Sharp)
– Uses 16 bits to represent characters
– 216, or 65,536 unique characters, can be
represented
• American Standard Code for Information
Interchange (ASCII) – subset of Unicode 9
– First 128 characters are the same
Data Representation
(continued)

Table 2-2 Common abbreviations for data representations


10
Memory Locations for Data
• Identifier
– Name
– Rules for creating an identifier
• Combination of alphabetic characters (a-z
and A-Z), numeric digits (0-9), and the
underscore
• First character in the name may not be
numeric
• No embedded spaces – concatenate
(append) words together
• Keywords cannot be used
• Use the case of the character to your
advantage
• Be descriptive with meaningful names 11
12
Reserved Words in C#
(continued)
• Contextual keywords
• As powerful as regular keywords
• Contextual keywords have special
meaning only when used in a specific
context; other times they can be used as
identifiers

13
14
Naming Conventions

• Pascal case
– First letter of each word capitalized
– Class, method, namespace, and
properties identifiers
• Camel case
– Hungarian notation
– First letter of identifier lowercase; first
letter of subsequent concatenated words
capitalized
– Variables and objects 15
Naming Conventions
(continued)

• Uppercase
– Every character is uppercase
– Constant literals and for identifiers that
consist of two or fewer letters

16
Examples of Valid Names
(Identifiers)

Table 2-5 Valid identifiers


17
Examples of Invalid Names
(Identifiers)

Table 2-6 Invalid identifier


18
Variables
• Area in computer memory where a
value of a particular data type can be
stored
– Declare a variable
– Allocate memory
• Syntax
– type identifier;
• Compile-time initialization
– Initialize a variable when it is declared
• Syntax
– type identifier = expression;

19
Types, Classes, and
• Type
Objects
– C# has more than one type of number
– int type is a whole number
– Floating-point types can have a fractional
portion
• Types are actually implemented through
classes
– One-to-one correspondence between a class
and a type
– Simple data type such as int, implemented
as a class
20
Types, Classes, and
Objects (continued)
• Instance of a class → object
• A class includes more than just data
• Encapsulation → packaging of data and
behaviors into a single or unit→class

21
Type, Class, and Object
Examples

Table 2-7 Sample data types

22
Predefined Data Types
• Common Type System (CTS)
• Divided into two major categories

Figure 2-3 .NET common types


23
Value and Reference Types

Figure 2-4 Memory representation for value and reference types

24
Value Types

• Fundamental or primitive data types

Figure 2-5 Value type hierarchy


25
26
Integral Data Types

• Primary difference
– How much storage is needed
– Whether a negative value can be stored
• Includes number of types
– byte & sbyte
– char
– int & uint
– long & ulong
– short & ushort

27
28
Examples of Integral Variable
Declarations
int studentCount; // number of students in the
class

int ageOfStudent = 20; // age - originally initialized to


20

int numberOfExams; // number of exams

int coursesEnrolled; // number of courses enrolled


29
Floating-Point Types
• May be in scientific notation with an
exponent
• n.ne±P
– 3.2e+5 is equivalent to 320,000
– 1.76e-3 is equivalent to .00176
• OR in standard decimal notation
• Default type is double

30
Examples of Floating-Point
Declarations
double extraPerson = 3.50; // extraPerson originally set to
3.50

double averageScore = 70.0; // averageScore originally set


to 70.0

double priceOfTicket; // cost of a movie ticket

double gradePointAverage; // grade point average

float totalAmount = 23.57F; // note the F must be placed after


31
23.57
Decimal Types
• Monetary data items
• As with the float, must attach the suffix
‘m’ or ‘M’

• Examples
decimal endowmentAmount =
33897698.26M;
32
Boolean Variables

• Based on true/false, on/off logic


• Boolean type in C# → bool
• Does not accept integer values such as
0, 1, or -1
bool undergraduateStudent;
bool moreData = true;

33
Strings

• Reference type
• Represents a string of Unicode
characters
string studentName;
string courseName = "Programming
I";
string twoLines = "Line1\nLine2";

34
Making Data Constant

• Add the keyword const to a declaration


• Value cannot be changed
• Standard naming convention
• Syntax
– const type identifier = expression;

const double TAX_RATE = 0.0675;


const int SPEED = 70;
const char HIGHEST_GRADE = 'A';

35
Assignment Statements
• Used to change the value of the
variable
– Assignment operator (=)
• Syntax
variable = expression;
• Expression can be:
– Another variable
– Compatible literal value
– Mathematical equation
– Call to a method that returns a compatible
value
– Combination of one or more items in this list36
Examples of Assignment
Statements
int numberOfMinutes,
count,
minIntValue;

numberOfMinutes = 45;
count = 0;
minIntValue = -2147483648;

37
Examples of Assignment
Statements
char firstInitial,
yearInSchool,
punctuation,
enterKey,
lastChar;

firstInitial = 'B';
yearInSchool = '1';
punctuation = '; ';
enterKey = '\n'; // newline escape character
lastChar = '\u005A'; // Unicode character 'Z'
38
Examples of Assignment
Statements (continued)
double accountBalance,
weight;
bool isFinished;

accountBalance = 4783.68;
weight = 1.7E-3; //scientific notation may be
used

isFinished = false; //declared previously as a bool


//Notice – no quotes used
39
Examples of Assignment
Statements (continued)
decimal amountOwed,
deficitValue;

amountOwed = 3000.50m; // m or M must be suffixed


to
// decimal data types

deficitValue = -322888672.50M;

40
Examples of Assignment
Statements (continued)
string aSaying, fileLocation;

aSaying = "First day of the rest of your life!\n";


fileLocation = @ "C:\CSharpProjects\Chapter2";

@ placed before a string literal signals that the


characters inside the double quotation marks
should be interpreted verbatim --- No need to
use escape characters with @

41
Examples of Assignment
Statements (continued)

Figure 2-7 Impact of assignment statement


42
Arithmetic Operations
• Simplest form of an assignment
statement
resultVariable = operand1 operator
operand2;
• Readability
– Space before and after every operator

43
Basic Arithmetic
Operations

Figure 2-8 Result of 67 % 3


• Modulus operator with negative values
– Sign of the dividend determines the result
– -3 % 5 = -3; 5 % -3 = 2; -5 % -3
= -2; 44
Basic Arithmetic
Operations (continued)
• Plus (+) with string Identifiers
– Concatenates operand2 onto end of
operand1
string result;
string fullName;
string firstName = "Rochelle";
string lastName = "Howard";

fullName = firstName + " " + lastName;

45
Concatenation

Figure 2-9 String concatenation


46
Basic Arithmetic
Operations (continued)
• Increment and Decrement Operations
– Unary operator
num++; // num = num + 1;

--value1; // value = value – 1;


– Preincrement/predecrement versus post
int num = 100;
WriteLine(num++); // Displays 100
WriteLine(num); // Display 101
WriteLine(++num); // Displays 102
47
Basic Arithmetic
Operations (continued)
int num = 100;
WriteLine(num++ + " " + ++num);
// Displays 100 102

48
Basic Arithmetic
Operations (continued)

Figure 2-10 Declaration of value type variables


49
Basic Arithmetic
Operations (continued)

Figure 2-11 Change in memory after count++; statement executed


50
Basic Arithmetic
Operations (continued)

Figure 2-12 Results after statement is executed


51
Compound Operations
• Accumulation
– Variable on left side of equal symbol is used
once the entire expression on right is
evaluated

52
Basic Arithmetic
Operations (continued)
• Order of operations
– Order in which the calculations are
performed
• Example
– answer = 100;
– answer += 50 * 3 / 25 – 4;

50 * 3 = 150
150 / 25 = 6
6–4=2
100 + 2 = 102
53
Order of Operations

• Associatively of operators
– Left
– Right

54
Order of Operations
(continued)

Figure 2-13 Order of execution of the operators

55
Mixed Expressions
• Implicit type conversion
– Changes int data type into a double
– No implicit conversion from double to int

double answer;
answer = 10 / 3; // Does not produce
3.3333333

int value1 = 440,


anotherNumber = 70;
double value2 = 100.60;
// ok here 440.0 stored in value2
value2 = value1;
56
Mixed Expressions
int value1 = 440;
double value2 = 100.60;

value1 = value2; // syntax error as shown in Figure 2-


14

57
Mixed Expressions
(continued)
• Explicit type conversion
– Cast
– (type) expression
– examAverage = (exam1 + exam2 + exam3) /
(double) count;

int value1 = 0,
anotherNumber = 75;
double value2 = 100.99,
anotherDouble = 100;
value1 = (int) value2;
// value1 = 100
value2 = (double) anotherNumber;// value2 = 75.0
58
Formatting Output

• You can format data by adding dollar


signs, percent symbols, and/or commas
to separate digits
• You can suppress leading zeros
• You can pad a value with special
characters
– Place characters to the left or right of
the significant digits
• Use format specifiers 59
Formatting Output (continued)

60
Numeric Format Specifiers

Table 2-16 Standard numeric format specifiers


61
Numeric Format Specifiers
(continued)

Table 2-16 Standard numeric format specifiers (continued)

62
Custom Numeric Format
Specifiers

63
Table 2-17 Custom numeric format specifiers
Custom Numeric Format
Specifiers (continued)

Table 2-17 Custom numeric format specifiers (continued)

64
Width Specifier
• Useful when you want to control the
alignment of items on multiple lines
• Alignment component goes after the
index ordinal followed by a comma
(before the colon)
– If alignment number is less than actual size,
it is ignored
– If alignment number is greater, pads with
white space
• Negative alignment component places spaces
on right

WriteLine("{0,10:F0}{1,8:C}", 47, 14);


65
47 $14.00 //Right justifies values
Coding Standards

• Naming conventions
– Identifiers
• Spacing conventions
• Declaration conventions

66
Resources

Naming Guidelines for .NET –


http://msdn.microsoft.com/en-us/library/xzf53
3w0(VS.71).aspx
Guide to Megabytes, Gigabytes,
Terabytes… –
http://fixitwizkid.com/threads/your-guide-to-m
egabytes-gigabytes-terabytes-yottabyte-exab
yte-petabyte-zettabyte.8062/

67
Resources

Writing Readable Code –


http://software.ac.uk/resources/guides/writing-re
adable-source-code#node-131
C# Video tutorials –
http://www.programmingvideotutorials.com/csha
rp/csharp-introduction

68
Summary

• Memory representation of data


• Bits versus bytes
• Number system
– Binary number system
• Character sets
– Unicode

69
Summary (continued)

• Memory locations for data


• Relationship between classes, objects,
and types
• Predefined data types
– Integral, Floating-point, Decimal,
Boolean and String variables

70
Chapter Summary (continued)

• Constants
• Assignment statements
– Order of operations
• Formatting output

71

You might also like