Midterm Review CP264
26 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

During the execution pipeline, which step is responsible for removing comments from the code and resolving directives?

  • Compilation
  • Linking
  • Assembling
  • Preprocessing (correct)

Which of the following tasks is performed by the compiler during the execution pipeline?

  • Resolving constant arithmetic (correct)
  • Combining different object files into an executable
  • Replacing macros with their corresponding values
  • Converting assembly code into machine code

Which of the following is NOT a typical task of the linking stage in the compilation process?

  • Including library functions.
  • Combining object files.
  • Resolving external references.
  • Converting assembly code to object code. (correct)

In C programming, what is the primary difference between pass by reference and pass by value?

<p>Pass by reference allows modification of the original variable, while pass by value creates a copy. (C)</p> Signup and view all the answers

What is the role of assembling in the execution pipeline of a C program?

<p>To convert assembly code into object code. (C)</p> Signup and view all the answers

When working with multidimensional arrays in C, what is a key requirement when declaring a pointer to iterate through the array?

<p>The pointer must be declared as a pointer to an array with one less dimension than the original array. (C)</p> Signup and view all the answers

In C file operations, which mode would you use to open a file for both reading and writing, while also truncating the file to zero length if it exists?

<p>&quot;w+&quot; (D)</p> Signup and view all the answers

Consider a scenario where multiple data types need to share the same memory location to conserve memory. Which C construct is most suitable for this purpose, and what is a potential risk associated with its use?

<p>Union; risk of accidentally overwriting storage. (A)</p> Signup and view all the answers

When is it appropriate to use the arrow operator (->) to access members of a struct, as opposed to the dot operator (.)?

<p>When accessing the struct through a pointer. (A)</p> Signup and view all the answers

If a program attempts to access memory that has been previously freed, what type of error is most likely to occur?

<p>Segmentation Fault (B)</p> Signup and view all the answers

What is the primary difference between a while loop and a do while loop in C?

<p>A <code>do while</code> loop always executes at least once, while a <code>while</code> loop may not execute at all. (D)</p> Signup and view all the answers

In C, which memory region is primarily used for storing local variables and function call information during runtime?

<p>Stack Region (D)</p> Signup and view all the answers

When a function uses 'pass by value', what happens to the original argument passed into the function?

<p>A copy of the original argument is created, so the original remains unchanged. (A)</p> Signup and view all the answers

Which of the data types in C occupies the largest amount of memory?

<p>double (A)</p> Signup and view all the answers

If you need to store only positive integer values and want to maximize the range of possible values, which data type modifier would be most appropriate in C?

<p>unsigned (C)</p> Signup and view all the answers

In C, what is the purpose of the break statement within a switch statement?

<p>To exit the <code>switch</code> statement and continue with the code following it. (B)</p> Signup and view all the answers

What is the primary purpose of using pointers in C programming?

<p>To directly manipulate memory locations and pass variables by reference. (A)</p> Signup and view all the answers

In pointer arithmetic, what operation is typically performed when incrementing a pointer?

<p>The memory address pointed to by the pointer is increased by the size of the data type it points to. (A)</p> Signup and view all the answers

Considering the code snippet:

int a = 5;
int *p = &a;
int **pp = &p;
**pp = 10;

What is the final value of a after executing this code?

<p>10 (B)</p> Signup and view all the answers

Which of the following printf format specifiers is used to print an integer in hexadecimal format?

<p>%x (D)</p> Signup and view all the answers

What is the purpose of the strcpy function in C?

<p>To copy a string from a source location to a destination location. (C)</p> Signup and view all the answers

What is the key difference between strcpy and memcpy when handling strings in C?

<p><code>strcpy</code> stops copying when it encounters a null terminator, while <code>memcpy</code> copies a specified number of bytes regardless of null terminators. (C)</p> Signup and view all the answers

Given the following structure and code:

struct Point {
 int x, y;
};
struct Point p1 = {10, 20};
struct Point *ptr = &p1;
ptr->x += 5;
ptr->y = 5;

What are the values of p1.x and p1.y after executing this code?

<p>15 5 (A)</p> Signup and view all the answers

What will be the output of the following program?

#include <stdio.h>

void swap(int *a, int *b) {
 int *temp;
 temp = a;
 a = b;
 b = temp;
}

int main() {
 int x = 10, y = 20;
 swap(&x, &y);
 printf("%d %d\n", x, y);    // Line A
 return 0;
}

<p>10 20 (B)</p> Signup and view all the answers

When using scanf for user input, what is the purpose of delimiters in the format string?

<p>They are used to separate different input values and define the expected input structure. (D)</p> Signup and view all the answers

In the context of string operations, what does it mean for a string to be a 'subsequence' of another string?

<p>The string can be formed by deleting some characters from the other string without changing the order of the remaining characters. (A)</p> Signup and view all the answers

Flashcards

Preprocessing

Removes comments and handles directives like #include and #define.

Compilation

Transforms preprocessed code into assembly language, which is a more human-readable form of machine code.

Assembling

Converts assembly language into machine-readable object code.

Linking

Combines object code files and libraries to create a single executable program.

Signup and view all the flashcards

main() function

The starting point, every C program must have it.

Signup and view all the flashcards

Char

A data type representing a single character.

Signup and view all the flashcards

Int

A data type representing an integer (whole number).

Signup and view all the flashcards

Float

A data type representing a floating-point number (number with decimal).

Signup and view all the flashcards

While Loop

A loop that executes as long as a condition is true.

Signup and view all the flashcards

Free Memory

Releases allocated memory back to the system after its use, preventing memory leaks.

Signup and view all the flashcards

Pass by Pointer

Passing the memory address (location) of a variable to a function.

Signup and view all the flashcards

Pointer

A variable that stores a memory address.

Signup and view all the flashcards

Structure (Struct)

A composite data type that groups variables into a single record.

Signup and view all the flashcards

Data Structure Principles

Represent, organize, store, and operate on collections of data.

Signup and view all the flashcards

Struct Access Pitfalls

Arrow (->) is for pointers; dot (.) is for values.

Signup and view all the flashcards

Enum and Union Differences

Enum: readable names for integer constants. Union: shares same memory, be careful!

Signup and view all the flashcards

Enum

A named constant, assigns an integer value.

Signup and view all the flashcards

Declare <T> x

Declares a variable 'x' of type 'T'.

Signup and view all the flashcards

Declare <T> *pointer

Declares a pointer that can hold the memory address of a variable of type 'T'.

Signup and view all the flashcards

Set pointer = &x

Assigns the memory address of variable 'x' to the pointer.

Signup and view all the flashcards

Pointer Arithmetic

Accessing values by incrementing the memory address the pointer points to.

Signup and view all the flashcards

strcpy

Copies the source string, including the null terminator, to the destination.

Signup and view all the flashcards

memcpy

Copies a specified number of bytes from the source location to the destination.

Signup and view all the flashcards

String Iteration

Iterate through each character of a string until the null terminator ('\0') is encountered.

Signup and view all the flashcards

String Matching

Process to find occurrences of a given string (pattern) within another string.

Signup and view all the flashcards

Case Conversion

Changing characters from upper to lower case, or vice versa.

Signup and view all the flashcards

Arrays

Contiguous blocks of memory that store elements of the same data type, allowing for efficient random access.

Signup and view all the flashcards

Study Notes

  • CP 264 Midterm Review provided by Laurier Computing Society

Table of Contents

  • Review includes: compiling, data types, keywords, functions, characters, pointers, arrays, strings, file input/output, data structure principles, struct, union, enum, design & analysis introduction, recurrences, samples and tips.
  • Estimated review time for compiling data types, keywords, functions: 10-15 minutes.
  • Estimated review time for characters, pointers, arrays, strings, file input/output: 20-25 minutes.
  • Estimated review time for data structure principles, struct, union, enum: 20-25 minutes.
  • Estimated review time for introduction to design, analysis, recurrences: 10-15 minutes.
  • Estimated review time for samples and tips: 5-10 minutes.

