6: Vectors
40 Questions
2 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

What does the line 'std::vector crossed_out = std::vector(n, false);' do?

  • Creates a vector of Booleans initialized to false. (correct)
  • Creates a vector of Booleans initialized to true.
  • Creates a vector of characters initialized to empty.
  • Creates a vector of integers initialized to zero.

The part 'for (int i=0; i < n; i++)' indicates that the loop will iterate n times.

True (A)

What is the primary purpose of a vector in programming?

To store a dynamically sized collection of elements.

In C++, a vector is part of the ________ Library.

<p>Standard Template</p> Signup and view all the answers

Match the following vector operations with their descriptions:

<p>Push_back = Adds an element to the end of the vector Pop_back = Removes the last element of the vector Size = Returns the number of elements in the vector Clear = Removes all elements from the vector</p> Signup and view all the answers

What does a precondition define in the context of a function?

<p>What is required to hold when the function is called (B)</p> Signup and view all the answers

The postcondition specifies what is required to be true before the function is called.

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

What happens if a function is called with invalid preconditions?

<p>Undefined behavior</p> Signup and view all the answers

The function 'pow' has a postcondition that guarantees the return value is ___ when the precondition is met.

<p>b^e</p> Signup and view all the answers

Which of the following is a recommended practice for defining preconditions?

<p>Ensure the precondition is as weak as possible (C)</p> Signup and view all the answers

Match the following terms with their definitions:

<p>Precondition = Requirements before function call Postcondition = Guaranteed outcomes after function call Undefined behavior = Results of invalid preconditions Overflow = Exceeding the limits of data representation</p> Signup and view all the answers

Weak postconditions provide the most detailed information available regarding a function's effects.

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

What should you document to help understand the function's behavior under its preconditions?

<p>Document the function's expected behavior and limitations.</p> Signup and view all the answers

If a function is called with preconditions not met, it may lead to ________ behavior.

<p>undefined</p> Signup and view all the answers

What is the primary goal when defining preconditions and postconditions for functions?

<p>To document expectations and maintain reasonable limits (B)</p> Signup and view all the answers

What is the consequence of using an assert statement with a false expression?

<p>It halts the program with an error message. (D)</p> Signup and view all the answers

Preconditions are always checked using assert statements.

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

What are the postconditions in the root function example?

<p>The result should return the larger root of the polynomial x^2 + p x + q.</p> Signup and view all the answers

The expression used in an assert statement must be convertible to ______.

<p>bool</p> Signup and view all the answers

Match the type of assertion with its purpose:

<p>Precondition = Checks validity before computation starts Postcondition = Checks correctness after computation finishes Invariant = Checks properties throughout method execution</p> Signup and view all the answers

What is the purpose of using assert statements in function 'pow'?

<p>To ensure the precondition holds when the function is called. (D)</p> Signup and view all the answers

In the gcd function example, the assertion 'assert(x > 0 && y > 0);' confirms that both inputs are non-negative.

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

Why is stepwise refinement important in programming?

<p>It simplifies problem-solving by breaking problems into smaller, manageable parts.</p> Signup and view all the answers

Using assertions helps to enforce ______ during program execution.

<p>correctness</p> Signup and view all the answers

Match the programming concept with its definition:

<p>Preconditions = Requirements that must be true before a function is executed Postconditions = Requirements that must be true after a function is executed Assertions = Statements that check conditions during runtime</p> Signup and view all the answers

What is the first step in the process of stepwise refinement?

<p>Create a coarse solution (D)</p> Signup and view all the answers

The refinement process only focuses on coding functions without considering data representation.

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

What is the purpose of stepwise refinement in programming?

<p>To break down a problem into smaller, manageable parts sequentially.</p> Signup and view all the answers

In the example problem, the rectangles are defined by their top-left corner coordinates and ______.

<p>dimensions</p> Signup and view all the answers

Match the rectangles with their respective properties:

<p>(x1, y1, w1, h1) = First rectangle with top-left corner at (x1, y1) (x2, y2, w2, h2) = Second rectangle with top-left corner at (x2, y2) w1 = Width of the first rectangle h2 = Height of the second rectangle</p> Signup and view all the answers

What is a critical factor to check when determining if two rectangles overlap?

<p>The position and dimensions of both rectangles (A)</p> Signup and view all the answers

The refinement process leads to the development of partial solutions that can be used in other problems.

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

