SOLUTION TO: WEEK ONE
Activity: Understand Basic Concept of C++ Programming Language
Aim: To enable students to understand the Basic concept of C++
Programming Language.
EXERCISE SOLUTIONS:
Exercise 1. explains the Features of C++:
Object-Oriented
Platform Independent
Case Sensitive
Rich Library Support
Multi-Paradigm Support
Low-level Memory Manipulation
Compiler-Based
Supports Recursion
Strong Type Checking
Portable
Exercise 2. Importance of C++:
Encourages structured programming
Facilitates code reusability via OOP
Used in system/application software development
High performance and fast execution
Large ecosystem and community support
Enables low-level data manipulation
Exercise 3. Identifiers: Valid:
totalSum
studentName
_index
age12
count
MAX_SIZE
num1
dataValue
isValid
x
Invalid identifies:
2value (starts with digit)
total$sum (special symbol not allowed)
class (reserved keyword)
my value (contains space)
SOLUTION TO: WEEK TWO - THREE
Activity: Understand the fundamentals of C++
Aim: To enable students to understand the fundamentals of C++
Programming Language.
Exercise Solutions:
i. C++ Program to display a line of text:
#include <iostream.h>
int main() {
cout << "Welcome to C++ Programming" << endl;
return 0;
}
ii. Explanation of the Structure:
#include <iostream.h>: Includes input/output functions
int main(): Program entry point
cout: Outputs data
return 0: Terminates program
iii. Valid Identifiers: a) Valid
b) Valid
c) Valid
d) Invalid (contains ‘-’)
e) Invalid (contains ‘$’)
f) Invalid (starts with digit)
g) Invalid (keyword)
h) Valid
i) Valid
j) Invalid (contains ‘.’)
SOLUTION TO: WEEK FOUR
Activity: Understand Input and Output of Operations in C++
Aim: Understand input/output operations in C++
Exercise Solutions:
a. Variables and Types: Variables store data types such as:
int: integers
float: decimal numbers
char: single character
bool: true/false
double: large decimal numbers
b. Data Input/Output Methods:
Input: cin with >>
Output: cout with <<
Use of manipulators like endl, setw
c. Object Types & Meta Classes:
Objects: Instances of classes
Types: Concrete, Abstract, Interface
Meta Class: Class of a class (describes class behavior)
SOLUTION TO: WEEK FOUR - FIVE
Activity: Understand functions and libraries in C++ Programming Language
Exercise Solutions:
i. Functions vs Overloaded Functions:
Function: Reusable block of code
Overloaded Function: Multiple functions with same name but different
parameters
ii. Passing vs Default Arguments:
Passing: Function call supplies all arguments
Default: Some parameters have preset values
iii. Functions and Libraries:
Libraries contain pre-defined functions (e.g., <cmath>, <string>)
Functions allow modular design, reusability, easy debugging
iv. Programmer-defined Functions:
Functions created by users for specific tasks
Syntax: returnType functionName(parameters) { … }
v. Swap Function Result: Values of x and y remain unchanged as
parameters are passed by value.
vi. Output of Program:
Parameter
local
global
Parameter
WEEK SEVEN - EIGHT
Activity: Understand Object Oriented Programming Concepts.
Exercise Solutions:
i. Creating Objects from Classes:
class Student {
public:
void display() {
cout << "Student Info";
}
};
Student s1; // Object
s1.display();
ii. Constructor and Inline Methods:
Constructor: Auto-invoked during object creation
Inline Method: Function defined within class body
iii. OOP Concepts:
Encapsulation: Wrapping data/methods
Inheritance: Deriving new class from base class
Polymorphism: One interface, multiple implementations
iv. Year Class Implementation: Implementation of functions like
WorkDay, OffDay, Working, and Day is required to manipulate day states
using inheritance from BitVec.
SOLUTION TO: WEEK NINE - TEN
Activity: Understand pointers and arrays.
Exercise Solutions:
a. Implementing Arrays:
Arrays are collections of fixed-size same-type data
int numbers[5] = {1, 2, 3, 4, 5};
b. Pointer Types:
Pointer: Stores address
Arithmetic Pointer: Supports +, -, ++, --
Array Pointer: Points to array elements
c. Functions to Read/Write Arrays:
void ReadArray(double nums[], const int size) {
for (int i = 0; i < size; i++)
cin >> nums[i];
}
void WriteArray(double nums[], const int size) {
for (int i = 0; i < size; i++)
cout << nums[i] << " ";
}
d. Reverse String with Pointer Arithmetic:
char* ReverseString(char *str) {
int len = strlen(str);
char *result = new char[len + 1];
for (int i = 0; i < len; ++i)
*(result + i) = *(str + len - i - 1);
*(result + len) = '\0';
return result;
}
SOLUTION TO: WEEK TWELVE
Activity: Understand how to apply object oriented C++ programming to
database development.
Exercise Solutions:
a. What is Database? A database is an organized collection of data.
Steps: Requirement gathering → Conceptual Design → Logical Design →
Physical Design → Implementation
b. OOP Design Guidelines:
Use abstraction
Apply encapsulation
Use inheritance for reusability
Design loosely coupled modules
c. Rewrite Classes as Templates:
template<typename Key, typename Data>
class Database {
public:
virtual void Insert(Key key, Data data) {}
virtual void Delete(Key key) {}
virtual bool Search(Key key, Data& data) { return false; }
};
Features of C++ Programming Language
C++ is a powerful, high-performance programming language that extends
the C language with object-oriented and generic programming features. Here
are its key features:
1. Object-Oriented Programming (OOP)
o Supports classes, objects, inheritance, polymorphism, and
encapsulation, making code modular and reusable.
2. Platform-Dependent (Low-Level Manipulation)
o Allows direct memory manipulation using pointers, making it
suitable for system programming.
3. Mid-Level Language
o Combines high-level (abstraction, OOP) and low-level (memory
management, hardware control) features.
4. Statically Typed
o Variable types are checked at compile-time, reducing runtime
errors.
5. Rich Standard Library (STL - Standard Template Library)
o Provides built-in functions and containers (like vectors, lists,
maps) for efficient programming.
6. Multi-Paradigm Language
o Supports procedural, object-oriented, and generic
programming styles.
7. Memory Management
o Allows manual memory
management using new and delete operators.
8. Fast and Efficient
o Compiled language that produces optimized, high-speed
executable code.
9. Function Overloading & Operator Overloading
o Enables multiple functions with the same name but different
parameters.
o Allows redefining operators (e.g., +, -) for user-defined types.
10. Exception Handling
o Supports try, catch, and throw for error handling.
11. Templates (Generic Programming)
o Enables writing reusable code for different data types.
12. Portability
o C++ code can be compiled and run on different platforms with
minimal changes.
Importance of C++ Programming
1. High Performance & Efficiency
o Used in game development, real-time systems, and high-
frequency trading where speed is crucial.
2. System & Embedded Programming
o Ideal for operating systems (Windows, Linux), device
drivers, and firmware.
3. Game Development
o Powers game engines like Unreal Engine due to its speed and
hardware control.
4. Competitive Programming & Interviews
o Preferred in coding contests (like ICPC, Google Code Jam) for its
execution speed.
5. Cross-Platform Development
o Used in Android NDK, IoT devices, and robotics.
6. Industry Applications
o Used in banking, aviation, medical systems, and
automotive software.
7. Foundation for Other Languages
o Languages like Java, Python, and C# are influenced by C++
syntax and concepts.
8. Large Community & Libraries
o Extensive support from Boost, Qt, OpenCV, and other libraries.
WEEK FOUR
a. Describe a Variable and Mention Types of Variables
Variable
A variable is a named storage location in memory that holds data, which
can be modified during program execution. It has a data type, name,
and value.
Types of Variables in C++
1. Local Variables
o Declared inside a function or block.
o Accessible only within that scope.
o Example:
void func() {
int x = 10; // Local variable
}
2. Global Variables
o Declared outside all functions.
o Accessible throughout the program.
o Example:
cpp
Copy
Download
int y = 20; // Global variable
3. Static Variables
o Retains its value between function calls.
o Declared with the static keyword.
o Example:
cpp
Copy
Download
void counter() {
static int count = 0; // Static variable
count++;
}
4. Instance Variables (Non-static Member Variables)
o Belongs to an object (class instance).
o Each object has its own copy.
o Example:
cpp
Copy
Download
class MyClass {
int num; // Instance variable
};
5. Class Variables (Static Member Variables)
o Shared among all objects of a class.
o Declared with static inside a class.
o Example:
cpp
Copy
Download
class MyClass {
static int sharedNum; // Class variable
};
6. Constant Variables (const)
o Value cannot be changed after initialization.
o Example:
cpp
Copy
Download
const int PI = 3.14;
b. Methods of Data Input/Output in C++
C++ provides multiple ways to handle input and output (I/O):
1. Using cin and cout (Standard I/O)
cin (for input)
cpp
Copy
Download
int num;
cin >> num; // Takes input from the user
cout (for output)
cpp
Copy
Download
cout << "Number: " << num; // Displays output
2. Using scanf() and printf() (C-style I/O)
scanf() (for formatted input)
cpp
Copy
Download
int num;
scanf("%d", &num); // Reads an integer
printf() (for formatted output)
cpp
Copy
Download
printf("Number: %d", num); // Prints formatted output
3. File I/O (fstream)
Reading from a file (ifstream)
cpp
Copy
Download
ifstream input("file.txt");
string line;
getline(input, line); // Reads a line from file
Writing to a file (ofstream)
cpp
Copy
Download
ofstream output("file.txt");
output << "Hello, File!"; // Writes to file
4. String Streams (sstream)
Used for reading/writing from strings as streams.
Example:
cpp
Copy
Download
stringstream ss;
ss << "Data: " << 100;
string str = ss.str(); // Converts to string
5. Command-Line Arguments (argc, argv)
Used to pass inputs when running the program.
Example:
cpp
Copy
Download
int main(int argc, char* argv[]) {
cout << "First argument: " << argv[1];
}
c. Types of Objects and Differences Between Meta Class
Types of Objects in C++
1. Instance Objects
o Created from a class.
o Example:
cpp
Copy
Download
class Car { ... };
Car myCar; // Instance object
2. Static Objects
o Only one instance exists (shared across all instances).
o Example:
cpp
Copy
Download
class Logger {
static Logger instance; // Static object
};
3. Temporary Objects
o Short-lived objects (e.g., return values).
o Example:
cpp
Copy
Download
string getName() { return "Temp Object"; }
4. Dynamic Objects (Heap Objects)
o Created using new and destroyed with delete.
o Example:
cpp
Copy
Download
int* num = new int(5); // Dynamic object
Difference Between Class and Meta Class
Feature Class Meta Class
A blueprint for creating
Definition A class that defines other classes.
objects.
Used to create instance Used to modify class behavior (e.g.,
Usage
objects. in Python).
Example class Car { ... }; In Python: type is a metaclass.
C++ Not natively supported (unlike
Directly supported.
Support Python).
In C++, metaclasses are not a built-in feature (unlike Python), but similar
behavior can be achieved using templates and advanced OOP
techniques.
Summary
Variables store data and have different scopes (local, global, static,
etc.).
I/O methods include cin/cout, scanf/printf, file streams, and string
streams.
Objects can be instance-based, static, temporary, or dynamic.
Metaclasses (common in Python) are not native to C++ but can be
simulated.
Exercise Solutions
i. What is a Function and Overloaded Functions?
Function
A function is a reusable block of code that performs a specific task. It
improves modularity and reduces code repetition.
Example:
cpp
Copy
Download
int add(int a, int b) {
return a + b;
}
Overloaded Functions
Functions with the same name but different parameters (number or
type). The correct function is called based on arguments.
Example:
cpp
Copy
Download
int add(int a, int b) { return a + b; }
float add(float a, float b) { return a + b; }
ii. Difference Between Passing and Default Arguments
Passing Arguments Default Arguments
Values are provided when calling the Values are predefined if no
function. argument is passed.
Example: void func(int x = 5, int y =
Example: func(10, 20);
10);
All arguments must be passed (unless
Optional arguments can be skipped.
default exists).
Example of Default Arguments:
cpp
Copy
Download
void greet(string name = "User") {
cout << "Hello, " << name;
}
greet(); // Output: "Hello, User"
greet("Alice"); // Output: "Hello, Alice"
iii. Functions and Libraries in Programs
Functions
Reusable blocks of code that perform tasks.
Improve readability and maintainability.
Example:
cpp
Copy
Download
int square(int x) { return x * x; }
Libraries
Pre-written collections of functions/classes.
Standard Library (STL): #include <iostream>, <vector>, etc.
Third-party Libraries: OpenCV, Boost.
Example:
cpp
Copy
Download
#include <iostream> // Library for I/O
using namespace std;
int main() {
cout << "Hello, World!"; // 'cout' is from iostream
}
iv. Programmer-Defined Functions
Functions created by the programmer (not built into the language). They
are customized for specific tasks.
Example:
cpp
Copy
Download
double calculateTax(double income) {
return income * 0.15; // Custom tax calculation
}
v. Swap Function Analysis
Given Code:
cpp
Copy
Download
void Swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int x = 10, y = 20;
Swap(x, y);
cout << "x = " << x << ", y = " << y;
}
Output:
x = 10, y = 20
Reason:
The function uses pass-by-value, so changes inside Swap() do not
affect the original variables.
To modify x and y, use pass-by-reference:
cpp
Copy
Download
void Swap(int &x, int &y) { ... } // Corrected version
vi. Program Output Analysis
Given Code:
cpp
Copy
Download
#include <iostream.h>
char *str = "global";
void Print(char *str) {
cout << str << '\n';
{
char *str = "local";
cout << str << '\n';
cout << ::str << '\n';
}
cout << str << '\n';
}
int main() {
Print("Parameter");
return 0;
}
Output:
text
Copy
Download
Parameter
local
global
Parameter
Explanation:
1. First cout: Prints the parameter "Parameter".
2. Inner Block:
o str is redefined as "local" (local scope).
o ::str accesses the global str ("global").
3. Final cout: The parameter str ("Parameter") is still in scope.
Summary
1. Functions encapsulate reusable logic; overloading allows same-
name functions with different parameters.
2. Passing arguments requires explicit values; default
arguments provide fallback values.
3. Libraries (like STL) extend functionality; programmer-defined
functions are custom.
4. Swap Function: Pass-by-value does not modify originals; use
references.
5. Scope Rules: Local variables override globals; :: accesses global
scope.