Midterm Format & Expectations

  • The midterm exam is 40 minutes long and will be administered through a lockdown browser.
  • The exam is in person and closed book, conducted during class time.
  • The mark breakdown: 33% multiple choice (25 questions), 27% short answer (4 questions), and 40% coding questions (4 questions).
  • Covers weeks 1-4 content including assignments.
  • Multiple-choice questions will be based on end-of-lecture quizzes.
  • Review labs and assignments for coding help.
  • Understand concepts for short answers.

Compiling and C Background

  • Compilation eliminates all comments from code.
  • A C program must contain a main function.
  • The flow of control for a C program starts at the main function.
  • A directive affects your code.
  • Directives are resolved during preprocessing.
  • When declaring an array of size 5, the amount of memory reserved depends on the data type
  • The memory is reserved when the function is called
  • One difference between pass by reference and pass by value is that pass by reference can modify the original data, while pass by value works on a copy

Execution Pipeline

  • Preprocessing parses code, resolves comments and directives, and replaces macros.
  • Compilation converts the parsed code into assembly code and resolves constant arithmetic.
  • Assembling converts assembly code to object code for the machine.
  • Linking combines object files and libraries from different sources into an executable program.

Data Types

  • Four primitive data types in C include:
    • char which is 1 byte,
    • int (on 32-bit systems) which is 4 bytes,
    • float which is 4 bytes,
    • double which is 8 bytes.
  • Unsigned accounts for positive numbers and reserves the leftmost bit
  • Int is 4 bytes long
  • Short is 2 bytes
  • Long is 4 bytes

Types of Loops

  • "For" loops define iteration as an argument.
  • "While" loops iteration is condition-based.
  • "Do while" loops iteration is condition-based plus one.
  • "Go to" allows for deep interation or for a quicker return
  • "If, else if, else" are specific cases.
  • "Switch" is used if matching many cases.
  • Break returns execution out of the current scope
  • Continue will skip the current iteration and continue at the end of the current scope
  • It's important to be careful if break is not used with switch statements.

Memory Management

  • Text region holds compiled instructions for all processes.
  • Data Region holds global and static variables.
  • Stack Region holds runtime functions and scoped variable data.
  • Heap Region is for allocated memory throughout the program for arrays.
  • Memory leaks come from the heap region
  • Allocated memory is not freed after its use.
  • All available memory can be exhausted.
  • An attempt to excess freed memory will cause a segmentation fault
  • Stack overflow impacts the stack region
  • Excessively deep recursion or large arrays can cause stack overflow

Functions - Pass by

  • Pass by pointer (reference): It passes the pointer to the object; allowing access or modification to original data, caution must be applied
  • Uses the unary operator * to dereference the pointer to get the object pointed to.
  • Pass by value: It constructs a copy of the value in memory, so there's no change to the parameter passed; may cause performance overhead.

Pointers, CharString, File I/O

  • Given string operations and file I/O practice questions

Pointers and Referencing

  • Pointers: A variable stores the memory address of an object rather than the object itself.
  • Declare a pointer using <T> *pointer.
  • Assign the address of a variable x to a pointer using pointer = &x.
  • Pointer Arithmetic: Incrementing pointers increments the memory addresses it points to, useful in traversing arrays.
  • Relational arithmetic can be performed on pointers
  • Null Pointers point to nothing, while generic pointers can point to anything.

Arrays

  • Arrays are declared with type and size, and elements are placed contiguously in memory.
  • Multidimensional arrays can be declared by appending sizes, e.g., <T> arr[1][2].
  • Arrays can be iterated over using index or pointer arithmetic.
  • With multidimensional arrays, a pointer type array must be declared with 1 less dimension.
  • Arrays can be accessed via index *(x,y) using the formula *(p + y * columns + x).

I/O Functions

  • printf: Uses replacement formatting such as % + flag + width align + precision + size + conversion.
  • printf Flags include: "d" for integer, “f” for floating point decimal, and "x" for hex value.
  • scanf/sscanf uses replacement formatting to assign variables to input.
  • Place one-off delimiters to format the input accordingly.
  • scanf/sscanf Makes a formula to follow when scanning

String Operations

  • String functions:
    • "strcpy” copies source string into target location,
    • "memcpy” copies the memory contents to the target location.
  • String writing functions: iterate until hitting the end character "\0” or iterate over the length of the string.
  • String Matching: Determine if a string is a subsequence of another, or follows a certain pattern
  • String conversions: Can convert strings to upper or lower case and vice versa, and Shifting by a character

File Operations

  • Keywords include: fopen() and fclose().
  • File modes:
    • "r" for reading,
    • "w" for writing,
    • “a” for appending,
    • "r+" for updating,
    • "w+” creates/wipes file for update,
    • "a+" creates file for update and append.
  • File reading functions: fgets() for string of length ? , fgetc() for character, fscanf() for formatted input.
  • File writing functions: fputs() for strings, fputc() for character, fprintf() for formatted output.

Struct, Union, Enum, and Some Principles

  • Struct is a composite data type using zero or more nested entries; is defined using struct and declared in the header; can use init function/constructor method; accessible via arrow notation struct -> parameter; and passed by value to function.
  • Principles of Data Structures describe how an associated collection is represented, organized, stored, and operated on, with common operations being accessing and modifying, as well as other traversal, membership testing, insertion/deletion, statistics and sorting.
  • Arrow notation is used to access inner members and is reserved for the use of pointers
  • Dot notation is used to access members and is reserved for the use of values

Enum and Union

  • Enum is typically used to enumerate constants and assign integer values; allows for more readable code for days of the week, Boolean, etc.
  • Union conserves memory by allowing multiple different data types to share the same block; all entries share the same block, which can accidentally overwrite storage; acts as Wildcard that can sequentially hold different data types.

Complexity Analysis

  • Big O Notation measures the number of operations an algorithm will perform relative to input size.
    • O(1) means constant,
    • O(log n) means log-proportional,
    • O(n) means linearly proportional,
    • O(2^n) means exponentially proportional,
    • O(n!) means factorially proportional to input size.
  • Given 1-10 seconds, the recommended input sizes are > 10^9 for subsets of O(log n) or better, ~10^7 for subsets of O(n) or better, ~ 10^5 for subsets of O(n log n) or better, and ~ 10^3 for subsets of O(n^2) or better.
  • Asymptotic complexity analysis is an approximation for how an algorithm will perform with relatively large input size; serves as a guideline and a measure for efficiency on large scale inputs; however, it isn't an exact runtime, or number of operations an algorithm has.
  • HBF likes algorithm correctness, time complexities, and proof of correctness.
  • Algorithm Paradigms include: Dynamic Programming, Divide and Conquer, and Complete Search.
  • Dynamic Programming uses known solutions to solve larger problems with Memorisation (top down) and Tabulated (bottom up) approaches.
  • Divide and Conquer breaks larger problems down into smaller NON-overlapping problems.
  • Complete Search can be very slow.

Interactive Examples

  • General questions about strings, memory and grade calculator

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Untitled
110 questions

Untitled

ComfortingAquamarine avatar
ComfortingAquamarine
Untitled Quiz
6 questions

Untitled Quiz

AdoredHealing avatar
AdoredHealing
Untitled
6 questions

Untitled

StrikingParadise avatar
StrikingParadise
Untitled Quiz
50 questions

Untitled Quiz

JoyousSulfur avatar
JoyousSulfur
Use Quizgecko on...
Browser
Browser