In the main function of the coarse solution, what are the two main actions captured?

<p>Input rectangles and output the solution on overlap.</p> Signup and view all the answers

Width and height inputs for the rectangles may be ______.

<p>negative</p> Signup and view all the answers

Which of the following is NOT a step in the refinement process?

<p>Finalizing the program (D)</p> Signup and view all the answers

What is true about function declarations in programming?

<p>A function can only be used after its declaration in the code. (A)</p> Signup and view all the answers

A function's definition is never considered a declaration.

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

What must be true about the lines of code that follow a function declaration?

<p>They can use the function that has been declared.</p> Signup and view all the answers

The statement 'void B (int i);' is an example of a ___ declaration.

<p>separate</p> Signup and view all the answers

Match the following terms with their definitions regarding functions:

<p>Declaration = A statement that introduces a function's name and type Definition = A statement that includes the body of the function and implementation Precondition = A condition that must be true before a function is executed Postcondition = A condition that must be true after a function is executed</p> Signup and view all the answers

Flashcards

String

A sequence of characters. It can represent words, sentences, or any combination of text.

Vector

A data structure that stores a collection of elements in a specific order. Each element can be accessed using an index.

Boolean vector

A data structure that uses a Boolean value (true or false) to indicate whether a specific element is present or not.

Iterator

A variable that iterates over a range of numbers, often used in loops to perform operations on each element of a data structure.

Signup and view all the flashcards

Indexed data structure

A data structure that can be accessed in a specific order, using an index starting from 0 to n-1.

Signup and view all the flashcards

Precondition

A condition that must be true before a function is called. It defines the function's input limitations.

Signup and view all the flashcards

Postcondition

A condition that is guaranteed to be true after a function is called. It specifies the function's output and side effects.

Signup and view all the flashcards

Correctness

Ensuring that both the precondition and postcondition hold within the function. It ensures the function operates correctly.

Signup and view all the flashcards

Undefined Behavior

Describing the function's behavior when the precondition is not met. C++ refers to this as undefined behavior.

Signup and view all the flashcards

Weak Precondition

Making preconditions as general as possible to allow the function to work for a broader range of input values.

Signup and view all the flashcards

Strong Postcondition

Providing as much specific information as possible about the function's output after it's called.

Signup and view all the flashcards

White Lies

Approximations in pre- and postconditions due to limitations in the system and representation methods.

Signup and view all the flashcards

Abstraction

Compromise between formal correctness and practical needs by simplifying pre- and postconditions.

Signup and view all the flashcards

Function Documentation

Providing documentation that clarifies the function's behavior and limitations to avoid misunderstandings.

Signup and view all the flashcards

Reasonable Limits

Using common sense and reasonable judgment to document function behavior, recognizing that complete accuracy may be impractical.

Signup and view all the flashcards

Assertion

A programming technique that checks if a condition is true during program execution. If false, the program halts with an error.

Signup and view all the flashcards

Stepwise Refinement

A technique to simplify complex tasks in programming by breaking them down into smaller, more manageable steps.

Signup and view all the flashcards

How to guarantee preconditions in a function?

Ensuring that preconditions are met before executing a function.

Signup and view all the flashcards

Using assertions for preconditions and postconditions.

Assertions can be used to check preconditions, postconditions, and other critical program conditions.

Signup and view all the flashcards

Benefits of using assertions

Assertions can help identify possible errors in your code early, improving the reliability and maintainability of your programs.

Signup and view all the flashcards

What is the first step in using stepwise refinement?

To understand the problem and break it down.

Signup and view all the flashcards

Why are assertions important in programming?

Assertions are a powerful tool for debugging and preventing unexpected behavior in both preconditions and postconditions.

Signup and view all the flashcards

Whatare the potential drawbacks of assertions?

Code efficiency can be slightly impacted, and assertions are typically disabled in release builds..

Signup and view all the flashcards

Coarse Solution

A general representation of a solution, focusing on core elements without detailed implementation.

Signup and view all the flashcards

Function Implementation

The process of replacing abstract function calls in a solution with concrete code implementations.

Signup and view all the flashcards

Data Representation

Detailed descriptions of the data used in a program, including its structure and organization.

Signup and view all the flashcards

Problem Decomposition

The process of systematically breaking down a complex problem into smaller, more manageable sub-problems.

Signup and view all the flashcards

Function Declaration Scope

A function can only be used in lines of code that come after its first declaration in the program. This means you can't call a function before it's been defined.

Signup and view all the flashcards

Function Definition as Declaration

The definition of a function is always also a declaration. This means that when you define a function, it's automatically available for use in the rest of your program.

Signup and view all the flashcards

Separate Function Declaration

A function can have its scope expanded by using a separate declaration in the code. This allows the use of the function before its definition is encountered.

Signup and view all the flashcards

Function Prototype

A separate declaration of a function allows the function to be used before its definition is encountered. This is useful when the function definition is located in a different part of the program.

Signup and view all the flashcards

Function Declaration Syntax

The declaration of a function is placed outside any functions and is followed by a semicolon. It specifies the function's return type, name, and arguments.

Signup and view all the flashcards

Study Notes

Introduction to Computer Science

  • Course details: 252-0032, 252-0047, 252-0058
  • Authors: Manuela Fischer and Felix Friedrich
  • Department: Department of Computer Science, ETH Zurich
  • Semester: Fall 2024

Vectors

  • Vectors store sequences of homogeneous data.
  • Iteration over numbers: for (int i=0; i<n; ++i) {...}
  • Sieve of Erathostenes example: calculates prime numbers less than n.
  • Crossing out non-prime numbers using a boolean vector.
  • Vector type: std::vector<T> where T is the element type.
  • Vector initialization: std::vector<T>(n,e) where n is the number of elements and e is the initial value for each element. Other initialization methods (e.g., initializer lists) are possible.
  • Element access: [] index operator, used for reading and writing elements.
  • std::vector<int> v = std::vector<int>(10); std::cout << v.at(10); example shows accessing elements using .at(), which performs bounds checking at runtime. Using [] might cause undefined behavior if referencing outside container bounds.
  • Vectors can be initialized with different values (e.g., 0, 2, a direct list of values).

Memory Layout and Properties

  • Vectors store elements in contiguous memory.
  • Random access is efficient.

Nested Vectors (Vectors of Vectors)

  • Used to represent multidimensional structures like tables or matrices.
  • Can be initialized using initialization lists or filling with a specific size and default value.
  • Access elements using nested indexing: m[i][j] for row i and column j.
  • Memory storage is flat, row-by-row.
  • Example to compute sum of lower triangle of a square matrix using nested for loops.

Beware of Mixed Integer Expressions

  • Vector functions often use unsigned integers (e.g., v.size()).
  • Mixed integer expressions can lead to unexpected behavior (e.g., infinite loops due to unsigned arithmetic—common error).
  • Compiler warnings can help detect potential issues. Example for (int x = 0; a.size()-x-1 >= 0; ++x){ std::cout << x; } demonstrates an infinite loop (due to the unsigned nature of a.size() ).

Reference Types

  • Pass by reference: Parameter receives the address of the actual argument, allowing modifications to be reflected in the caller.
  • Pass by value: Parameter receives a copy of the actual argument, modifications do not affect the original argument.
  • Reference types are denoted by T& (e.g., int&, std::vector<double>&).
  • Reference variables act as aliases to the objects they reference. References must have an existing object to reference.
  • Return by reference: Function returns a reference, allowing modifications to the original argument directly. Use of reference return type leads to changes to the original object, like int& inc(int i) example.
  • Temporary objects: A reference to a temporary object can lead to undefined behavior. A reference must remain valid for the lifetime of the object it refers to. Example: int& foo(int i) { return i; }.

Const References (const T& )

  • Passing elements by constant reference (const T&): Prevents accidental modification of the passed object within the function, while still avoiding unnecessary copying of large objects.
  • Improves performance by avoiding unnecessary copying (especially for large objects). Example of computing vector average using const std::vector<double>& values which prevents modification.

Studying That Suits You

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

Quiz Team

Related Documents

Lecture 6: Functions II PDF

Description

This quiz focuses on the concept of vectors in computer science, covering their storage, iteration, and properties. It includes examples such as the Sieve of Eratosthenes and illustrates the use of nested vectors. Test your understanding of how vectors function and their application in programming.

More Like This

Vector Quiz
5 questions

Vector Quiz

EffusiveHeliotrope avatar
EffusiveHeliotrope
Chapter 6: Vectors Flashcards
15 questions
Computer Graphics Overview
8 questions
Physics 1 Quiz - BSc Computer Science 2024/25
32 questions
Use Quizgecko on...
Browser
Browser