BCA 2nd sem C++ Practise
THESE ARE PRACTISE PAPER ANSWER:
by- ayanakoji
4,5 unit will be update soon
111111111111111111111111111
1. Procedure-oriented programming focuses on dividing the program into smaller procedures or functions, while object-oriented programming emphasizes organizing data and functions into objects. Example: In procedure-oriented programming, a program to calculate the area of different shapes would have separate functions for each shape. In object-oriented programming, each shape would be represented as an object with its own properties and methods.
3. Tokens are the smallest individual units in a C++ program, such as keywords, operators, and identifiers. Keywords are reserved words with predefined meanings in the language. Identifiers are names given to variables, functions, or other program elements. Constants are fixed values that cannot be changed during program execution. Example: In the statement "int x = 10;", "int" is a keyword, "x" is an identifier, and "10" is a constant.
4. Basic data types in C++ include integer types (e.g., int, long), floating-point types (e.g., float, double), character types (e.g., char), and boolean type (bool). Integer: int x = 5; Floating-point: float y = 3.14; Character: char c = 'A'; Boolean: bool flag = true;
5. Type compatibility refers to the ability to use one data type in place of another. For example, an int can be assigned to a long because they are compatible. int x = 5; long y = x; // Type compatibility. float z = x; // Type incompatibility.
6. Example:
#include <iostream>
using namespace std;
int main() {
int x, y;
cout << "Enter two numbers: ";
cin >> x >> y;
cout << "Sum: " << (x + y) << endl;
return 0;
}
7. Reference variables are aliases for existing variables. They provide a way to access and modify the same memory location as the referenced variable. Example: int x = 5; int& ref = x; // Reference variable. ref = 10; // Changes the value of x to 10.
8. The scope resolution operator (::) is used to access variables or functions that are defined in a different scope. The member dereferencing operators (., ->) are used to access members of an object or a pointer to an object. The memory management operators (new, delete) are used for dynamic memory allocation and deallocation. The type cast operator (static_cast, dynamic_cast) is used to convert one data type to another. Example: int x = ::x; // Accesses global variable x.
9. Expressions are combinations of operators, variables, and literals that produce a value. Arithmetic expressions perform mathematical operations (e.g., x + y). Relational expressions compare values (e.g., x > y). Logical expressions combine conditions using logical operators (e.g., x > 0 && y < 10).
10. Operator overloading allows the same operator to be used with different operands or perform different operations depending on the context. Example: class Vector { public: Vector operator+(const Vector& other) { /* Addition logic */ } }; Vector v1, v2; Vector result = v1 + v2;
11. Control structures in C++ include if-else statements, loops (for, while, do-while), switch statements, and jump statements (break, continue, return). Example: if (x > 0) { // If-else statement } for (int i = 0; i < 10; i++) { // Loop }
2222222222222222222
Certainly! Here are the answers to the remaining questions:
2. Function prototyping in C++ involves declaring the function's signature before its actual definition. It is necessary because it allows the compiler to verify the function's usage and catch any potential errors. Function prototypes help in organizing code by providing a clear overview of the functions used in a program. Example of a function prototype:
```
// Function prototype
int addNumbers(int x, int y);
```
3. Call by reference in C++ involves passing the memory address of a variable to a function parameter, allowing the function to modify the original value. It differs from call by value where only a copy of the variable is passed. Example program demonstrating call by reference:
```cpp
#include <iostream>
using namespace std;
void increment(int& num) {
num++;
}
int main() {
int x = 5;
increment(x);
cout << "Value of x after increment: " << x << endl;
return 0;
}
4. Return by reference in C++ allows a function to return a reference to a variable. Its purpose is to enable modification of the returned value directly. Advantages include avoiding unnecessary copying of large objects and allowing cascading function calls. Example program demonstrating return by reference:
```cpp
#include <iostream>
using namespace std;
int& findMax(int& a, int& b) {
return (a > b) ? a : b;
}
int main() {
int x = 5, y = 10;
int& maxRef = findMax(x, y);
maxRef = 15;
cout << "Modified value of x: " << x << endl;
return 0;
}
```
5. Inline functions in C++ are small functions that are expanded at the point of function call, eliminating the overhead of function call mechanisms. Benefits include improved performance and reduced function call overhead. Limitations include increased code size and potential loss of code modularity. Example of an inline function:
```cpp
#include <iostream>
using namespace std;
inline int square(int num) {
return num * num;
}
int main() {
int result = square(5);
cout << "Square of 5: " << result << endl;
return 0;
}
```
6. Default arguments in C++ functions allow parameters to have default values, simplifying function calls by providing default values when no arguments are specified. Example of a function with default arguments:
```cpp
#include <iostream>
using namespace std;
void greet(string name = "Guest") {
cout << "Hello, " << name << "!" << endl;
}
int main() {
greet(); // Output: Hello, Guest!
greet("John"); // Output: Hello, John!
return 0;
}
```
7. Const arguments in C++ functions indicate that the function will not modify the value of the argument passed. They ensure data integrity and prevent accidental modification. Example of a function with const arguments:
```cpp
#include <iostream>
using namespace std;
void printValue(const int& num) {
// num = 10; // Error: Cannot modify const argument
cout << "Value: " << num << endl;
}
int main() {
int x = 5;
printValue(x); // Output: Value: 5
return 0;
}
```
8. Function overloading in C++ allows multiple functions with the same name but different parameters or return types. Its purpose is to provide flexibility and enable the same function name to perform different operations based on the context. Example program demonstrating function overloading:
```cpp
#include <iostream>
using namespace std;
int add(int a, int b
) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int main() {
int result1 = add(2, 3);
double result2 = add(2.5, 3.5);
cout << "Result 1: " << result1 << endl;
cout << "Result 2: " << result2 << endl;
return 0;
}
```
9. Friend functions in C++ are non-member functions that have access to the private and protected members of a class. They are declared as friends inside the class. Unlike member functions, friend functions are not invoked using the object of a class. Example program with a friend function:
```cpp
#include <iostream>
using namespace std;
class MyClass {
private:
int data;
public:
MyClass(int d) : data(d) {}
friend void printData(const MyClass& obj);
};
void printData(const MyClass& obj) {
cout << "Data: " << obj.data << endl;
}
int main() {
MyClass obj(5);
printData(obj); // Output: Data: 5
return 0;
}
```
10. Virtual functions in C++ are functions declared in a base class and overridden in derived classes. They enable runtime polymorphism, allowing the correct function to be called based on the actual object type. Example program demonstrating virtual functions:
```cpp
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape." << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle." << endl;
}
};
int main() {
Shape* shapePtr = new Circle();
shapePtr->draw(); // Output: Drawing a circle.
delete shapePtr;
return 0;
}
```
3333333333
Certainly! Here are the answers to the additional questions:
1. Classes and objects in C++:
- Classes are user-defined data types that encapsulate data (attributes) and functions (methods) into a single entity. They serve as blueprints for creating objects.
- Objects are instances of a class. They represent a specific entity and can have their own set of attributes and behaviors.
Example:
```cpp
// Class declaration
class Rectangle {
private:
int width;
int height;
public:
void setDimensions(int w, int h) {
width = w;
height = h;
}
int calculateArea() {
return width * height;
}
};
int main() {
// Object instantiation
Rectangle rect;
rect.setDimensions(5, 3);
int area = rect.calculateArea();
cout << "Area: " << area << endl;
return 0;
}
```
2. Static data members in C++:
- Static data members are shared by all objects of a class. They belong to the class itself rather than individual objects.
- They are declared using the `static` keyword and have a single instance shared among all objects.
- They can be accessed using the class name, without the need for object instantiation.
Example:
```cpp
class Counter {
private:
static int count;
public:
Counter() {
count++;
}
static int getCount() {
return count;
}
};
int Counter::count = 0;
int main() {
Counter c1;
Counter c2;
Counter c3;
cout << "Count: " << Counter::getCount() << endl;
return 0;
}
```
3. Employee class program:
```cpp
#include <iostream>
using namespace std;
class Employee {
private:
string name;
int age;
float salary;
public:
void setName(string n) {
name = n;
}
void setAge(int a) {
age = a;
}
void setSalary(float s) {
salary = s;
}
string getName() {
return name;
}
int getAge() {
return age;
}
float getSalary() {
return salary;
}
};
int main() {
Employee emp;
emp.setName("John Doe");
emp.setAge(30);
emp.setSalary(5000.0f);
cout << "Name: " << emp.getName() << endl;
cout << "Age: " << emp.getAge() << endl;
cout << "Salary: " << emp.getSalary() << endl;
return 0;
}
```
4. Nesting of member functions in C++:
- Nesting of member functions refers to defining a member function inside another member function.
- The nested function has access to the outer function's variables and can manipulate them directly.
- It can be useful for code organization and encapsulation of related functionality.
Example:
```cpp
class Outer {
private:
int x;
public:
void setX(int value) {
x = value;
}
void outerFunction() {
cout << "Outer function" << endl;
// Nested function
void innerFunction() {
cout << "Inner function" << endl;
cout << "Accessing outer variable x: " << x << endl;
}
innerFunction();
}
};
int main() {
Outer obj;
obj.setX(10);
obj.outerFunction();
return 0;
}
```
5. BankAccount class program:
```cpp
#include <iostream>
using namespace std;
class BankAccount {
private:
int accountNumber;
string accountHolderName;
double balance;
public:
void setAccountNumber(int num) {
accountNumber = num;
}
void setAccountHolderName(string name) {
accountHolderName = name;
}
void deposit(double amount) {
balance += amount;
}
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
cout << "Insufficient balance." << endl;
}
}
void displayBalance() {
cout << "Account Number: " << accountNumber << endl;
cout << "Account Holder Name: " << accountHolderName << endl;
cout << "Balance: " << balance << endl;
}
};
int main() {
BankAccount account;
account.setAccountNumber(12345);
account.setAccountHolderName("John Doe");
account.deposit(500.0);
account.withdraw(200.0);
account.displayBalance();
return 0;
}
```
6. Pointers to members in C++:
- Pointers to members allow accessing and calling class member functions and data members through pointers.
- They are declared using the class name, the `::*` operator, and the member's type.
- Pointers to member functions can be invoked using the pointer and the `->*` operator.
Example:
```cpp
#include <iostream>
using namespace std;
class MyClass {
public:
int add(int a, int b) {
return a + b;
}
};
int main() {
MyClass obj;
int (MyClass::*addPtr)(int, int) = &MyClass::add;
int result = (obj.*addPtr)(2, 3);
cout << "Result: " << result << endl;
return 0;
}
```
Comments
Post a Comment