0% found this document useful (0 votes)
9 views

C++

Uploaded by

lachlanpoole567
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

C++

Uploaded by

lachlanpoole567
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

Here are the answers to the C++ theory questions based on your PDF lecture notes:

Introduction to C++

1. What is C++, and who developed it?


C++ is a cross-platform, high-performance programming language developed by Bjarne
Stroustrup as an extension of the C language.
2. List and explain at least three reasons why C++ is widely used.
• Portability: C++ programs can be compiled and run on different
platforms.
• Object-Oriented: It supports OOP principles like inheritance,
polymorphism, and encapsulation.
• Memory Management: It gives developers direct control over memory,
which is useful for system-level programming.
3. What are the key differences between C and C++?
• C++ supports object-oriented programming (OOP) with classes and
objects, while C does not.
• C++ provides features like function overloading, exception handling,
and templates, which are absent in C.
• C++ code can use both C-style procedural programming and object-
oriented paradigms.
4. Explain the purpose of #include <iostream> and using namespace std.
• #include <iostream>: Includes the input/output stream library for using
cin, cout, etc.
• using namespace std: Allows the use of standard library names without
prefixing them with std:: (e.g., cout instead of std::cout).

Basic Syntax and Structure

5. Describe the structure of a simple C++ program.


• Preprocessor Directive: #include <iostream>
• Namespace Declaration: using namespace std;
• Main Function: int main() – entry point of the program
• Statements/Logic: Code within curly braces {}
• Return Statement: return 0; indicates successful program execution.
6. What is the significance of the main() function in a C++ program?
The main() function is the entry point of a C++ program. The execution of the
program starts from here.
7. Explain the purpose of cout and cin in C++.
• cout: Stands for “character output” and is used to print data to the
console.
• cin: Stands for “character input” and is used to read user input from
the keyboard.
8. What is the difference between \n and endl when printing output?
• \n: Inserts a newline character without flushing the output buffer.
• endl: Inserts a newline and flushes the output buffer.

Variables and Data Types

9. Define a variable. What are the rules for naming variables in C++?
A variable is a named storage location for data.
Naming rules:
• Must start with a letter or underscore.
• Can contain letters, digits, and underscores.
• Case-sensitive.
• Cannot use reserved keywords (e.g., int, class).
10. What are the different data types in C++? Give examples.

• int: Integer values (e.g., int age = 25;)


• double: Floating-point numbers (e.g., double pi = 3.1415;)
• char: Single characters (e.g., char grade = 'A';)
• string: Text sequences (e.g., string name = "John";)
• bool: Boolean values (e.g., bool isTrue = true;)

11. Differentiate between float and double.

• float: 4 bytes, 6–7 decimal digits precision.


• double: 8 bytes, 15 decimal digits precision.

12. Explain the difference between char and string.

• char: Stores a single character (e.g., 'A').


• string: Stores multiple characters as a text sequence (e.g., "Hello").

Operators

13. What are arithmetic operators? List five with examples.

• Addition (+): 5 + 3 = 8
• Subtraction (-): 7 - 4 = 3
• Multiplication (*): 6 * 2 = 12
• Division (/): 10 / 2 = 5
• Modulus (%): 7 % 3 = 1

14. Explain the difference between = and == operators.

• =: Assignment operator (e.g., x = 5;).


• ==: Comparison operator (e.g., x == 5 checks if x equals 5).

15. What are logical operators in C++? Provide examples.

• AND (&&): (x > 5 && y < 10)


• OR (||): (x == 5 || y == 7)
• NOT (!): !(x == 5)

Control Flow

16. What is the purpose of if, else if, and else statements?
These are conditional statements used for decision-making.

• if: Executes code if the condition is true.


• else if: Checks a new condition if the previous if is false.
• else: Executes code if none of the conditions are true.

17. Explain how the switch statement works.


The switch statement checks an expression against multiple case labels. When a
match is found, the corresponding block is executed. break is used to exit the
switch after a case is executed.
18. What is a ternary operator? Write a sample code snippet demonstrating
its use.
The ternary operator is a shorthand for if-else.
Syntax: condition ? expression1 : expression2;
Example:

int age = 18;


string result = (age >= 18) ? "Adult" : "Minor";
cout << result;
Output: Adult.

Loops

19. Differentiate between while and do-while loops.

• while: Checks the condition before execution.


• do-while: Executes at least once, then checks the condition.

20. What is the syntax of a for loop? How does it differ from a while loop?
Syntax:

for (int i = 0; i < 5; i++) {


cout << i << "\n";
}

• Difference: for loop is used when the number of iterations is known;


while loop is used when the condition is dynamic.

21. Explain the concept of a nested loop with an example.


A nested loop is a loop inside another loop.

for (int i = 1; i <= 3; i++) {


for (int j = 1; j <= 3; j++) {
cout << i << "," << j << "\n";
}
}

This prints all combinations of i and j from 1 to 3.

22. What is the purpose of break and continue statements?

• break: Exits the loop immediately.


• continue: Skips the current iteration and continues with the next.

Functions

23. What is a function in C++? Why are functions important?


A function is a block of code that performs a specific task. Functions improve code
reusability, organization, and maintainability.
24. Differentiate between function parameters and arguments.

• Parameters: Variables in the function definition.


• Arguments: Actual values passed to the function during the call.

25. What is function overloading? Provide an example.


Function overloading allows multiple functions with the same name but different
parameter types or numbers.

int add(int a, int b) { return a + b; }


double add(double a, double b) { return a + b; }

26. Explain the use of the return statement with an example.


The return statement returns a value from a function.

int square(int x) { return x * x; }

Object-Oriented Programming (OOP)


27. What is a class? How is it different from an object?

• Class: A blueprint for objects.


• Object: An instance of a class.

28. Define and explain the concept of attributes and methods in a class.

• Attributes: Data members (variables).


• Methods: Member functions that operate on data.

29. What are access specifiers in C++? Explain public, private, and
protected.

• public: Accessible from anywhere.


• private: Accessible only within the class.
• protected: Accessible within the class and derived classes.

30. How do you create an object from a class? Give an example.

class Car {
public:
string brand;
};
int main() {
Car myCar;
myCar.brand = "Toyota";
cout << myCar.brand;
}

Arrays and Strings

31. How do you declare and initialize an array in C++?

int arr[3] = {1, 2, 3};

32. Explain how array elements are accessed and modified.


Access elements using the index.

cout << arr[0]; // Access


arr[1] = 5; // Modify

33. What is string concatenation? Provide two methods of concatenating


strings in C++.

• Using +: string fullName = firstName + lastName;


• Using append(): fullName.append(lastName);

34. How does getline() work when accepting user input?


getline(cin, str) reads an entire line, including spaces, until a newline
character.

Miscellaneous Concepts

35. What is the difference between const and #define?

• const: Type-safe constant declared within code.


• #define: Preprocessor directive for defining macros.

36. Explain the significance of #include <cmath> and provide three


functions it offers.
The <cmath> library provides mathematical functions.

• sqrt(x) – square root


• pow(x, y) – power
• abs(x) – absolute value

37. What is the difference between compile-time and run-time errors?

• Compile-time: Errors detected during compilation (e.g., syntax errors).


• Run-time: Errors that occur while the program is running (e.g.,
division by zero).

38. How does C++ handle type conversions?


C++ supports:

• Implicit conversion (type coercion): Automatically converting


compatible types.
• Explicit conversion (casting): Using static_cast<type>() or C-style
casting.

Let me know if you need more explanations or code examples!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy