Week 3 - Gemini Flashcards
(24 cards)
Explain the concept of a ‘block’ in C++ and its relation to variable scope.
A block is a sequence of statements enclosed in curly braces {}
. Variables declared inside a block have ‘block scope’, meaning they only exist and are accessible within that block (and any nested blocks). They are created upon entering the block and destroyed upon exiting.
What is the difference between ‘function scope’ and ‘block scope’?
Function scope typically refers to labels (like for goto
, though goto
is discouraged), which are visible throughout the function. Block scope applies to variables declared within any {}
block, limiting their existence and visibility to that block.
Describe a situation where using a switch
statement might be clearer or more efficient than a long chain of if-else if
statements.
A switch
statement is often clearer when you need to perform different actions based on the specific value of a single integer or character expression, especially when there are many possible constant values to check against. It directly jumps to the matching case
.
Why is the break
statement crucial in most switch
case blocks? What happens if it’s omitted?
break
exits the switch
statement after a case
block is executed. If omitted, execution ‘falls through’ to the statements in the next case
block, which is usually unintended behavior.
When is a do-while
loop guaranteed to execute its body at least once, unlike a while
or for
loop?
Because the condition in a do-while
loop (do { statements } while (condition);
) is checked after the loop body executes, ensuring the body runs at least one time, even if the condition is initially false.
Contrast the typical use cases for for
loops versus while
loops.
for
loops are often preferred when the number of iterations is known beforehand (e.g., iterating 0 to N-1, processing all elements of an array). while
loops are generally better when the loop should continue as long as a condition holds true, but the number of iterations isn’t known in advance (e.g., reading data until end-of-file, repeating until user enters a specific value).
Explain the difference in behavior between break
and continue
when used inside a loop.
break
immediately terminates the entire loop, and execution resumes after the loop. continue
skips the remainder of the current iteration only and proceeds to the next iteration’s condition check (and increment in a for
loop).
How can you create a loop that runs indefinitely until a specific condition inside the loop triggers an exit?
You can use while(true)
to create an infinite loop, and then use an if
statement inside the loop to check for the exit condition, executing a break
statement when that condition is met.
What is the purpose of ‘procedural abstraction’ when designing functions?
It means focusing on what a function does (its purpose and interface - parameters and return type) without needing to worry about the internal details of how it does it. This allows for modular design and makes code easier to use and maintain.
Explain the difference between a function parameter declared as int x
(pass-by-value) and int& x
(pass-by-reference).
With int x
(pass-by-value), the function receives a copy of the argument’s value; changes inside the function don’t affect the original. With int& x
(pass-by-reference), the function receives a reference (alias) to the original argument; changes inside the function do affect the original variable.
Why might pass-by-reference (&
) be preferred over pass-by-value for function parameters in certain situations?
- To allow the function to modify the original argument. 2. To avoid the overhead of copying large data structures (like complex objects or large arrays) when the function only needs to read them (though
const&
is better for read-only access).
What constitutes a function’s ‘signature’ in C++?
The function’s name combined with the number and types of its parameters. The return type is NOT part of the signature for overloading purposes.
How does the compiler resolve calls to overloaded functions (functions with the same name but different parameters)?
The compiler determines which version of the function to call based on the number and types of the arguments provided in the function call, matching them to the function signature.
If you call an overloaded function with argument types that don’t exactly match any signature, what might the compiler try to do?
The compiler may attempt to perform implicit type conversions (casting) on the arguments to find a suitable match. If no unique match can be found after considering conversions, it will result in a compilation error.
What is the key difference in the lifetime and initialization of a regular local variable versus a static
local variable within a function?
A regular local variable is created and initialized every time the function is called and destroyed when the function exits. A static
local variable is initialized only the first time the function is called and retains its value between calls, existing for the entire duration of the program’s execution after its first initialization.
Describe the process of splitting a C++ program into header (.h
) and implementation (.cpp
) files for a function. What goes where?
The header file (.h
) contains the function declaration (prototype) and any necessary includes, type definitions, or constants related to the function’s interface. The implementation file (.cpp
) contains the function definition (the actual code/body) and includes its own header file. The file calling the function includes the header file.
What is the purpose of the <iomanip>
library? Name two manipulators it provides.
It provides tools for formatting input and output streams. Examples: setw(n)
to set the field width, setprecision(n)
to set floating-point precision, setiosflags()
to set formatting flags like ios::left
or ios::fixed
.
What is the purpose of the <fstream>
library?
It provides classes for file stream operations, allowing programs to read from and write to files. Key classes include ifstream
(input), ofstream
(output), and fstream
(input/output).
Explain the role of ofstream
, ifstream
, and the open()
and close()
methods in file handling.
ofstream
is used to create output file streams (for writing). ifstream
is used to create input file streams (for reading). The open(filename, mode)
method associates the stream object with a physical file and specifies the mode (e.g., ios::out
, ios::in
, ios::app
). The close()
method disconnects the stream from the file.
How can a program detect when it has reached the end of a file while reading?
Using the eof()
member function of the ifstream
object (e.g., inputFile.eof()
). It returns true
if a read operation has attempted to read past the end of the file.
What is the difference between opening a file with ios::out
versus ios::app
?
ios::out
(default for ofstream
) opens the file for writing. If the file exists, its contents are discarded (truncated). If it doesn’t exist, it’s created. ios::app
opens the file for appending; output is added to the end of the file without deleting existing content. If the file doesn’t exist, it’s created.
What control structure is suitable for mapping a specific integer input (like a finger number 1-5) to a specific string output (like ‘Thumb’)? (Week 3 Problem 1)
A switch
statement is ideal here, checking the integer input against case
values 1 through 5 and outputting the corresponding name, with a default
case for invalid input. An if-else if
chain could also be used.
How would you structure a program that repeatedly calculates the square of a user-entered number until the user decides to exit? (Week 3 Problem 3)
Use a loop that continues indefinitely (e.g., while(true)
or for(;;)
). Inside the loop: 1. Prompt the user for a number. 2. Read the number. 3. Calculate and display the square. 4. Ask the user if they want to continue (e.g., enter ‘y’ or ‘n’). 5. Read the user’s choice. 6. If the choice indicates exit (e.g., ‘n’), use break
to exit the loop.
What key components are needed to sum all odd integers within a range specified by the user (e.g., from start
to end
)? (Week 3 Problem 4)
- Input: Read
start
andend
values from the user. 2. Initialization: Declare a sum variable and initialize it to 0 (int sum = 0;
). 3. Loop: Use afor
loop to iterate through numbers fromstart
toend
(for (int i = start; i <= end; ++i)
). 4. Condition: Inside the loop, use anif
statement to check if the current numberi
is odd (if (i % 2 != 0)
). 5. Accumulation: If the number is odd, add it to the sum (sum += i;
). 6. Output: After the loop, display the finalsum
.