CP264 Midterm Prep
CP264 Midterm Prep
Keywords
Program Structure
Imperative Programming: Statements executed strictly one after the other
Procedural Programming: Organizing statements into functions
C source program organized as sequence of functions
o Must contain main() function for executable function; execution of C program begins at
main() function
o Function contains logical sequence of statements
o Order matters when writing functions!
Can't call function A from function B if function A is declared after function B
After compiling, an executable program is organized in a sequence of blocks of functions
Program Structure Model:
Flow Control
Flow Control: Controls of orders of statements/instructions of executable programs
3 Basic Flow Control Structures:
1. Sequence Control: Executes program instructions in linear order of their appearances in
program (default)
2. Selection Control (aka Decision or Branching): Enables jump from one instruction to
another depending on condition
4 Decision Control Statements:
a. if statement
Note: Block scope braces {} can be eliminated if there's only one
statement block
Note: Can be compressed further to become
b. if-else statement
Ternary Operator: If condition is true, use expression1, else use
expression2
Syntax: condition? expression1 : expression
c. if-else-if statement
d. switch statement
3. Repetition Control (aka Loop): Executes block of statements over and over until certain
condition is satisfied
3 repetition statements:
a. for loop
b. while loop
executes condition first; if true, executes loop block
c. do-while loop
executes loop block first, then checks conditions
Data Types, Variables, Constants
Data Types
Data Type: Defines how certain type of values are represented and operated in programming
Used to inform compiler about:
o Type of data stored
o How much space in memory data recquires
o Operations that can be applied to data
8 Primitive Data Types:
o char
Uses 1 byte
Represents integers from -127 to 127
Uses ASCII to map integers from 0 to 127
RECALL: ‘A’ = 65; ‘a’ = ‘A’ + 32 = 97
o int
Uses 4 bytes
Represents integers from -231+1 to 2-31-1
First bit from the left is a sign bit (0 for positive, 1 for negative)
2 ways to store 4 byte int type in memory block of size 4:
Little-endian: Stores least significant byte in smallest address memory cell
Big-endian: Stores most significant byte in smallest address memory cell
o float
float types → 4 bytes for single precision floating point numbers
o double
double types → 8 bytes for double precision floating point numbers
o short
o long
o signed
o unsigned
Arithmetic operations applied to primary types
Keywords short, long, signed, and unsigned are modifiers for int type
o ∴ can't use them for arithmetic operations!! Can only use the primary types in purple
Data Type Size: Number of bytes needed to store data value of the type in memory
Value Range: Range of values data type can hold
Variables
Variable: Identifier of a data value in program; gets memory allocation at compile time and
instantiated at runtime
When compiler encounters statement of variable declaration and assignment of value to it:
o Variable is allocated a memory block with relative address at compile time that's
mapped to a memory location of a computer system at runtime
Size of memory block of variable is the size of the data type of the variable
o Variable is assigned a value in a source program
o Compiler generates instructions that write value to memory location of the variable at
runtime
Local Variable: Variable declared within code block enclosed by {}
o Can be used in block after its declaration
Global Variable: Variable declared outside a function
o Can be used in any function
o Relative memory location of variable is relative with beginning of scope
Constants
Constants: Fixed data values in programs
2 ways to define constants/read-only variables:
1. Preprocessor using #define
2. const keyword
Operations, Operators, Expressions, Operations
Operations & Operators
Arithmetic Operations: Operation of two operands by operator (e.g. a+b)
Constants operations and evaluations done by compiler
o Starts at right side; actual computing at compile time
Variable operations computed at runtime
o Compiler generates instructions to do operation at runtime
Expressions
Arithmetic Expressions: Consist of constants, variables, arithmetic operators, and parentheses
Compiler parses right side expression, evaluates, and converts it to sequence of instructions of
operations
Resulting Type of Arithmetic Operations:
o Two operands of same data type = result is in operands' data type
o Two operands of different data type = lower type operand converted to higher type
first, then do equation
Order: char, int, long, float, double
Overflow: Out of range data type after operation
(Floating Point) Underflow: Operation produces result smaller than smallest floating number of
float type
Correctness of Operation Computing -> Precision loss for each float/double type operation
Logic Operations
Relation Operation: Compares two operands by relational operator, return 1 if true, 0 otherwise
o
Bitwise Operations
Bitwise Operation: Operates on bit patterns (or binary numbers) at individual bit level
o Data types are unsigned data types including unsigned char, unsigned int, unsigned long
o Every bit of the types are involved in the operation
o Result of bitwise operation is the same type of its operands
Bitwise Expression: Consists of constants, variables, bitwise operators, and parenthesis;
constructed by bitwise operations
Unary Operators
Preprocessors
Preprocessor Directives: Line starts with #
Preprocessor resolves all preprocessor directives at preprocessing step of compiling
Commonly used case:
o Include files (#include)
o Macro definitions (#define)
o Conditional compilation (e.g. #ifdef)
Libraries
Library: Collection of predefined constants and functions, can be reused in creating new
programs
Notable libraries:
o stdio: Input/Output → standard device and file input/output functions
o stdlib: General Utilities → functions that don’t fit to other headers
o math: Mathematics → common mathematical functions
o string: String Handling → functions for string operations
o time: Date & Time → functions for determining time and date
Pointers
Pointer: Variable to hold memory address of another variable
Pointer is a tool to access data -
o Alternative method to access memory block and value stored at memory block
o Make it possible to do address operations to access data for data operations
o Address values of pointers are meaningful only at runtime
& Operator: Gets address of a variable instance
* Operator: Indicates a variable is a pointer; Gets/sets value stored at given address
Pointer Applications:
o Used in pass-by-references; allows output of multiple values from function through
function arguments
o Increases efficiency of accessing data for algorithms
o Enable dynamic memory allocation and management
o Used to implement complex data structures (e.g. linked lists, queues, stacks, trees)
Pointer Operations:
o Dereferencing Operation
Dereferencing: Gets/sets value pointed by a pointer
o Assignment Operation
Assignment: Assign value of one pointer or address of variable to another
pointer of the same type
Dereferencing can also be used to set values at memory location pointed by
pointer
o Add and Minus Operations
We can add an integer value c to a pointer, it increases the address by
sizef(data_type)*c
The size of the pointer matters in this case
o Increase and Decrease Operations
Pointers support increase and decrease by adding/subtracting an integer value k
Operation will increase/decrease address value by k times the size of the data
type of the pointer
Unary increment (++) and decrement (--) are supported
Note: Amount of increment/decrement is determined by size of pointer type
o Comparison Operations
Pointer comparisons are supported by using relational operators
Special Pointers:
o Null Pointers
Null Pointer: Pointer value for not pointing anywhere
Good programming practice to set NULL to pointer if you don't have a target to
point
o Generic Pointers
Generic Pointer: Pointer that has void type; can point at a variable of any type
Needs to be casted to a specific type when doing operations and
dereferencing
Syntax: void *ptr;
o Pointers to Pointers
Pointer to Pointer: Pointer set to point to another pointer
To declare, add * for each level of reference
Pointer Pros and Cons:
Pros Cons
Alternative way to access and operate data Difficult concept
Help to output multiple values from function Error prone, difficult to debug
through pass-by-reference
Cahn point to functions and pass function Uninitialized/wrong points cause
references to another function segmentation fault
Support dynamic memory allocation for data Dynamically allocated memory blocks need
objects to be freed explicitly to avoid memory leak
Increase program execution on data processing
Provide efficient tools for manipulating data
structures
Memory Allocations in C
Static Memory Allocation: Memory allocation done by declaration of global/static variables
o At compile time, global/static variable allocated memory block with relative address to
data region
o At runtime, statically allocated memory blocks are instanced with absolute addresses in
data region
o Size of data region determined by sum of sizes statically allocated memory blocks at
compile time and won’t be changes at runtime
Automatic Memory Allocation: Memory allocation done by function arguments/local variables
o At compile time, local/argument variable assigned memory block with relative address
to function scope
o At runtime, memory block of automatic allocation is put in stack region when function is
called and automatically released when function is finished
o Automatic release = memory release managed by program execution mechanism, not
program statements
Dynamic Memory Allocation: Memory allocation done by stdlib library funciton malloc()
o Memory block of dynamic allocation located in heap region; won’t be released
o Dynamically allocated memory block scan be shared by different functions
o Use free() function to release memory block
Arrays
Operations
Arrays: Data structure that stores collection of data items of the same type in contiguous
memory locations
Used to:
o Store application data records
o Store strings
o Implement other data structures (e.g. Queues, stacks, heaps, hash tales)
o Implement mathematical vectors, matrices, and rectangular tables
Static Method/Arrays: Allocates memory block in data/stack region at compile time
Dynamic Method/Arrays: Uses stdlib function malloc() to allocate memory space for array
Array Pointer: Pointer pointing to an array
o Declaration Syntax: data_type (*ptr_name)[k];
o If pointer ptr holds address of array element, ptr++ represents next element
Pointer Array (aka Array of Pointers): Array of pointer type elements
o Declaration Syntax: data_type *ptr_array_name[k];
Passing arrays to functions:
1. Passing by data values
Value of array element is copied to function
Array element won't be changed by function
2. Passing by element reference (address at runtime)
Address of array is copied into function
Through address, array element can be accessed and changed
3. Passing array by name (i.e. Passing address of the first element)
Passing array address to function
Application of arrays:
o Store collection of data items of the same type when maximum number of data items
are known and random access used in application
o Implement mathematical vectors, matrices, and other rectangular tables
o Implement other data structures like string, queues, stacks, hash tables, heaps
o Databases to store data tables
Array Data Structures
4 reasons why arrays are used to represent and store data in applications:
o Data objects (aka records) to be presented have the same type
o Maximum number of data records is known
o Many random access operations in applications
o Data objects have regular relationship like vector, table, and matrix
Array data structures stores sequence of data
Basic array data structure operations:
o Traverse: Access/visit every data record in the array
o Search: Find data record in the array by key value
o Insert: Add new data record in array
o Delete: Remove data record from array
o Merging two arrays
o Sort: Rearrange data records in ascending/descending order
Unions
Union: User-defined data type that can hold any variable of a given set of member variables at
the same memory location
o Can hold different types of values, but only one value at a time
Size of union is maximum size of its member types
Unions vs. Structures
Enumerations
Enumeration Type: User-defined data type to represent integral constants by symbols/names
o Enumeration type variable stored memory as int type
o sizeof enumeration data type = sizeof(int)
o int operations can be applied to enumeration type
enum: Keyword to define an enumeration type
Enumeration vs. Macro
o Advantage of enumeration over using #define is enum is a data type and can be used to
declare and do operations on variables
File I/O
File I/O: Data transfer between computer memory and hard disk
Data in memory: For processing and short term storage
o When computer turns off, data is gone
Hard Disks: Long term storage
o Data remains even if computer if off
File Output: Write data stored in computer memory to hard disk in forms of files so data can be
retrieved using file name
o Save data from memory to files in disk or other media for long term storage
File Input: Read data from disk into computer memory for processing
File I/O and OS
o File I/O requires kernel operations of operating systems (OS)
Writing data files in disks and accessing file data stored in disks need to access
and control disk
Disk accessing controls managed by OS
OS provides services for file I/O user application
OS Services are system calls
o Programming file I/O in C mostly use file I/O functions provided by stdio library
Programming file I/O in C can directly use OS's system caller BUT C stdio library
provides functions for file I/O
Stream Buffer: To transfer data between application's memory and file in disk stream buffer is
used as an intermediate buffer holding chunk of file data for batch transferring from/to disk
o File I/O functions do data transfer between application's memory and file stream buffer
o Data transfer between stream buffer and disk is managed by OS
2 file format types:
1. ASCII File (test file): Stores data as a sequence of characters
2. Binary File (stream file): Stores data as they are in memory blocks
When fopen() is called with filename and mode, it does the following:
1. Create I/O stream buffer connecting to file
2. Create FILE structure instance
3. Set pointe rbuffer pointing to stream buffer
4. Set curp pointer to beginning position of stream buffer and other fields of FILE structure
instance
5. Return NULL if one of the above operations fails, otherwise return FILE instance address
Data Structures
Data Structure: Collection of data values of certain types together with a set of specific
operations that can be performed
o Defines how data items are represented, organized, stored in memory, and operated
Data structure operations used to operate (access, modify, insert, delete) data values in data
structures
Selecting/designing efficient data structure is a crucial step in algorithm design/implementation,
the steps are:
1. Determine problem data and data representation
2. Determine basic operations that must be supported
3. Determine resource constraints for each operation
4. Select/design data structure that best meets requirements
Data Item/Object: Value or set of values
o Elementary Item: Data item that doesn't have subordinate data items
o Composite Item: Data item that has subordinate data items
Record: Group of data items
Collection of Records: Application of data
Data structures design involves the following concepts:
o Abstract Data Type
Abstract Data Type (ADT): Mathematical model for data whose behaviour is
defined by set of values and operations
Acts as guideline for implementing data type
Description of logical and mathematical properties of data
Specifies set of data objects to be represented and operations on data objects
Focuses on what it is and what it does, not how
Abstract: Away from the detailed implementations
o Data Type
Data Type: Implementation of ADT in programming language
Translates ADT's specification into detailed representation and operations and
syntax of programming language
Implementation of ADT contains detailed bit pattern representation of data
values and operations on bit patterns
Data type operations can be implemented by:
Hardware circuitry as part of computer CPU
Software implementation where programs interpret bit patterns to
perform operations
Data Type Categories:
Native Data Types: Set of data types directly supported by CPU for
manipulating bit pattern as binary numbers
Primary Data Types: Set of data types supported by program language
o Define how data will be internally represented, stored, and
retrieved from memory
Structure Data Types: Composite data type consisting of one or more
data members of various types
Three parts:
o Data Part: Contains data values of various data types
o Address Part: Stores runtime data location information of other
data objects
o Atomic Type: Structure data type that contains no address part,
only data items; ceases to be atomic when you load it into
memory
o Abstract Data Structure
Abstract Data Structure: Specification on representation and operations of
collection of data items
Data structure can be viewed as implementation of abstract data structure to
represent one or more data values of specific types in program
o Data Structure Operations
Basic data structure operations:
Accessing: Get value of any data element in data structure
Modification: Set value of data element
Commonly used data structure operations:
Traversal: Access each data element exactly once
Searching: Find location of one or more data elements that satisfy given
condition
Inserting: Add new data element to data structure
Deleting: Remove particular data element from data structure
Advanced data structure operations:
Sorting: Arrange data objects in ascending/descending order of keys
Merging: Combine two collections of data values into one data structure
o Application Specific Data Structures
Application algorithm uses data operations on abstract data types/structures
Application Specific Data Structures: Program to implement algorithm uses
existing data types to implement abstract data types/structures to create
algorithm specific data types/structures so operations can be efficient
When writing program to implement algorithm, it needs to use primitive data
types to implement abstract data types/structures to create algorithm specific
data types/structures so operations can be done specifically
Classification of Data Structures:
o Primitive Data Structure: Consist of single data element of primitive data type of
programming language
o Non-primitive Data Structure: Created using primitive data types
Linear Data Structure: Elements organized/stored in linear order
Can be represented in memory in two different methods:
Physically Ordered: Two adjacent elements stored adjacently in memory
(e.g. Arrays)
Virtually Linked: Linear relationship between elements define by links
(e.g. Addresses of next data elements
Example: arrays, linked lists, queues, stacks
o Non-linear Data Structure: Elements not organized in sequential order; data element
may connect to multiple data elements
Example: trees, graphs