Wk2-6 Content Flashcards
What is the primary focus of procedural programming?
Focusing on a specific aim or end result with limited reusability.
How do procedures (or functions) in procedural programming relate to the main() function?
They are declared/defined independent of main() and called within the program.
What is the main() function in C++ compared to Java?
In C++, main() is a standalone function that returns an int, whereas in Java, it is a static public member of a Runnable class.
What does the return value of 0 typically indicate in a C++ program?
It typically means a normal termination of the program.
Describe the basic structure of a C++ ‘Hello World!’ program.
The program includes function arguments, a return_type, and outputs ‘Hello World!’.
What is the role of #include in C++?
It brings in a header, like iostream, effectively a collection of code written elsewhere.
How do input/output streams work in C++?
Using cin for input and cout for output, with operators like «_space;for insertion.
Explain the difference between literals and variables in C++ output.
Literals have fixed explicit values, whereas variables do not.
What is the significance of using namespace std in C++?
It allows for shorter syntax but can lead to name collisions.
How is scope defined in C++ and what is its importance?
Scope is the context where a variable is visible and is defined by braces {}.
What does the term ‘global scope’ mean in C++?
A variable or entity is visible anywhere in the file after its declaration.
Can main() in C++ have arguments? If yes, what are they?
Yes, int main(int argc, char *argv[]) where argc is the argument count and argv is an array of arguments.
What is the purpose of the stoi function in C++?
It is used to convert strings to integers.
What is a forward declaration in C++?
Declaring a function before defining it, typically before reaching main().
Why is it advantageous to spread code across multiple files in C++?
It helps in organizing code, reusing functions, and easing debugging.
What is the purpose of header (.h) files in C++?
To declare data structures and function prototypes for use in other files.
How does the C++ library cmath enhance programming capabilities?
It provides access to mathematical functions, like square root.
Is it necessary to include a return statement in C++ functions?
While it can be omitted, it is best practice to include it for clarity.
What are the advantages of using functions in procedural programming?
Code reusability, ease of maintenance, and improved program structure.
What is the difference between signed and unsigned types in C++?
Signed types can represent both positive and negative values, while unsigned types represent only non-negative values.
How is the input/output functionality implemented in C++?
Through iostream library, using cin for input and cout for output.
What is the role of endl in C++?
It is a manipulator used to insert a newline character and flush the output buffer.
What does the term ‘unstructured code’ refer to in C++?
Code written without using functions or procedures, often in a sequential manner.
How does the concept of namespaces improve code organization in C++?
Namespaces prevent name collisions and organize code into logical groups.
How do you declare a pointer to an integer in C++?
int* ptr;
This declares a pointer ptr that can point to an integer.
What are control structures in C++ used for?
Control structures are used to dictate the flow of control in a program.
What is the syntax of a simple if statement in C++?
if (condition) { statements }
How does an if-else structure work in C++?
It executes the if block if the condition is true, else executes the else block.
In a C++ if-else-if ladder, how is the condition evaluated?
The conditions are evaluated in sequence and the block for the first true condition is executed.
How do logical operators work in control structures in C++?
Logical operators like AND, OR, and NOT are used to combine or invert conditions.
What is the NOT logical operator in C++ and how is it used?
The NOT operator (!) inverts the truth value of a condition.
How does the AND operator (&&) function in C++ conditions?
It returns true if both conditions are true.
What is the role of the OR operator (||) in C++?
It returns true if at least one of the conditions is true.
Describe the switch-case control structure in C++.
It allows the execution of one out of multiple blocks of code based on a variable’s value.
When is a switch-case structure more suitable than if-else?
When there are multiple outcomes based on the value of a single variable.
What are the types of loops available in C++?
Pre-test (for, while) and post-test (do-while) loops.
What is the significance of the for loop in C++?
The for loop provides a concise way of writing the loop structure.
How do you write a for loop in C++?
for (initialisation; condition; update) { // statements }
What is a variation of the for loop in C++?
Using multiple initialization expressions or omitting parts of the loop syntax for different behaviors.
What is an infinite loop in C++ and how is it written?
An infinite loop continues forever and can be written as for (;;) { // statements }.
How does the range-based for loop work in C++?
It iterates over elements in a range, like in an array or a container.
What is the basic structure of a while loop in C++?
while (condition) { // statements }
How does the do-while loop differ from the while loop in C++?
The do-while loop executes its statements at least once before checking the condition.
What is the importance of loop control in C++?
It helps in executing a set of statements repeatedly based on a condition.
How can you terminate a loop prematurely in C++?
Using the break statement.
What is the purpose of the continue statement in loops in C++?
It skips the current iteration and moves to the next iteration of the loop.
How do you ensure a loop does not become infinite in C++?
By ensuring the loop condition will eventually become false.
What is a nested loop in C++?
A loop inside another loop, allowing for more complex iterative processes.
How can control structures impact the readability of a C++ program?
Proper use of control structures can make a program easier to understand and maintain.
What are the advantages of using control structures effectively in programming?
They allow for better organization, flexibility, and efficient flow control in a program.
What is a pointer in C++?
A pointer is a variable that stores the memory address of another variable.
How do you declare a pointer in C++?
A pointer is declared using the asterisk () symbol, e.g., int ptr;
What is the use of the & operator in C++?
The & operator is used to obtain the memory address of a variable.
How do you assign a value to a pointer in C++?
By using the & operator on a variable, e.g., ptr = &var;
What is the role of the * operator when used with pointers?
The * operator is used to access the value at the memory address pointed to by the pointer.
How do you declare a reference in C++?
A reference is declared using the & symbol next to the type, e.g., int& ref = var;
What is the difference between a pointer and a reference?
A pointer can be reassigned to point to different addresses, whereas a reference always refers to the same object it was initially assigned.
What are arrays in C++?
Arrays are collections of elements of the same type, stored in contiguous memory locations.
How do you declare an array in C++?
An array is declared by specifying the type, followed by square brackets containing the size, e.g., int arr[10];
What is dynamic memory allocation in C++?
Dynamic memory allocation allows allocating memory during runtime using operators like new and delete.
How does the new operator work in C++?
The new operator allocates memory on the heap for a variable and returns a pointer to it.
What is the delete operator in C++?
The delete operator frees up the memory allocated by new when the memory is no longer needed.
How do you create a dynamic array in C++?
A dynamic array is created using the new keyword, followed by the type and size, e.g., int* arr = new int[size];
What is a memory leak in C++?
A memory leak occurs when dynamically allocated memory is not released back to the system using delete.
How do you initialize an array in C++?
An array is initialized by enclosing the initial values in curly braces, e.g., int arr[] = {1, 2, 3};
What is the significance of const in C++?
const is used to declare variables whose value cannot be changed after initialization.
How do you pass an array to a function in C++?
Arrays are passed to functions by passing the name of the array, which is a pointer to its first element.
What is the difference between passing by value and passing by reference?
Passing by value creates a copy of the variable, while passing by reference allows the function to modify the original variable.
How do you allocate memory for a multi-dimensional array in C++?
By using the new keyword with the required dimensions, e.g., int** arr = new int*[rowSize]; for each row, arr[i] = new int[colSize];
What is the null pointer in C++ and how is it used?
A null pointer points to nothing and is used to indicate that a pointer does not point to any valid memory location.
What is pointer arithmetic in C++?
Pointer arithmetic involves adding or subtracting integers to or from pointers, which moves the pointer to different memory addresses.
How do you deallocate a dynamic array in C++?
By using delete[] followed by the array name, e.g., delete[] arr;
What is the size of a pointer in C++?
The size of a pointer in C++ is dependent on the architecture, typically 4 bytes on a 32-bit system and 8 bytes on a 64-bit system.
How do you use a void pointer in C++?
A void pointer can point to any data type, but it cannot be dereferenced directly without typecasting.
What are the advantages of using dynamic memory allocation?
Dynamic memory allocation allows for flexible management of memory and can allocate memory as needed during runtime.
What is a struct in C++ and how is it used?
A struct is a user-defined data type that groups related variables of different data types.
How do you define a struct in C++?
A struct is defined using the struct keyword followed by structure name and definition.
What are the primary differences between a struct and a class in C++?
The main difference is that struct members are public by default, whereas class members are private.
How can you access elements of a struct in C++?
Elements of a struct are accessed using the dot (.) operator.
What is a union in C++?
A union is a special data type that allows storing different data types in the same memory location.
When is it appropriate to use a union in C++?
Use a union when you need to store one of many objects of different types but never simultaneously.
What is the difference between struct and union in terms of memory usage?
Struct allocates separate memory for each of its members, whereas union shares the same memory for all its members.
How do you initialize an empty vector in C++?
std::vector<int> v; or std::vector<int> v{};</int></int>
What is randomness in programming and how is it achieved in C++?
Randomness in programming refers to generating unpredictable results, achieved in C++ using the library.
How do you generate random numbers in C++?
Use the default_random_engine and distribution classes from the library to generate random numbers.
What is a probability distribution in C++?
A probability distribution is a function that describes the likelihood of obtaining the possible values of a random variable.
What are the common types of probability distributions in C++?
Common types include uniform, normal, binomial, and exponential distributions.
How do you include file handling capabilities in C++?
Include the library to use file streams for file handling in C++.
What are the different types of file streams in C++?
The primary file streams are ifstream for reading, ofstream for writing, and fstream for both reading and writing.
How do you open a file in C++?
Use the open() method of the file stream object with the file name as an argument.
How do you close a file in C++?
Use the close() method of the file stream object.
What is the importance of checking the status of a file stream in C++?
Checking the status helps to ensure that file operations like opening, reading, and writing are successful.
How do you read data from a file in C++?
Use extraction operators (») or getline() function with ifstream objects to read data.
How do you write data to a file in C++?
Use insertion operators («) with ofstream objects to write data to a file.
What are text files and binary files in C++?
Text files store data in readable text format, whereas binary files store data in binary format.
What are the advantages of using binary files over text files?
Binary files are more efficient in terms of storage and performance as they involve direct data writing and reading.
How do you handle errors during file operations in C++?
Use file stream’s fail(), bad(), and eof() methods to check for different types of errors.
What is buffering in file I/O and why is it used?
Buffering is the temporary storage of data during file I/O to enhance performance by reducing the number of direct disk accesses.
What is the role of the std namespace in C++?
The std namespace includes features of the C++ Standard Library to avoid naming conflicts.
How do you read and write complex data types to a file in C++?
Serialize complex data types into a format suitable for file I/O, such as converting objects into byte streams for binary files.
What is an exception in C++?
An exception is an unusual occurrence during execution, often representing errors.
How do you throw an exception in C++?
Use the ‘throw’ keyword followed by an exception object or value.
What is the purpose of a try block in C++?
A try block encloses code that might throw an exception.
How do you catch an exception in C++?
Use a catch block following a try block to handle exceptions.
What types of exceptions can be thrown in C++?
Any type, including basic data types or objects.
How does exception handling improve C++ programs?
It separates error handling from regular code, improving readability and reliability.
What happens if an exception is not caught in C++?
The program terminates and the default handler is invoked.
Can multiple exceptions be caught in C++?
Yes, by using multiple catch blocks for different exception types.
What is a namespace in C++?
A namespace is a declarative region that provides a scope to identifiers.
How do you declare a namespace in C++?
Using the ‘namespace’ keyword followed by the namespace name and a block of code.
What is the purpose of the std namespace in C++?
It contains standard library functions and avoids name conflicts.
How can you use elements from a namespace in C++?
By using the scope resolution operator (::) or the ‘using’ directive.
What is the syntax to use a specific element from a namespace?
namespace_name::element_name
Can namespaces be nested in C++?
Yes, namespaces can be defined within other namespaces.
What are unnamed or anonymous namespaces?
Namespaces without a name, used for defining items with internal linkage.
What is the advantage of using namespaces?
They help avoid name conflicts and organize code logically.
How can you create an alias for a namespace?
Using the syntax ‘namespace alias = existing_namespace;’
Why is exception handling preferred over traditional error handling in C++?
It provides a cleaner and more flexible way to handle errors and exceptions.
Can a catch block rethrow an exception in C++?
Yes, using the ‘throw;’ statement within a catch block.
What is exception propagation in C++?
The process by which an exception is passed up the function call stack until caught.
How do you initialize a vector with specific values (e.g., 1, 2, 3, 4, 5)?
std::vector<int> v = {1, 2, 3, 4, 5};</int>
What are standard exception classes in C++?
Classes like std::runtime_error, std::logic_error, and their derived classes.
How do you handle exceptions from standard library functions?
By enclosing library calls in a try block and catching exceptions.
What is the significance of exception specifications in C++?
They declare which exceptions a function might throw, but are not recommended in modern C++.
How do namespaces and exceptions collectively enhance C++ programming?
Namespaces organize code and avoid conflicts, while exceptions provide robust error handling.
What is defensive programming in C++?
A methodology aimed at improving software and source code quality.
What are some key practices in defensive programming?
Consistent indentation, meaningful error messages, and handling all possible input cases.
Why is consistent indentation important in C++?
It makes the source code easier to read and debug.
What is the role of the default case in a switch statement in C++?
It acts as a catch-all for any cases not explicitly handled.
What is the significance of time handling in C++ programming?
Time handling is important for operations like timeouts, delays, and measuring durations.
What are the main time types defined in C++?
Clocks, time points, and durations.
How do you make a C++ program wait for a specified time?
Use std::this_thread::sleep_for with a duration, like std::chrono::seconds or milliseconds.
What are some common time durations used in C++?
Hours, minutes, seconds, milliseconds, microseconds, nanoseconds.
What does preprocessing in C++ involve?
It includes operations like file inclusion, macro definition, and conditional compilation.
What is the syntax for defining a macro in C++?
define MACRO replacement-text.
What is the use of #define in C++?
It is used for defining macros, often for constants or compiler directives.
How do you use extern keyword in C++?
extern is used to indicate a variable is defined elsewhere.
What are predefined macros in C++?
Macros like __TIME__, __DATE__, __LINE__, __FILE__, and __func__ for debugging purposes.
How do you compile C++ code with debugging enabled?
Use the -DDEBUG flag with the g++ compiler.
What is the use of a Makefile in C++?
A Makefile automates the build process, specifying how to compile and link the program.
What is the GNU Project Debugger (gdb) in C++?
A debugger that helps in examining what is happening inside a program while it runs.
How do you run a program in gdb?
Use the command ‘gdb program_name’ followed by ‘run’.
What is the purpose of breakpoints in debugging?
Breakpoints allow pausing program execution at specific points to examine the current state.
How can you print a variable’s value in gdb?
Use the ‘print variable_name’ command in gdb.
What is the importance of clearing the cin buffer in C++?
Clearing the cin buffer prevents unwanted input from affecting subsequent reads.
What is the purpose of the cin.ignore() function in C++?
It discards characters in the input buffer, often used before cin.get().
What is the significance of the -o option in g++?
It specifies the output filename for the compiled program.
Why is defensive programming important?
It helps in creating more reliable, readable, and maintainable code.
How does preprocessing aid in C++ development?
Preprocessing provides flexibility in code compilation and can optimize performance.
What are the benefits of using a debugger like gdb?
It allows for detailed inspection and troubleshooting of runtime behavior in C++ programs.