Programming in C++
1. explain the features of structured programming in brief with its
advantages and disadvantages.
=✅ Structured Programming – Overview
Structured Programming is a programming paradigm aimed at improving the clarity,
quality, and development time of software by using clear, logical control structures.
It emphasizes:
Top-down design
Modular programming
Use of sequence, selection, and iteration
⭐ Features of Structured Programming
1. Modular Approach
o Program is divided into smaller blocks or modules (functions/procedures).
2. Use of Control Structures
o Uses simple structures: sequence, if/else (selection), loops (iteration).
3. Top-Down Design
o Design starts from the main function and breaks down into sub-functions.
4. Single Entry and Exit
o Each function or block has one entry and one exit point, making flow
predictable.
5. Improved Readability
o Code is easier to understand and maintain due to structured layout.
6. Eliminates GOTO Statements
o Reduces the use of GOTO, which can make code hard to follow (spaghetti
code).
✅ Advantages
1. Easier to Read and Understand
o Clean structure and modular design make it simple to follow.
2. Easier to Debug and Maintain
o Isolated modules allow easier error detection and updates.
3. Reusability
o Functions or modules can be reused in other programs.
4. Improves Productivity
o Speeds up development and reduces effort with well-organized code.
5. Encourages Discipline
o Promotes good coding habits and logical thinking.
❌ Disadvantages
1. Not Suitable for All Problems
o Complex real-world scenarios may not fit well into a strictly structured model.
2. Limited Support for Real-World Modeling
o Cannot represent objects or entities as naturally as object-oriented
programming.
3. Code Duplication
o Without classes/objects, data and functions may be repeated in different parts.
4. Harder to Modify Large Programs
o Changes in one module might affect others, especially without proper design.
🔚 Conclusion
Structured programming is great for small to medium-sized applications where clarity
and logic are important. However, for complex systems, object-oriented programming
(OOP) is often more effective.
2.Write a C++ program to demonstrate the use of switch statement.
include <iostream>
using namespace std;
int main() {
int num1, num2, choice;
float result;
// Display menu
cout << "Simple Calculator using switch statement\n";
cout << "1. Addition\n";
cout << "2. Subtraction\n";
cout << "3. Multiplication\n";
cout << "4. Division\n";
cout << "Enter your choice (1-4): ";
cin >> choice;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
// Switch statement
switch(choice) {
case 1:
result = num1 + num2;
cout << "Result = " << result << endl;
break;
case 2:
result = num1 - num2;
cout << "Result = " << result << endl;
break;
case 3:
result = num1 * num2;
cout << "Result = " << result << endl;
break;
case 4:
if (num2 != 0)
result = (float)num1 / num2;
else {
cout << "Error: Division by zero!" << endl;
return 1;
}
cout << "Result = " << result << endl;
break;
default:
cout << "Invalid choice!" << endl;
}
return 0;
}
🧪 Sample Output:
cpp
Copy
Edit
Simple Calculator using switch statement
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice (1-4): 3
Enter two numbers: 5 6
Result = 30
3.What is an object? Explain how objects in C++ are created and
destroyed, with help of example
🔷 What is an Object in C++?
In C++, an object is an instance of a class.
A class is like a blueprint, and an object is a real-world entity created based on that
blueprint.
Example: If Car is a class, then myCar and yourCar are objects of that class.
Objects encapsulate data and functions that operate on that data.
🛠 How Objects are Created in C++
Objects can be created in several ways:
1. Static Object (created on stack)
cpp
CopyEdit
ClassName obj; // created automatically
2. Dynamic Object (created on heap using new)
cpp
CopyEdit
ClassName* obj = new ClassName(); // created manually
💥 How Objects are Destroyed in C++
Static Objects: Automatically destroyed when they go out of scope.
Dynamic Objects: Must be deleted manually using delete to free memory.
✅ Example Program: Object Creation & Destruction
#include <iostream>
using namespace std;
class Demo {
public:
Demo() { cout << "Object created\n"; }
~Demo() { cout << "Object destroyed\n"; }
};
int main() {
Demo obj; // Static object created
return 0; // Destructor called automatically here
}
Output:
css
Copy
Edit
Object created
Object destroyed
4.list any 5common examples of exception
Here are 5 common examples of exceptions in programming (especially in C++ or other
high-level languages):
✅ Common Exceptions:
1. Divide by Zero Exception
o Occurs when a number is divided by zero.
o Example: int x = 5 / 0;
2. Null Pointer Exception
o Trying to access or use a pointer that is null.
o Example: int* p = nullptr; *p = 10;
3. Array Index Out of Bounds
o Accessing an element outside the valid range of an array.
o Example: arr[10] when array size is 5.
4. Invalid Input/Type Conversion
o Trying to convert a string to a number when it’s not valid.
o Example: stoi("abc") in C++ throws invalid_argument.
5. File Not Found Exception
o Occurs when trying to open a file that does not exist.
o Example: ifstream file("nonexistent.txt");
3(a) What is Constructor?
A constructor is a special member function in C++ that is automatically called when an
object is created.
🔑 Key Features:
Has the same name as the class
No return type, not even void
Can be default, parameterized, or copy constructor
✅ Advantages of Constructor:
1. Automatic Initialization
o Automatically initializes objects when they are created.
2. Overloading Support
o Multiple constructors can be defined with different parameters.
3. No Explicit Call Required
o Unlike other functions, constructors are invoked automatically.
4. Better Code Organization
o Initialization logic is kept within the constructor, reducing duplication.
🔧 Example:
cpp
Copy code
class Car {
public:
Car() {
cout << "Car created!" << endl;
}
};
int main() {
Car myCar; // Constructor is automatically called
return 0;
}
3(b) What is a Member Function?
A member function is a function that is defined inside a class and is used to perform
operations on class data members.
📌 Purpose of Member Functions:
1. Encapsulation of Behavior
o Defines how objects behave using functions.
2. Data Access and Manipulation
o Can access and modify private data of the class.
3. Code Reusability
o Functions can be reused by calling them on different objects.
4. Object Interaction
o Allow interaction with and manipulation of an object's internal state.
🔧 Example:
cpp
Copy code
class Car {
private:
int speed;
public:
void setSpeed(int s) {
speed = s;
}
void displaySpeed() {
cout << "Speed: " << speed << endl;
}
};
int main() {
Car myCar;
myCar.setSpeed(80);
myCar.displaySpeed();
return 0;
}
✅ 4(a) Operator Overloading in C++
🔹 Need for Operator Overloading
Operator overloading allows *standard operators (like +, -, , etc.) to work with user-defined
types (like classes).
🧠 Why It's Needed:
To make class objects behave like built-in types
Improves code readability and reusability
Allows intuitive usage of objects in expressions
🔧 Example: Overload + Operator
cpp
Copy code
#include <iostream>
using namespace std;
class Complex {
private:
float real, imag;
public:
Complex(float r = 0, float i = 0) {
real = r;
imag = i;
}
// Overload + operator
Complex operator + (Complex c) {
return Complex(real + c.real, imag + c.imag);
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(2.5, 3.5), c2(1.5, 2.0);
Complex c3 = c1 + c2; // uses overloaded + operator
cout << "Sum = ";
c3.display();
return 0;
}
✅ 4(b) Inheritance and Multiple Inheritance
🔹 What is Inheritance?
Inheritance is a mechanism in C++ where a class (derived class) can inherit properties and
behaviors (data members and member functions) from another class (base class).
🔹 Types of Inheritance:
Single: One base → one derived
Multiple: Two or more base classes → one derived class
Others: Multilevel, Hierarchical, Hybrid
🔹 Multiple Inheritance
In multiple inheritance, a class can inherit from more than one base class.
🔧 Example: Multiple Inheritance
cpp
Copy code
#include <iostream>
using namespace std;
class A {
public:
void showA() {
cout << "Class A function\n";
}
};
class B {
public:
void showB() {
cout << "Class B function\n";
}
};
class C : public A, public B { // multiple inheritance
public:
void showC() {
cout << "Class C function\n";
}
};
int main() {
C obj;
obj.showA(); // from class A
obj.showB(); // from class B
obj.showC(); // from class C
return 0;
}
✅ Summary:
Concept Purpose
Operator Overloading Customize operators for user-defined types
Concept Purpose
Inheritance Reuse and extend functionality of existing classes
Multiple Inheritance Derive a class from more than one base class
✅ 5(a) What is a Friend Function?
A friend function is a function that is not a member of a class but has access to its private
and protected members.
🔑 Key Points:
Declared using the keyword friend inside the class.
Useful for operations involving multiple classes.
Can access private data of the class directly.
🔧 Program to Demonstrate Friend Function:
cpp
Copy code
#include <iostream>
using namespace std;
class Box {
private:
int length;
public:
Box() { length = 0; }
void setLength(int l) { length = l; }
// Friend function declaration
friend void printLength(Box b);
};
// Friend function definition
void printLength(Box b) {
cout << "Length of box: " << b.length << endl;
}
int main() {
Box b1;
b1.setLength(10);
printLength(b1); // accessing private member using friend function
return 0;
}
🧾 Output:
rust
Copy code
Length of box: 10
✅ 5(b) Basic Characteristics of OOP (Object-Oriented Programming)
Object-Oriented Programming (OOP) is a programming paradigm centered around objects
and classes. It provides better structure and code reusability.
⭐ Key Characteristics:
1. Encapsulation
o Bundling of data and functions into a single unit (class)
o Hides internal details (data hiding)
2. Abstraction
o Shows only essential features and hides complexity
o Makes programs simpler to use
3. Inheritance
o Allows a class (derived) to inherit properties and behavior from another class
(base)
o Promotes code reuse
4. Polymorphism
o Means "many forms"
o Functions or operators behave differently depending on the context
Example: Function Overloading, Operator Overloading
5. Modularity
o Program is divided into independent modules (classes/objects)
o Easy to manage, debug, and reuse
6. Dynamic Binding
o Function call is resolved at runtime
o Supports runtime polymorphism using virtual functions
📌 Summary Table:
Characteristic Description
Encapsulation Data hiding through classes
Abstraction Hiding complex implementation details
Inheritance Reuse of existing class features
Polymorphism Same interface, different implementations
Modularity Organizing code into self-contained units
Dynamic Binding Late binding of function calls at runtime
✅ 6(a) What is Polymorphism?
Polymorphism is a key concept of Object-Oriented Programming (OOP) that means "many
forms".
It allows the same function or operator to behave differently depending on the context,
such as the object that calls it.
✳️Types of Polymorphism in C++:
1. Compile-Time Polymorphism (Static Binding)
o Achieved using Function Overloading and Operator Overloading.
2. Run-Time Polymorphism (Dynamic Binding)
o Achieved using Virtual Functions.
✅ Advantages of Polymorphism:
1. Code Reusability
o The same interface can be reused with different implementations.
2. Flexibility and Extensibility
o New classes can be added with minimal changes to existing code.
3. Simplifies Code Maintenance
o Easier to manage and modify code using common interfaces.
4. Improves Readability
o Code is more intuitive and easier to understand.
✅ 6(b) Explain the Concept of Virtual Function
A virtual function in C++ is a member function in the base class that can be overridden in
the derived class. It supports runtime polymorphism.
🔑 Key Points:
Declared using the keyword virtual in the base class.
Enables dynamic dispatch, where the function call is determined at runtime.
Allows base class pointer to call derived class function.
🔧 Example of Virtual Function:
cpp
Copy code
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() {
cout << "Animal makes a sound\n";
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks\n";
}
};
int main() {
Animal* a;
Dog d;
a = &d;
a->sound(); // Calls Dog's sound() due to virtual function
return 0;
}
🧾 Output:
nginx
Copy code
Dog barks
✅ Summary:
Concept Description
Polymorphism One interface, multiple implementations
Virtual Function Supports runtime polymorphism using base pointer
✅ 7(a) What is an Exception?
An exception is an unexpected error or abnormal condition that occurs during the
execution of a program.
In C++, exceptions are handled using:
try block – where the exception might occur
catch block – to handle the exception
throw keyword – to raise an exception
🔹 Example:
cpp
Copy code
try {
int a = 5, b = 0;
if (b == 0) throw "Division by zero!";
cout << a / b;
}
catch (const char* msg) {
cout << "Error: " << msg;
}
✅ 7(b) Short Notes
1. 🔸 Message Passing
It is the process of communication between objects in OOP.
Objects send and receive information using functions/methods.
Promotes low coupling and better modularity.
2. 🔸 Objects
An object is an instance of a class.
It represents a real-world entity like a student, car, or book.
Objects contain data (attributes) and functions (methods) to operate on that data.
3. 🔸 Structured Programming
A programming paradigm that emphasizes clear, linear flow of control.
Uses sequences, selections (if/switch), and loops.
Makes code easier to read, debug, and maintain.
4. 🔸 Access Specifier
Defines the visibility/scope of class members.
Types:
o private – Accessible only within the class
o public – Accessible from anywhere
o protected – Accessible in the class and its derived classes
Controls how data and functions are accessed and modified.
5. 🔸 Class
A class is a blueprint or template for creating objects.
It defines data members (variables) and member functions (methods).
Supports concepts like encapsulation, inheritance, and abstraction.