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

02 - Unit 2. Data Types

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

02 - Unit 2. Data Types

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

UNIT 2 – REPRESENTING SIMPLE DATA IN

MEMORY
ARTURO S. GARCÍA PROGRAMMING FUNDAMENTALS 1
UNIVERSITY OF CASTILLA-LA MANCHA
DEGREE IN COMPUTER SCIENCE AND ENGINEERING.
2024-2025 ESII ALBACETE
CONTENTS

Data and identifiers

Data types

Operators and expressions

Pointers

2
DATA AND IDENTIFIERS

 What is Data?
 The raw information that a program processes and stores in memory.
 Characteristics defined by the programmer:
 Identifier.
 Type.
 Value.
 Characteristics assigned at declaration:
 Memory address in which data is stored.
 Scope.
3
DATA AND IDENTIFIERS

 Data
 Data representation in memory.
 Different views.
1 or 0

4
DATA AND IDENTIFIERS

 Data
 Data representation in memory

5
DATA AND IDENTIFIERS

 Data
 Example:

Memory
Identifier: age
0001 Type: integer
0002 00000022 Address: 0002
age 0003 Value : 22
Scope: global
0004

6
DATA AND IDENTIFIERS

 Data :: Identifiers
 Label or name that the programmer assigns to each individual data in order
to reference them later.
 General rules:
 Only letters, numbers and the underlined character (_) are allowed.
 The first character cannot be a number.
 Spaces or characters such as . ; * : - + etc. are not allowed.
 The identifiers have a maximum length of characters.
 They can’t coincide with the keywords of the language.
 Case sensitive: The upper- and lower-case letters are different.
7
DATA AND IDENTIFIERS

 Data :: Identifiers
 Label or name that the programmer assigns to each individual data in order
to reference them later.
 General rules:
 Only letters, numbers and the underlined character (_) are allowed.
 The first character cannot be a number.
Spaces or characters such as . ; * : - + etc. are not allowed.
I P


T
The identifiers have a maximum length of characters.
 They can’t coincide with the keywords of the language.
 Case sensitive: The upper- and lower-case letters are different.
8
DATA AND IDENTIFIERS

 Data :: Identifiers :: Examples


 2temperature WRONG: The first character is a number.
 _2temperature RIGHT
 “coordinate” WRONG : Not allowed characters ( “ ).
 Temperature-1 WRONG : Not allowed character ( - ).
 Temperature_1 RIGHT
 X Coordinate WRONG. Spaces not allowed.
 X_Coordinate RIGHT
 x_coordinate RIGHT
9
CONTENTS

Data and identifiers

Data types

Operators and expressions

Pointers

10
DATA TYPES

 A data type indicates three important characteristics:


 The amount of memory that will be used to store that data.
 The set of values that this data can take.
 The set of operators that can be applied to that data.
 All programming languages define a set of basic data types and
mechanisms for defining new types by aggregating simple ones
(composite data type or user-defined data type).

11
DATA TYPES

12
DATA TYPES

 Basic :: Character
 Keyword: char
 Stores a single symbol that will be represented internally by its ASCII code.
 Size in memory: 1 byte 8 bits. Range: -128 to 127 (signed) 0 to 255 (unsigned).
 Example: The character a will be represented as the symbol 'a' and the numeric
character 1 as '1'.
 Operators:
 Relational operators, also called comparison operators.
 Addition and subtraction of an integer.
 Several characters must be enclosed in double quotes "".
13
DATA TYPES

 Basic :: Character
 Keyword: char • Characters are internally represented as numbers in C.
• The computer maps each integer with the corresponding
 Stores a single symbol that will be represented internally by its ASCII code.
character using a numerical code.
 1 byte. • When we store a character in a char variable, we are actually
storing its number in the ASCII table.
 Example: The character a will be represented as the
• Think about symbol
the ASCII as theand
code'a' the
order numeric
in which the
character 1 as '1'. symbols are stored.
• The 48th symbol is ‘0’, which is not a number!
• You can use ‘0’ and the index 48 to refer to the same
symbol.
• Do not think ‘0’ is a number or you will get confused…

14
DATA TYPES

 Basic :: Character
 Another example:
 The character 'A' is assigned the value 65 in the ASCII table.
 In memory, the character 'A' is stored as an 8-bit sequence, with the values 01000001.
 The character '1' is assigned the value 49 in the ASCII table.
 In memory, the character '1' is stored as a sequence of 8 bits, with the values 00110001.
 Therefore, since they are stored as the index in the table (a number), you can
perform arithmetic operations with them that are, in principle, not very intuitive:

'A' + 1 = 'B' 65 + 1 = 66

15
DATA TYPES

 Basic :: Character
 Sometimes, it is necessary to use characters that cannot be typed or that
have a special meaning in the C language.

Use escape sequences

16
DATA TYPES
Escape sequence Description
 Basic :: Character
\' (single quote) Prints the single quote character (').
 Sometimes, it is necessary
\" (double quote) toPrints
use the
characters
double quotethat cannot
character ("). be typed or that
have a special meaning
\? (question mark) in the Prints
C language.
the question mark character (?).
\\ (backslash) Prints the backslash character (\).
\a (alert or bell) Cause an audible (bell) or visual alert.
\b (backspace) Move the cursor back one position on the current line.
\f (new page or form feed) Move the cursor to the start of the next logical page.
\n (newline)
Use Move the cursor to the beginning of the next line.
escape sequences
\r (carriage return) Move the cursor to the beginning of the current line.
\t (horizontal tab) Move the cursor to the next horizontal tab position.
\v (vertical tab) Move the cursor to the next vertical tab position.

17
DATA TYPES

 Basic :: Integer
 Keyword: int
 Stores integer values: numbers without decimals.
 The range of values allowed for this type will depend on the compiler being used,
normally:
 2 bytes for the storage the range of values are from -32768 to 32767.
 4 bytes for the storage the range of values are from -2,147,483,648 to 2,147,483,647.
 Relational operators and arithmetic operators can be applied to these data.

18
DATA TYPES

 Basic :: Floating-point:
 Store Real numbers, with decimals.
 4 bytes are usually used for storage.
 Relational and arithmetic operations can be applied (except the remainder
of the division operator).
 Two data types:
 Keyword: float: 4 bytes. -3.4e-38 to 3.4e+38.
 Keyword: double: 8 bytes. -1.7e-308 to 1.7e+308.

19
DATA TYPES

 Basic :: Floating-point:
CHAR_MAX : 127
CHAR_MIN : -128
 Store Real numbers, with decimals.
UCHAR_MAX : 255

 4 bytes are usually


INT_MAXused :for2147483647
storage.
INT_MIN : -2147483648
 Relational and arithmetic operations can be applied (except the remainder
LONG_MAX : 2147483647
LONG_MIN : -2147483648
of the division operator).
FLT_MAX : 3.40282e+038
 Two data types:FLT_MIN : -3.40282e+038
DBL_MAX : 1.79769e+308
 Keyword: float:
DBL_MIN4 bytes.
: -3.4e-38 to 3.4e+38.
-1.79769e+308
Storage size for int: 4
 Keyword: double:
Storage8 size
bytes. -1.7e-308
for long int: 4 to 1.7e+308.
Storage size for float : 4

Data size depends on the compiler!


20
DATA TYPES

 Basic :: Numeric datatypes : overflow and underflow


 Assigning a value that exceeds the upper limit is called overflow.
 Assigning a value that is smaller than the lower limit is called underflow.
 Examples: Size of char = 1 byte 256 different values
[-128 .. 127]

char c = 127; char c = -128;


c = c + 1; c = c - 1;

Value of c: -128 Value of c: 127

21
DATA TYPES

 Basic :: Numeric datatypes : overflow and underflow


 Examples:
 Imaging the lowest number that can be represented is 0,001.
 What would be the result of multiplying 0,004 * 0,004??
 0,004 * 0,004 = 0,000016
 Lower than 0,001!!
 Underflow!

22
DATA TYPES

 Basic :: Numeric datatypes : Modifying the basic types


 Applicable to char, int and double.
 Modifiers:
 short
 long
 signed
 unsigned
 Examples
 long int: 32 bits (4 bytes), [-2147483648 to 2147483647]
 unsigned long int: 32 bits (4 bytes), [0 to 4294967295]
 unsigned char: 8 bits (1 byte), [0 to 255]. signed char 8 bits (1 byte) [-128 to 127]

23
DATA TYPES

 Basic :: Boolean:
 The allowed values for data of this type are only two, TRUE and FALSE.
 Only Boolean operators (AND(&&), OR(||) and NOT(!)) can be applied to
this type of data.
 Not completely “built-in”. Alternatives:
 Traditional:
 int: Use integers: zero means false, nonzero means true.
 Only with compilers that support C99:
 _Bool. ‘0’ means false, ‘1’ means true.
 Including <stdbool.h>. ‘bool’, ‘true’ and ‘false’ can be used.
24
DATA TYPES

 Basic :: Pointer:
 A pointer is the memory address where the data is stored.
 A pointer variable is declared to hold a pointer to an object of a specified
type.
 Pointers are one of C's most powerful features, and they are used for a
wide variety of purposes.
 And one of the most complex features to master…

25
DATA TYPES

 Void data type:


 Keyword: void
 It's a special type of data.
 Used in functions.
 Interpreted as "nothing".

26
DATA TYPES

 Composite data types :: Homogeneous


 Array: Collection of variables of the same type that are referred to through
a common name.
Syntax: type name[size]; int days_per_month[12]; days_per_month[7] = 31;

days_per_month[0] days_per_month[4] days_per_month[8]


days_per_month[1] days_per_month[5] days_per_month[9]
days_per_month[2] days_per_month[6] days_per_month[10]
days_per_month[3] days_per_month[7] days_per_month[11]

Initialization: int days_per_month[12] = {31,28,31,30,31,30,31,31,30,31,30,31};

27
DATA TYPES

 Composite data types :: Homogeneous


 Array: Collection of variables of the same type that are referred to through
a common name.
Syntax: type name[size]; int days_per_month[12]; days_per_month[7] = 31;

 String: Null-terminated character array.


char str[6] = "hello"; ['h','e','l','l','o','\0']

28
DATA TYPES

 Composite data types :: Homogeneous


 Array: Collection of variables of the same type that are referred to through
a common name.
Syntax: type name[size]; int days_per_month[12]; days_per_month[7] = 31;

 String: Null-terminated character array.


char str[6] = "hello"; ['h','e','l','l','o','\0']
0 1 2 3
 Matrix: Two-Dimensional arrays. 0 1 2 3 4
1 5 6 7 8
Syntax: type name[rows][cols]; int d[3][4];
2 9 10 11 12

Initialization: int d[3][4] = { {1,2,3,4},{5,6,7,8},{9,10,11,12} }; 29


DATA TYPES

 Composite data types :: Heterogeneous


 Struct: Collection of variables referenced under one name, providing a
convenient way of keeping related information together.

struct address
{
char name[30];
char street[40];
char city[20];
int zip;
};

30
DATA TYPES

 Using the data types


 Literals:
 Represent specific values of each of the data types. 'a'
22
 Specific values not associated with a named memory location. "Hello world!"
 Constants:
 Refer to fixed values that, once defined, cannot be altered by the program.
 Constants can be of any of the basic data types. const int temperature = 22;
temperature = 20;
 Variables:
 A named location in memory used to hold a value that can be modified by the program.
 All variables must be declared before they can be used. int temperature = 22;
temperature = temperature – 1;

31
DATA TYPES

 Using the data types


 Variables: Good practices:
 Declare the variables 1 by 1, each on a different line. This makes it easier to read, change variable
names, or data types.
 Always initialize variables as soon as you define them, use an initial default value.
 Declare and initialize variables close to where you are going to use them. When the code is very long
it is easy to lose sight of the variable, which may have changed by accident, generating errors.
 Reset the variables you use as a counter or index each time you use them. A typical mistake is to
forget to reset counters.
 Each variable must have exactly one purpose. Don't try to “save" by reusing the same variable for 2
or more things.
 Be sure to use all the variables you declare. Or the other way around, don't declare variables you
don't use in the program.

32
CONTENTS

Data and identifiers

Data types

Operators and expressions

Pointers

33
OPERATORS AND EXPRESSIONS

 Expressions
 Valid combination of variables, constants, literals and operators.
 Generates a value.
 Operators:
 Assignment.
 Arithmetic
 Relational
 Logical

34
OPERATORS AND EXPRESSIONS

 Operators :: Assignment
 The assignment operator can be used within any valid expression.
 The general form of the assignment operator is:
variable_name = expression;

 Example: var a b
const int var = 43; 43 8 43
int a = 8; 39
int b = var;

a = b - 4;

Works from left to right only!!! 35


OPERATORS AND EXPRESSIONS

 Operators :: Assignment
 Multiple assignments
x = y = z = 0;

36
OPERATORS AND EXPRESSIONS

 Converting data types


 Implicit.
 Expressions: the largest type of all those involved.
double x = 2.5; The type of the expression is
int y = 3; double, and its value is 5.5

x + y;

 Assignment: the type of data in which the result is stored (left).


double x = 2.5;
int y = 3; The type of the expression is
int result; int, and its value is 5

result = x + y;
37
OPERATORS AND EXPRESSIONS

 Converting data types


 Explicit (aka Casting).
 You can force an expression to be of a specific type by using a cast. The general
form of a cast is:
(data_type) expression

 Examples:
double result; double result;
int a; int a;

a = 45; a = 45;
result = a / 2; result = ((double) a / 2);

result = 22.0 result = 22.5


38
OPERATORS AND EXPRESSIONS

 Converting data types


 Explicit (aka Casting).
 You can force an expression to be of a specific type by using a cast. The general
form of a cast is:
(data_type) expression

 Examples:
double result; double result;
int a; int a;

a = 45; a = 45;
result = a / 2; result = ((double) a / 2);

result = 22.0 result = 22.5


39
OPERATORS AND EXPRESSIONS

 Operators :: Arithmetic

Operator Action Example Meaning


- Subtraction, also unary minus (multiply by -1) a – b / –a a minus b / a negative
+ Addition a + b a plus b
* Multiplication a * b a multiplied by b
/ Division a / b a divided by b
% Modulus (remainder after integer division) a % b reminder of a / b
-- Decrement a-- a-1
++ Increment a++ a+1

40
OPERATORS AND EXPRESSIONS

 Operators :: Arithmetic
 ‘++’ and ‘--’
x = x + 1; is the same as x++; or x += 1;

x = x - 1; is the same as x--; or x -= 1;

 Both can be written:


x++; or ++x;

 Difference between the prefix and postfix forms:

x = 10; x = 11 x = 10; x = 11
y = ++x; y = 11 y = x++; y = 10
Prefix Postfix
41
y = (x++) (y = x)++
OPERATORS AND EXPRESSIONS

 Operators :: Arithmetic
 ‘/’ and ‘%’. Example:
int x, y, result;
x = 5;
y = 2;

result = x / y result = x % y

2 1

 ‘%’ can’t be used on floating-point types.


42
OPERATORS AND EXPRESSIONS

 Operators :: Relational

Operator Symbol Example Meaning


Equal to == x == y x is equal to y
Not equal to != x != y x is different from y
Greater than > x > y x is greater than y
Greater than or equal to >= x >= y x is greater than or equal to y
Less than < x < y x less than y
Less than or equal to <= x <= y x is less than or equal to y

43
OPERATORS AND EXPRESSIONS

 Operators :: Logical

Operator Symbol Example Meaning


AND && x && y x and y
OR || x || y x or y
NOT ! !x Not x (contrary)

44
OPERATORS AND EXPRESSIONS

 Operators :: Logical

Operator Symbol Example Meaning


AND && x && y x and y
OR || x || y x or y
NOT ! !x Not x (contrary)

zero means false


nonzero means true
45
OPERATORS AND EXPRESSIONS

 Operators :: Logical

Operator Symbol Example Meaning


AND && x && y x and y
OR || x || y x or y
NOT ! !x Not x (contrary)

P Q P && Q P || Q !P
false false false false true
false true false true true
true false false true false
true true true true false

46
OPERATORS AND EXPRESSIONS

 Operators :: Relational
 Examples: int i, j, k;
i = 1;
j = 2;
k = 3;

Expression Interpretation Value


i < j true 1
(i + j) >= k true 1
(j + k) > (i + 5) false 0
k != 3 false 0
j == 2 true 1

47
OPERATORS AND EXPRESSIONS

 Operators :: Relational
 Examples:

Pay attention to the difference!


int temperature1 = 24;
int temperature2 = 20;
int value1, value2;

value1 = temperature1 == temperature2; // value1 is 0 (false)


value2 = temperature2 <= temperature1; // value2 is 1 (true)

48
OPERATORS AND EXPRESSIONS

 Operators :: Logical
int i;
 Examples: char c;
double f;
i = 7;
c = 'w';
f = 5.5;

Expression Interpretation Value


(i >= 6) && (c == 'w') true 1
(i >= 6) || (c == 119) true 1
(f < 11) && (i > 100) false 0
(c != 'p') || ((i + f) <= 10) true 1
!(i == 7) false 0

49
OPERATORS AND EXPRESSIONS

 Operators :: Operators precedence in C


Operator category Operators
Postfix () [] -> . ++ --
Unary operators - ++ -- ! sizeof(type)
Arithmetic multiply, divide and remainder * / %
Arithmetic add and subtract + -
Relational operators < <= > >=
Equality operators == !=
Logical and &&
Logical or ||
Conditional operator ?:
Assignment operators = += -= *= %=

TIP: Use brackets! 50


OPERATORS AND EXPRESSIONS

 Operators :: Precedence of operators


 Examples:
int i;
char c;
double f;
i = 7;
c = 'w';
f = 5.5;

Expression Interpretation Value


i + f <= 10 false 0
i >= 6 && c == 'w' true 1
c != 'p' || i + f <= 10 true 1

51
OPERATORS AND EXPRESSIONS

 Operators :: Precedence of operators


 Examples:
int i;
char c;
double f;
i = 7;
c = 'w';
f = 5.5;

Expression Interpretation Value


(i + f) <= 10 false 0
(i >= 6) && (c == 'w’) true 1
(c != 'p') || ((i + f) <= 10) true 1

52
CONTENTS

Data and identifiers

Data types

Operators and expressions

Pointers

53
POINTERS

 In programming, variables are containers that are used to store data


in the computer's memory.
 Each variable has a name, a data type and a value that can change
during program execution.
 Moreover, they are stored at a specific memory address.
Memory
Identifier: age
0001 Type: integer
0002 00000022 Address: 0002
0003 Value : 22
Scope: global
0004

54
POINTERS

 A pointer is a variable that represents the location (rather than the


value) of a data item.

location memory address

 The general form of a pointer is:


data_type *variable_name; int *ptr;

This indicates to the compiler that ‘variable_name’ will


hold a pointer to a ‘data_type’.
55
POINTERS

 A metaphor to illustrate a pointer: The Library Index Book


 Imagine a pointers as a "Library Index Book". The library index book doesn't
contain the books themselves, but it has a detailed list of all the books in the
library along with their exact locations.
 The library is the computer's memory, where all the books (data) are stored.
 Each book is a piece of information (like a variable) that resides at a specific location in the
library (memory).
 When you need to find a particular book, you consult the "Library Index Book“
for its location instead of searching through the entire library.
 The "Library Index Book" provides you with the precise location (pointer) of the
book you're looking for.
Key Point: 56
A pointer is like an index entry that tells you where to find the data in memory, not the data itself.
POINTERS

 Operators :: Pointers
 Once the variable is defined, then we have two operators we can use:

Operator Symbol Example Meaning


The value of the data located at the
Get value at memory address * *m
address stored in the variable ‘m’.
Get memory address & &m The memory address of the variable ‘m’.

57
POINTERS

 Operators :: Pointers
 Example: int count = 0;
int *m;
m = &count;
 Places into ‘m’ the memory address of the variable ‘count’.
int q;
q = *m;
 Places the value of ‘count’ into the variable ‘q’.

58
POINTERS

 Example: int val_temperature; val_temperature = 22;


int *ptr_temperature; ptr_temperature = &val_temperature;
int value; value = *ptr_temperature;

Identifier: ptr_temperature
memory Type: pointer
0001:2000 0001:223A Storage address: 0001:2000
0001:2001 Scope: global
0001:2002
Value: 0001:223A

0001:2003

Identifier: val_temperature
0001:223A 00000022 Type: integer
0001:223B Storage address: 0001:223A
0001:223C
Scope: global
Value: 22
59
0001:223D
POINTERS

 Dynamic memory allocation


 Manage the memory dynamically without the need to define variables to
reserve the memory and then obtain its address.
 The basic form of the operator is:
pointer = malloc(amount_of_memory);

 The memory allocated needs to be freed when it is not needed anymore:


free(pointer);

 It is especially important to free up memory if many allocations are done in a loop.


 We can run out of memory!
60
POINTERS

 Dynamic memory allocation


 Example:
int *p;
p = malloc(50 * sizeof(int)); memory
p 0001:2000 0001:223A
… …
0001:223A
0001:223B
50 slots 0001:223C
… …
0001:226C

61
POINTERS

 Dynamic memory allocation


 TIP:
 The operator ‘malloc’ returns ‘0’ if it was not possible to allocate the memory.
 We should check that before using the pointer.
 Avoids using null pointers, which is a common mistake.

62
POINTER RULES SUMMARY

 No matter how complex a pointer structure gets, the list of rules remains
short.
 A pointer stores a reference to its pointee (variable the pointer refers to).
 The pointee, in turn, stores something useful.

 The * operation on a pointer accesses its pointee. A pointer may only be accessed
after it has been assigned to refer to a pointee.
 Most pointer bugs involve violating this one rule.
 Allocating a pointer does not automatically assign it to refer to a pointee.
 Assigning the pointer to refer to a specific pointee is a separate operation which is easy to
forget.
 Assignment between two pointers makes them refer to the same pointee, which
introduces sharing.

63

Taken from: http://cslibrary.stanford.edu/102/PointersAndMemory.pdf


END.

You might also like