SlideShare a Scribd company logo
1 of 68
Download to read offline
Problem Solving and Computer Programming 1
Problem Solving and Computer
Programming
Data Types
Operators- arithmetic, relational, logical, bitwise, pointer, miscalleneous
Decision making Statements
Loops
Jump statements
Escape sequences
Arrays
Searching
Sorting
Pointers and references
Functions
Methods of passing parameters
Recursion
Function overloading/polymorphism,
Function templating
Storage classes
Structures
Unions
OOP and Classes:
Class
Constructor
Problem Solving and Computer Programming 2
Destructor
Binary operator overloading
Friend functions
Friend Classes
Inheritance
File management
Strings
Data Types
Data types define the type of data that a variable can hold.
Primary/Fundamental Data Types
1. Integer Types:
int : Integer type, representing whole numbers.
short : Short integer type.
Problem Solving and Computer Programming 3
long : Long integer type.
2. Floating-Point Types:
float : Single-precision floating-point type.
double : Double-precision floating-point type.
long double : Extended precision floating-point type.
3. Character Types:
char : Character type, representing a single character.
wchar_t : Wide character type.
4. Boolean Type:
bool : Boolean type, representing true or false values.
Derived Data Types
1. Function : A derived data type that encapsulates executable code, declared with a
return type and parameters.
2. Array : Collection of elements of the same data type arranged in a fixed-size
sequence.
3. Pointer : A variable that stores the memory address of another variable.
4. Reference : An alternative name for an existing variable.
User-defined Data Types
1. Class : A user-defined data type that can encapsulate data members and
member functions.
2. Structure : A user-defined composite data type that groups variables of different
data types under a single name.
3. Union : Similar to a structure, but it uses the same memory location for all its
members, allowing different data types to share the same memory space.
4. Enum : A user-defined data type consisting of named integer constants.
typedef : It is a keyword used to create an alternate name for a data type,
enhancing code readability and providing a convenient way to declare complex or
compound data types.
Problem Solving and Computer Programming 4
Example:
typedef long int lint;
lint x1,x2;//declares long integers x1 and x2
Operators
Operators are symbols that perform operations on operands, which can be variables,
constants, or expressions.
They can be classified into the following major types:
Unary operators
Unary operators operate on a single operand.
Prefix Increment ( ++x ):
Increments the value of x before its current value is used and the updated value is
immediately available for use in the expression.
Example:
int x = 5;
int y = ++x; // y is 6, x is 6
Postfix Increment ( x++ ):
Uses the current value of x in an expression before incrementing it and the update
occurs after the current value is used.
Example:
int x = 5;
int y = x++; // y is 5, x is 6
Add and Assign ( += ):
Adds the right operand to the left operand and assigns the result to the left operand.
Problem Solving and Computer Programming 5
int a = 3;
a += 2; // Equivalent to a = a + 2; a is now 5
Operators like -- , -= , *= , /= , %= also work accordingly.
Binary operators
Binary operators operate on two operands.
Arithmetic Operators:
1. + (Addition): Adds two operands.
2. - (Subtraction): Subtracts the right operand from the left operand.
3. * (Multiplication): Multiplies two operands.
4. / (Division): Divides the left operand by the right operand.
5. % (Modulus): Returns the remainder of the division of the left operand by the
right operand.
Relational Operators:
1. == (Equal to): Checks if the values of two operands are equal.
2. != (Not equal to): Checks if the values of two operands are not equal.
3. > (Greater than): Checks if the value of the left operand is greater than the
value of the right operand.
4. < (Less than): Checks if the value of the left operand is less than the value of
the right operand.
5. >= (Greater than or equal to): Checks if the value of the left operand is greater
than or equal to the value of the right operand.
6. <= (Less than or equal to): Checks if the value of the left operand is less than
or equal to the value of the right operand.
Logical Operators:
1. && (Logical AND): Returns true if both operands are true.
2. || (Logical OR): Returns true if at least one of the operands is true.
3. ! (Logical NOT): Returns true if the operand is false and vice versa.
Problem Solving and Computer Programming 6
Bitwise Operators:
1. & (Bitwise AND): Performs bitwise AND operation on corresponding bits of two
operands.
2. | (Bitwise OR): Performs bitwise OR operation on corresponding bits of two
operands.
3. ^ (Bitwise XOR): Performs bitwise XOR (exclusive OR) operation on
corresponding bits of two operands.
4. ~ (Bitwise NOT): Flips the bits of the operand, changing 1s to 0s and vice
versa.
5. << (Left Shift): Shifts the bits of the left operand to the left by a specified
number of positions.
6. >> (Right Shift): Shifts the bits of the left operand to the right by a specified
number of positions.
Pointer operators:
1. & (Address-of Operator): Returns the memory address of a variable.
2. * (Pointer Declaration): Declares a pointer variable or dereferences a pointer,
depending on the context.
Miscalleneous Operators:
1. = (Assignment Operator): Assigns the value of the right operand to the left
operand.
2. sizeof : Returns the size, in bytes, of an object or data type.
3. :: (Scope Resolution Operator): Specifies the scope of a variable or function,
especially in the context of namespaces and classes.
4. new : Dynamically allocates memory for a variable or object during runtime.
5. delete : Deallocates memory that was previously allocated using new .
6. ? : (Ternary Conditional Operator): A shorthand way of writing an if-else
statement, allowing conditional expressions.
7. . ( Dot operator): Member access
8. -> (Arrow operator): Member access through pointer
Problem Solving and Computer Programming 7
Decision-Making Statements
Decision-making statements are used to control the flow of a program based on
certain conditions.
If statement
Executes a block of code if the specified condition is true. If the condition is false, the
code block is skipped.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
Example:
int x = 10;
if (x > 5)
{
cout << "x is greater than 5." << endl;
}
If - else Statement
Executes one block of code if the condition is true and another block if the condition
is false.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
else
{
Problem Solving and Computer Programming 8
// Code to execute if the condition is false
}
Example:
int x = 3;
if (x > 5)
{
cout << "x is greater than 5." << endl;
}
else
{
cout << "x is not greater than 5." << endl;
}
If - else if - else Statement
Allows you to specify multiple conditions and execute different code blocks based on
which condition is true. It's used for choosing from several options.
Syntax:
if (condition1)
{
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition2 is true
}
//...
else
{
// Code to execute if neither condition1 nor conditio
}
Example:
Problem Solving and Computer Programming 9
int x = 7;
if (x < 5)
{
cout << "x is less than 5." << endl;
}
else if (x == 5)
{
cout << "x is equal to 5." << endl;
}
else
{
cout << "x is greater than 5." << endl;
}
//Output: x is greater than 5.
Switch Statement
Provides a way to select one of many code blocks to execute based on the value of
an expression. It's often used for menu-like selection.
Syntax:
switch (expression)
{
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
// ...
default:
// Code to execute if none of the cases match
}
Example:
int choice = 2;
switch (choice)
Problem Solving and Computer Programming 10
{
case 1:
cout << "You chose option 1." << endl;
break;
case 2:
cout << "You chose option 2." << endl;
break;
case 3:
cout << "You chose option 3." << endl;
break;
default:
cout << "Invalid choice." << endl;
}
//Output: You chose option 2.
Conditional (Ternary) Operator
Offers a concise way to choose between two expressions based on a condition. It
returns one of two values depending on whether the condition is true or false.
Syntax:
(condition) ? expression_if_true : expression_if_false;
Example:
int x = 7;
string result = (x > 5) ? "x is greater than 5" : "x is not g
cout << result << endl;
return 0;
//Output : x is greater than 5
These decision making statements can be nested to handle more complex decision-
making scenarios where you need to evaluate multiple conditions within a
hierarchical structure.
Problem Solving and Computer Programming 11
Loop Statements
Loop statements are used to repeatedly execute a block of code as long as a
specific condition is met.
for Loop
The for loop is commonly used for iterating over a range or sequence of values. It
includes an initialization step, a condition to check before each iteration, and an
updation step that is executed after each iteration.
Syntax:
for (initialization; condition; update)
{
// Code to repeat while the condition is true
}
Example:
for (int i = 0; i < 5; ++i)
{
cout<<i<<" ";
}
//output: 0 1 2 3 4
while Loop
The while loop repeatedly executes a block of code as long as the specified
condition is true. It does not require an initialization step, but it's crucial to ensure that
the condition eventually becomes false to avoid an infinite loop.
Syntax:
while (condition)
{
// Code to repeat while the condition is true
}
Problem Solving and Computer Programming 12
Example:
int i = 0;
while (i < 5)
{
cout<< i<<" ";
i++;
}
//output: 0 1 2 3 4
do-while Loop
The do-while loop is similar to the while loop, but it guarantees that the code block is
executed at least once before checking the initial condition. The loop continues as
long as the condition remains true.
Syntax:
do
{
// Code to repeat at least once
} while (condition);
Example:
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);
//output: 0 1 2 3 4
Example to show the difference between the working of while and do-while loops:
int i = 0;
while (i < 0)
{
cout << i << " ";
i++;
Problem Solving and Computer Programming 13
}
// No output
In a while loop with the condition i < 0 , the loop body would not be executed at all
because the initial value of i is 0, which does not satisfy the condition.
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 0);
//output: 0
In a do-while loop with the condition i < 0 , the loop body would be executed at least
once before checking the condition. The output would be 0 , and the loop would
terminate after the first iteration.
The do-while loop guarantees at least one execution of the loop body before
evaluating the condition.
Nesting of these loop statements allows for the creation of complex and structured
control flow, enabling the execution of repetitive tasks within other repetitive tasks.
Nesting loop statements with decision-making (conditional) statements allows for
executing certain blocks of code repeatedly based on conditions, leading to more
flexible and powerful program logic.
Jumping Statements
Jumping statements change the normal flow of control within a program. The main
jumping statements are break , continue , return and goto .
The break and continue statements are generally used within loops ( for , while , do-
while ) and
switch statements.
1. break : Terminates the innermost loop or switch statement and transfers control
to the statement following the terminated loop or switch.
Problem Solving and Computer Programming 14
2. continue : Skips the rest of the loop's code and proceeds to the next iteration of
the loop.
3. return : Terminates the execution of a function and returns a value (if applicable)
to the calling function.
4. goto : Transfers control to a labeled statement in the program.
Note: Using goto is generally discouraged due to its potential to create unreadable
and unmaintainable code.
Escape Sequences
Escape sequences are special combinations of characters that represent non-
printable or special characters.
Commonly used escape sequences:
1. t : Horizontal tab character
2. v : Vertical tab character
3. n : Newline character, indicating a new line
4. a : Produces an audible alert or beep
5.  : Represents a backslash character
6. " : Represents a double quote character within a string
7. ' : Represents a single quote character within a string
8. b : Backspace character
9. r : Carriage return character → move the cursor or print-head back to the
beginning of the line.
Arrays
Arrays are used to store a collection of elements of the same data type under a
single name. They provide a way to efficiently manage and access multiple values
Problem Solving and Computer Programming 15
using a single identifier. They provide a convenient way to manage and iterate over
sequential data.
Syntax:
data_type array_name[array_size]={element1, element2, element3
//The number of elements the array can store is the value of a
data_type : Specifies the type of elements the array will hold.
array_name : The name assigned to the array.
array_size : The number of elements the array can hold.
Indexing: Array elements are accessed using their index, starting from 0 for the
first element and incrementing by 1 for each subsequent element.
array_name[index]
Examples:
#include <iostream>
using namespace std;
int main() {
// Declaration and initialization of an integer array
int numbers[5] = {10, 20, 30, 40, 50};
// Accessing and printing array elements
cout << "Element at index 0: " << numbers[0] << endl;
cout << "Element at index 2: " << numbers[2] << endl;
return 0;
}
//Output:
//Element at index 0: 10
//Element at index 2: 30
Taking input from the user:
Problem Solving and Computer Programming 16
#include <iostream>
using namespace std;
int main() {
cout<<"Enter the size of the array: ";
cin>>size;
int numbers[size];
cout<<"Enter the elements: ";
for(int i=0;i<size;i++){
cin>>numbers[i];
}
return 0;
}
2D Arrays
A two-dimensional array is a data structure that represents a grid or matrix of
elements arranged in rows and columns. It can be visualized as an array of arrays,
where each element in the array is itself an array. This structure allows for the
representation of tables, matrices, and other two-dimensional data. Accessing
elements in a 2D array requires specifying both the row and column indices.
Example:
#include <iostream>
using namespace std;
int main() {
int rows1, cols1, rows2, cols2;
//Inputting the matrices
cout<<"Enter the number of rows of matrix 1: ";
cin>>rows1;
cout<<"Enter the number of columns of matrix 1: ";
Problem Solving and Computer Programming 17
cin>>cols1;
cout<<"Enter the number of rows of matrix 2: ";
cin>>rows2;
cout<<"Enter the number of columns of matrix 2: ";
cin>>cols2;
int matrix1[rows1][cols1];
int matrix2[rows2][cols2];
cout<<"Enter the elements of matrix 1: ";
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
cin>>matrix1[i][j];
}
}
cout<<"Enter the elements of matrix 2: ";
for(int i=0;i<rows2;i++){
for(int j=0;j<cols2;j++){
cin>>matrix2[i][j];
}
}
//Displaying the matrices
cout<<"Matrix 1: "<<endl;
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
cout<<matrix1[i][j]<<" ";
}
cout<<endl;
}
cout<<"Matrix 2: "<<endl;
for(int i=0;i<rows2;i++){
for(int j=0;j<cols2;j++){
cout<<matrix2[i][j]<<" ";
Problem Solving and Computer Programming 18
}
cout<<endl;
}
//Adding the matrices
if(rows1==rows2 && cols1==cols2){
int result[rows1][cols1];
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
cout<<"Addition matrix: ";
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
cout<<result[i][j]<<" ";
}
cout<<endl;
}
}
else{
cout<<"Matrix addition is not possible!"<<endl;
}
//Subtracting the matrices
if(rows1==rows2 && cols1==cols2){
int result[rows1][cols1];
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
result[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
cout<<"Subtraction matrix: ";
for(int i=0;i<rows1;i++){
Problem Solving and Computer Programming 19
for(int j=0;j<cols1;j++){
cout<<result[i][j]<<" ";
}
cout<<endl;
}
}
else{
cout<<"Matrix subtraction is not possible!"<<endl;
}
//Multiplying the matrices
if(cols1==rows2){
int common = cols1;
int result[rows1][cols1];
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
result[i][j] =0;
for(int k=0;k<common;k++){
result[i][j] += matrix1[i][k]*matrix2[k][j
}
}
}
cout<<"Multiplication matrix: ";
for(int i=0;i<rows1;i++){
for(int j=0;j<cols1;j++){
cout<<result[i][j]<<" ";
}
cout<<endl;
}
}
else{
cout<<"Matrix multiplication is not possible!"<<endl;
}
return 0;
}
Problem Solving and Computer Programming 20
Character arrays
A character array is an array of characters. It is a data structure that allows you to
store a sequence of characters under a single identifier. Character arrays are used to
represent strings in C++.
They are null-terminated, meaning that the end of the string is marked by a null
character ( 0 ). This null character is automatically appended when a character array
is initialised.
#include <iostream>
using namespace std;
int main() {
const int arraySize = 10;
char greeting[arraySize] = "Hello";
cout << "The greeting is " << greeting << endl;
return 0;
}
//Output: The greeting is Hello
Searching
Searching is an operation that finds the location of a given element in a list. The
search is said to be successful or unsuccessful depending on whether the element
that is to be searched is found or not. Here, we will discuss two standard searching
methods - Linear search and Binary search.
Linear Search
Problem Solving and Computer Programming 21
#include <iostream>
using namespace std;
// Function to perform linear search
int linearSearch(int arr[], int size, int key) {
for (int i = 0; i < size; ++i) {
if (arr[i] == key) {
return i; // Return the index if the key is found
}
}
return -1; // Return -1 if the key is not found
}
int main() {
const int size = 5;
int arr[size] = {10, 25, 30, 15, 20};
int key;
cout << "Enter the element to search: ";
cin >> key;
int index = linearSearch(arr, size, key);
if (index != -1) {
cout << "Element found at index: " << index << endl;
} else {
cout << "Element not found in the array." << endl;
Problem Solving and Computer Programming 22
}
return 0;
}
Binary Search
Example:
#include <iostream>
using namespace std;
// Function to perform binary search
int binarySearch(int arr[], int size, int key) {
int low = 0;
int high = size - 1;
while (low <= high) {
int mid = (low + (high - low)) / 2;
Problem Solving and Computer Programming 23
if (arr[mid] == key) {
return mid; // Return the index if the key is fou
} else if (arr[mid] < key) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
}
}
return -1; // Return -1 if the key is not found
}
int main() {
int size = 10;
int arr[size] = {1, 2, 3, 9, 11, 13, 17, 25, 57, 90};
int key;
cout << "Enter the element to search: ";
cin >> key;
int index = binarySearch(arr, size, key);
if (index != -1) {
cout << "Element found at index: " << index << endl;
} else {
cout << "Element not found in the array." << endl;
}
return 0;
}
Problem Solving and Computer Programming 24
Binary search using Recursion (refer Recursion topic)
Sorting
Sorting refers to arranging elements of a set in some order. The data is generally
sorted in ascending or descending order.
Bubble sort
Problem Solving and Computer Programming 25
#include <iostream>
using namespace std;
// Function to perform bubble sort on an array
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) { // Outer loop for t
for (int j = 0; j < size - i - 1; j++) { // Inner loo
if (arr[j] > arr[j + 1]) {
// If the current element is greater than the nex
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Display the sorted array
cout << "The sorted array is: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
int main() {
// Set the size of the array
int size = 5;
// Initialize the array with values
int arr[size] = {25, 17, 31, 13, 2};
// Call the bubbleSort function to sort the array
bubbleSort(arr, size);
Problem Solving and Computer Programming 26
return 0;
}
Selection sort
Problem Solving and Computer Programming 27
#include <iostream>
using namespace std;
// Function to perform selection sort on an array
void selectionSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) { // Outer loop for i
for (int j = i + 1; j < size; j++) { // Inner loop fo
if (arr[i] > arr[j]) { // If the current element i
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
// Display the sorted array
cout << "The sorted array is: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
int main() {
int size = 5;
int arr[size] = {25, 17, 31, 13, 2};
Problem Solving and Computer Programming 28
// Call the selectionSort function to sort the array
selectionSort(arr, size);
return 0;
}
Problem Solving and Computer Programming 29
Pointers and references
Pointers
Pointers are variables that store the memory address of another variable. They allow
direct manipulation of memory and facilitate dynamic memory allocation.
int x = 10;
int* ptr = &x;//declares a pointer ptr to an integer and initi
References
References are alternative names for existing variables. They provide a way to
manipulate variables indirectly. The reference must be initialized upon declaration
and always refers to the same object.
int x = 10;
int& ref = x; //declares and initializes a reference to x
//Now ref can be used like x to read or modify the value of t
Dereferencing
Dereferencing is retrieving the value at the memory address held by a pointer. It
involves using the dereference operator * to retrieve the value associated with the
pointer.
int x = 10;
int* ptr = &x; // ptr holds the address of x
// Dereferencing the pointer to access the value at the memory
int value = *ptr; // value now holds the value of x (10)
Pointer to Pointer
int x = 10;
int* ptr1 = &x; // ptr1 holds the address of x
Problem Solving and Computer Programming 30
int** ptr2 = &ptr1; // ptr2 holds the address of ptr1
// Dereferencing the double pointer to access the value of x
int value = **ptr2; // value now holds the value of x (10)
Here, ptr2 is a pointer to a pointer. It stores the memory address of ptr1 , which
itself holds the address of the integer variable x .
Functions
A function in programming is a set of program statements used to perform a specific
task. When invoked, a function operates as if its code is seamlessly integrated at the
point of the function call. The interaction between the caller (the function making
the call) and the callee (the function being called) occurs through parameters,
allowing for effective communication and data exchange between different parts of
the program.
The advantages of functions include the following:
1. Modular programming
2. Reduction in the amount of work and development time
3. Program and function debugging is easier
4. Division of work is simplified due to the use of divide-and-conquer principle
5. Reduction in size of the program due to code reusability
6. Functions can be accessed repeatedly without redevelopment, which in turn
promotes reuse
of code
7. Library of functions can be implemented by combining well-designed, tested, and
proven
functions
Syntax:
return_type function_name(parameter1_type parameter1_name, pa
// Function body
Problem Solving and Computer Programming 31
// Statements to perform the desired task
// Optional: return statement to return a value if the functio
return return_value;
}
Function prototype
A function prototype is a declaration of a function that tells the compiler about the
function's name, return type, and the types of its parameters. A function prototype is
typically placed at the beginning of a program or in a header file.
return_type function_name(parameter_type parameter_name, ...)
Function Calling
Function calling involves invoking a function to execute its code. If the function has
parameters, values are passed to the function during the call.
Examples:
// Function prototype
int add(int a, int b);
// Function definition
int add(int a, int b) {
return a + b;
}
// Function call
int sum = add(3, 4);
Roots of a quadratic equation :
#include<iostream>
#include<cmath>
using namespace std;
Problem Solving and Computer Programming 32
void quadratic(int a,int b,int c){
double disc,root1,root2,real,imag,root;
disc = b*b-4*a*c;
if(disc>0){
root1 = (-b + sqrt(disc))/2*a;
root2 = (-b - sqrt(disc))/2*a;
cout<<"The 2 real roots of this equation are: "<<root1
}
else if(disc == 0){
root = -b/2*a;
cout<<"There are 2 equal roots.Hence the root is: "<<
}
else{
real = -b/2*a;
imag = sqrt(disc)/2*a;
root1 = real + imag;
root2 = real - imag;
cout<<"The imaginary roots are: "<<root1<<" and "<<roo
}
}
int main()
{
int a,b,c;
cout<<"Enter the values of a , b , c: ";
cin>>a>>b>>c;
quadratic(a,b,c);
}
Sine of an angle:
#include<iostream>
#include<cmath>
using namespace std;
//factorial function
Problem Solving and Computer Programming 33
double factori(double num)
{
double fact=1;
for(int i=1;i<=num;i++){
fact = fact * i;
}
return fact;
}
//sine function
void sine(double rad,int terms){
double sum=0;
for(int i=0;i<terms;i++){
sum = sum +(pow(rad,2*i+1)*pow(-1,i))/factori(2*i+1);
}
cout<<"Sine of the angle is: "<<sum<<endl;
}
int main(){
int degree,terms;
double rad;
cout<<"Enter the angle in degrees: ";
cin>>degree;
rad = (M_PI*degree)/180;
cout<<"Enter the no of terms till which you want to c
cin>>terms;
sine(rad,terms);
}
Methods of passing parameters
Problem Solving and Computer Programming 34
Pass by Value
In "pass by value," a copy of the argument is passed to the function.
Any changes made to the parameter within the function do not affect the
original argument.
It is suitable for situations where you want to work with a local copy of the data
and not modify the original.
It's the default way of passing arguments to functions in C++.
Example:
void increment(int x) {
x++; // Changes the local copy of x, not the original
}
int main() {
int num = 5;
increment(num);
// num remains 5, as the function works with a copy of num
return 0;
}
Pass by Pointer
In "pass by pointer," a pointer to the argument is passed to the function.
The function can modify the original data by dereferencing the pointer.
Any changes made to the pointed-to data within the function affect the original
data outside the function.
Example:
void increment(int* ptr) {
(*ptr)++; // Modifies the original data
}
int main() {
int num = 5;
increment(&num);
Problem Solving and Computer Programming 35
// num is now 6, as the function modified the original da
return 0;
}
Pass by Reference
In "pass by reference," a reference to the argument is passed to the function.
The function operates directly on the original data, not on a copy.
Changes made to the reference parameter within the function affect the
original data outside the function.
It's often used when you want to modify the original data without the overhead of
pointer syntax.
Example:
void increment(int& ref) {
ref++; // Modifies the original data
}
int main() {
int num = 5;
increment(num);
// num is now 6, as the function modified the original da
return 0;
}
Pass by Const Reference
In "pass by const reference," a constant reference to the argument is passed
to the function.
The function can access the original data but cannot modify it.
It's useful when you want to avoid making a copy of the data and ensure that the
function does not accidentally modify it.
It's commonly used for efficiency and safety.
Example:
Problem Solving and Computer Programming 36
void print(const int& ref) {
// Can read the original data, but cannot modify it
cout << ref << endl;
}
int main() {
int num = 5;
print(num); // The original data remains unchanged
return 0;
}
Recursion
A function which calls itself is called a recursive function. Recursive functions can be
powerful and elegant tools for solving certain types of problems.
Two important conditions which must be satisfied by any recursive function are the
following:
1. Each time a function calls itself, it must be nearer, in some sense, to a solution.
2. There must be a decision criterion for stopping the process or computation.
Example:
// Recursive function to calculate factorial
long factorial(int n) {
// Base case
if (n == 1) {
return 1;
}
// Recursive case
else {
return n * factorial(n - 1);
}
}
Problem Solving and Computer Programming 37
Binary search using Recursion
#include <iostream>
using namespace std;
int recBinarySearch(int arr, int lower, int upper int key){
int mid = (lower + (upper - lower))/2;
if(arr[mid] == key){
return mid; // Return the index if the key is found
}
else if(arr[mid] < key){
recBinarySearch(arr, lower, mid-1, key); // Search in
}
else if(arr[mid] > key) {
recBinarySearch(arr, mid+1, upper, key); // Search
}
return -1; // Return -1 if the key is not found
}
int main() {
int size = 10;
int arr[size] = {1, 2, 3, 9, 11, 13, 17, 25, 57, 90};
int key;
cout << "Enter the element to search: ";
cin >> key;
int index = recBinarySearch(arr, 0, size-1, key);
if (index != -1) {
cout << "Element found at index: " << index << endl;
} else {
cout << "Element not found in the array." << endl;
}
return 0;
}
Problem Solving and Computer Programming 38
Function Overloading
Function polymorphism, also known as function overloading, is a concept that
enables multiple functions to use the same name but with different parameter
types. This allows a single function name to have multiple forms, each tailored to
handle specific argument types. Function overloading, or function-name overloading,
is the practice of associating one or more function bodies with the same function
name.
Problem Solving and Computer Programming 39
#include <iostream>
using namespace std;
void swap ( char& x, char& y )
{
char t; // temporary used in swapping
t = x;
x = y;
y = t;
}
void swap( int& x, int& y )
{
int t; // temporary used in swapping
t = x;
x = y;
y = t;
}
void swap( float& x, float& y )
{
float t; // temporary used in swapping
t = x;
x = y;
y = t;
}
int main()
{
char chl, ch2;
cout << "Enter two Characters <chl, ch2>: ";
cin >> chl >> ch2;
swap( chl, ch2 );
cout << "On swapping <chl, ch2>: " << chl << " " << ch2 <<
int a, b;
cout << "Enter two integers <a, b>: ";
cin >> a >> b;
swap( a, b );
Problem Solving and Computer Programming 40
cout << "On swapping <a, b>: " << a << " " << b << endl;
float c, d;
cout << "Enter two floats <c, d>: ";
cin >> c >> d;
swap( c, d );
cout << "On swapping <c, d>: " << c << " " << d;
return 0;
}
//Output:
//Enter two Characters <chl, ch2>: a b
//On swapping <chl, ch2>: b a
//Enter two integers <a, b>: 3 5
//On swapping <a, b>: 5 3
//Enter two floats <c, d>: 3.6 2.4
//On swapping <c, d>: 2.4 3.6
Function Template
A function template, also called a generic function, combines the functionalities of
several functions differing only in data types. This allows us to write a single source
declaration that can generate multiple functions tailored to various data types.
Function templates provide a concise and flexible way to express the same logic for
different types, promoting code reusability and simplicity.
Syntax:
Problem Solving and Computer Programming 41
Example:
#include <iostream>
using namespace std;
template <class T>
void my_swap( T& x, T& y )
{
T t; // temporarily used in my_swap, template variable
t = x;
x = y;
y = t;
}
int main()
{
char chl, ch2;
cout << "Enter two Characters <chl, ch2>: ";
cin >> chl >> ch2;
my_swap( chl, ch2 ); // compiler calls my_swap( char &x, c
cout << "On swapping <chl, ch2>: " << chl << " " << ch2 <<
int a, b;
cout << "Enter two integers <a, b>: ";
cin >> a >> b;
my_swap( a, b ); // compiler creates and calls my_swap( i
cout << "On swapping <a, b>: " << a << " " << b << endl;
Problem Solving and Computer Programming 42
float c, d;
cout << "Enter two floats <c, d>: ";
cin >> c >> d;
my_swap( c, d ); // compiler creates and calls my_swap( fl
cout << "On swapping <c, d>: " << c << " " << d;
return 0;
}
//Output:
//Enter two Characters <chl, ch2>: a b
//On swapping <chl, ch2>: b a
//Enter two integers <a, b>: 3 5
//On swapping <a, b>: 5 3
//Enter two floats <c, d>: 3.5 6.8
//On swapping <c, d>: 6.8 3.5
Storage Classes
C++ provides several storage classes that determine the scope, lifetime, and
accessibility of variables. The main storage classes are auto , register , static , and
extern .
auto Storage Class
The auto storage class is the default storage class for all local variables. It
specifies that the variable has a local scope and a lifetime limited to the block in
which it is defined.
auto is rarely used for local variables since it's the default.
Scope: Local scope within the block or function where they are defined.
Extent: Limited to the block or function execution; destroyed upon block or
function exit.
register Storage Class
Problem Solving and Computer Programming 43
The register storage class suggests that the variable should be stored in a CPU
register for faster access. However, the compiler may ignore this suggestion since
modern compilers are optimized.
The register keyword is rarely used because compilers are often better at optimizing
variable storage than programmers.
Scope: Local scope within the block or function where they are defined.
Extent: Limited to the block or function execution; destroyed upon block or
function exit.
static Storage Class
The static storage class is used for variables that persist throughout the
program's lifetime. Static variables have local scope within the function or block
but retain their
values between function calls
. They are initialised only once.
Scope: Local (if within a block or function) or global (if outside any function).
Extent: Local static variables persist throughout program execution, retaining
values across function calls. Global static variables are accessible from any part
of the program.
extern Storage Class
The extern storage class is used to declare variables that are defined in other
files. It tells the compiler that the variable is defined externally and should be linked
at the linking phase.
Scope: Global within the file where declared; used for accessing variables
defined in other files.
Extent: Depends on the storage duration of the referenced variable.
// File1.cpp
int globalVar = 42;
// File2.cpp
#include <iostream>
extern int globalVar; // Declare 'globalVar' defined in anothe
int main()
{
Problem Solving and Computer Programming 44
cout << "GlobalVar: " << globalVar << endl;
return 0;
}
//Output:
//GlobalVar: 42
Structures
Structures combine logically related data items into a single unit. The data items
enclosed within a structure are known as members and they can be of the same or
different data types. Hence, a structure can be viewed as a heterogeneous user-
defined data type. It can be used to create variables, which can be manipulated in
the same way as variables of standard data types. It encourages better
organization and management of data in a program.
The individual members of a structure can be variables of built-in data types,
pointers, arrays, or even other structures.
The period or dot(.) operator is used to access the members of a structure
independently. The dot operator connects a structure variable and its member.
Syntax:
struct struct_name {
// Member variables (fields)
data_type member1_name;
data_type member2_name;
// ...
};
Example:
#include <iostream>
using namespace std;
struct student {
Problem Solving and Computer Programming 45
int roll_no;
char name[25];
char branch[15];
int marks;
};
int main() {
// Creating a variable of type student and initializing i
struct student s1 = {1, "Om", "Mechanical", 100}; // Using
// Accessing and printing the 'name' member of the struct
cout << s1.name << endl;
return 0;
}
Array of structures
#include <iostream>
using namespace std;
struct student {
int roll_no;
char name[25];
char branch[15];
int marks;
};
int main() {
cout<<"Enter the size of the array: "<<endl;
cin>>size;
student students[size]; // Array of structures to store s
// Inputting data for each student using a for loop
for (int i = 0; i < size; ++i) {
cout << "Enter details for student " << i + 1 << ":
cout << "Roll No: ";
Problem Solving and Computer Programming 46
cin >> students[i].roll_no;
cout << "Name: ";
cin>>students[i].name;
cout << "Branch: ";
cin>>students[i].branch;
cout << "Marks: ";
cin >> students[i].marks;
cout << endl;
}
return 0;
}
Nesting of structures
A member of a structure may itself be a structure. Such nesting enables building of
very powerful data structures.
For example, here, the student structure can be enhanced to accommodate the date
of birth of a student.
#include <iostream>
using namespace std;
struct date {
int day;
int month;
int year;
}
struct student {
int roll_no;
char name[25];
struct date birthday;
char branch[15];
int marks;
Problem Solving and Computer Programming 47
};
int main() {
// Creating a variable of type student and initializing i
student s1 = {1, "Vivek", "Mechanical", 100};
// Accessing and printing the 'name' member of the struct
cout << s1.name << endl;
return 0;
}
Problem Solving and Computer Programming 48
Structures and Functions
Structure variables or an array of structure variables may be passed to functions just
like any other variables. It is also possible for functions to return structure variables
through the use of the return statement.
//Passing Structure to a Function
Passing Structure to a Function
void show(student stu) //taking structure type parameter
{
cout<<"Name"<<stu.name<<endl;
cout<<"Roll number:"<<stu.roll_no<<endl;
cout<<"Branch:"<<stu.branch<<endl;
cout<<"Marks:"<<stu.marks<<endl;
}
//Returning Structure from Function
student read()
{
student stu;
cout<<"Name"<<endl;
cin>>stu.name;
cout<<"Roll number:"<<endl;
cin>>stu.roll_no;
cout<<"Branch:"<<endl;
cin>>stu.branch;
cout<<"Marks:"<<endl;
cin>>stu.marks;
return stu; //returning structure type variable
}
Unions
A union is a user-defined data type that allows you to store different data types in
the same memory location. Unlike structures, where each member has its own
Problem Solving and Computer Programming 49
memory space, members of a union share the same memory location.
The amount of memory required to store a structure variable is the sum of the
size of all the members. On the other hand, in the case of unions, the amount of
memory required is always equal to that required by its largest member.
Members of the union can be accessed using either the dot . or the arrow ->
operator. It is similar to accessing the structure variable. Only one member of a union
can be accessed at any given time. This is because, at any instant, only one of the
union variables can be active.
Syntax:
Object Oriented Programming and Classes
Object-oriented modeling is a modern approach to problem-solving that revolves
around real-world concepts. In this methodology, objects are the fundamental
building blocks, created through programming constructs known as classes. These
classes encapsulate both data and functions related to a specific concept into
a single unit.
Class
Problem Solving and Computer Programming 50
A class is a user-defined data type which is like a blueprint, defining the
structure and behavior of the objects of that class. The process of creating
variables (instances) based on a class is called class instantiation, and these
variables are referred to as objects. Each object is a unique instance of its class.
Within a class, we find two key components:
1. Data Members: These represent the variables of an object. By default, these are
private.
2. Member Functions: These define the actions or operations that can be
performed on the data members. By default, these are public.
private , public , and protected are access specifiers that determine the visibility and
accessibility of class members (data members and member functions) within the
class and from outside the class.
private members are only accessible within the class.
public members are accessible from anywhere.
protected members are accessible within the class and its derived classes.
Syntax:
class ClassName {
private:
data_type privateMember1;
data_type privateMember2;
// ...
public:
return_type memberFunction1(data_type param1, data_ty
return_type memberFunction2(data_type param1, data_ty
// ...
};
return_type CLassName::memberFunction1(data_type param1, data_
//function body of memberFunction1
}
return_type CLassName::memberFunction2(data_type param1, data_
//function body of memberFunction2
Problem Solving and Computer Programming 51
}
//...
Example:
class ratio{
private:
int num, den;
public:
void read(){
cout<<"Enter the numerator: ";
cin>>num;
cout<<"Enter the denominator: ";
cin>>den;
}
void print(){
cout<<num<<"/"<<den<<endl;
}
double convert(){
double r = num/den;
return r;
}
};
The difference between structures and classes is that all the members of structures
are public by default whereas, the members of classes are private by default. Class
follows the principle that the information about a module should be private to the
module unless it is specifically declared public.
Constructor
A constructor is a special member function that allocates memory and initializes
the object of a class. It is automatically called when an object is created to set its
initial state or perform any necessary setup.
Problem Solving and Computer Programming 52
It has the same name as the class to which it belongs.
It has no return type and return statement.
A constructor which takes no arguments is called a default constructor.
Example of a constructor:
#include <iostream>
using namespace std;
class ComplexNumber {
private:
double real;
double imaginary;
public:
//Default constructor
ComplexNumber() {
real = 0;
imaginary = 0;
}
};
Constructor overloading
An interesting feature of the constructors is that a class can have multiple
constructors. This is called constructor overloading. All the constructors have the
same name as the corresponding class, and they differ only in terms of their
signature (in terms of the number of arguments, or data types of their arguments, or
both).
In such a case, a constructor is invoked during the creation of an object depending
on the number and type of arguments passed.
Example:
Problem Solving and Computer Programming 53
Destructor
A destructor is a special (public) member function of a class that is responsible for
releasing resources held by an object.
The destructor has the same name as the class but is preceded by a tilde ~ .
Destructors are automatically called when an object goes out of scope or is explicitly
deleted using the delete operator.
Destructors have no return type, and they don't take any parameters/arguments.
Binary Operator Overloading
Binary operator overloading allows you to define custom behaviors for operators
when they are applied to objects of user-defined classes. This means you can use
operators like + , - , * , / , and more with your custom data types, making your
code more intuitive and readable. It provides a way to define how two objects of
your class should interact when operated upon with a binary operator.
Here's an example of how you can create a class for complex numbers and overload
the + operator for two complex numbers:
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r, double i){
Problem Solving and Computer Programming 54
real = r;
imag = i;
}
// Overloading the + operator for adding two complex
Complex operator+(Complex other){
Complex temp;
temp.real = real + other.real;
temp.imag = imag + other.imag;
return temp;
}
// Display the complex number
void display(){
cout << real << " + " << imaginary << "i" << endl
}
};
int main() {
Complex num1(3, 4);
Complex num2(1, 2);
Complex sum = num1 + num2;
cout << "Result of addition: ";
sum.display();
return 0;
}
In this code:
1. We define a Complex class to represent complex numbers, with real and
imaginary parts.
2. Inside the class, we overload the + operator by defining the operator+ member
function. This function takes another Complex object ( other ) as a parameter and
returns a new Complex object that represents the sum of the two complex
numbers.
Problem Solving and Computer Programming 55
3. The display member function is used to display the complex number.
4. In the main function, we create two Complex objects, num1 and num2 , and then
add them using the + operator.
5. The result of the addition is stored in the sum object, and we display the result
using the display member function.
Friend Functions
A friend function is a function that is not a member of a class but has access to its
private and protected members. A friend function is declared within a class, but
it is defined outside of the class scope.
A friend function can access private and protected members of the class for which it
is declared as a friend.
Friend functions are declared within the class using the friend keyword.
A function can be friend to any number of classes.
A friend function is used to bridge classes.
Friend function allows a more obvious syntax for calling a function rather than
what a member function can do.
It is used to increase the versatility of overloaded functions.
Example:
#include <iostream>
using namespace std;
class Car {
private:
int speed;
public:
Car(int initialSpeed) {
speed = initialSpeed;
}
Problem Solving and Computer Programming 56
// Friend function declaration
friend bool isCarMoving(const Car& car1);
};
// Friend function definition
bool isCarMoving(const Car& car1) {
// Compare the speed of the car
return (car1.speed > 0);
}
int main() {
Car car1(50); // Speed of car1 is 50
// Check if the caris moving using the friend function
if (isCarMoving(car1)) {
cout << "The car is moving!" << endl;
} else {
cout << "The car is not moving." << endl;
}
return 0;
}
Friend Classes
Similar to friend functions, we can also declare an entire class as a friend of
another class. This allows all the member functions of the friend class to access the
private and protected members of the other class.
#include <iostream>
using namespace std;
class Boy {
private:
int boyNumber;
Problem Solving and Computer Programming 57
int age;
public:
Boy(const int phNum, int age){
boyNumber = phNum;
age = age;
}
// Declaration of Girl class as a friend
friend class Girl;
};
class Girl {
public:
// Function to access private members of Boy
void displayBoyInfo(const Boy& boy);
private:
int girlNumber;
};
// Definition of the function to access private members of Boy
void Girl::displayBoyInfo(const Boy& boy) {
cout << "Girl accessing Boy's info:" << endl;
cout << "Boy's Number: " << boy.boyNumber << endl;
cout << "Boy's Age: " << boy.age << endl;
}
int main() {
Boy Pradeep(123456789, 26);
Girl Nikitha;
// Girl accesses and displays information from Boy
Nikitha.displayBoyInfo(Pradeep);
Problem Solving and Computer Programming 58
return 0;
}
In this example:
The Girl class is declared as a friend of the Boy class, allowing the Girl class
to access private members of the Boy class.
The Boy class has private members boyNumber and age .
The Girl class has a function displayBoyInfo that takes a Boy object as a
parameter and can access and display the private information of the Boy class.
Inheritance
Inheritance is a technique of organizing information in a hierarchical form. It is like a
child inheriting the features of its parents.
Inheritance allows new classes to be built from older and less specialized classes
instead of being rewritten from scratch.
Inheritance, a prime feature of OOP, can be stated as the process of creating new
classes (called derived classes), from the existing classes (called base classes).
The derived class inherits the features of the base class (depending on the visibility
mode and level of inheritance) and adds its own features.
Problem Solving and Computer Programming 59
Derived class accesses features of the base class and not vice versa.
Syntax:
The visibility mode enclosed within the square brackets implies that it is optional. The
default visibility mode is private. It specifies whether the features of the base class
are publicly or privately inherited.
Problem Solving and Computer Programming 60
Forms of inheritance
(a)Single Inheritance: Derivation of a class from only one base class.
(b)Multiple Inheritance: Derivation of a class from several (two or more) base
classes.
(c)Hierarchical Inheritance: Derivation of several classes from a single base class,
i.e., the traits of one class may be inherited by more than one class.
(d)Multilevel Inheritance: Derivation of a class from another derived class.
(e)Hybrid Inheritance: Derivation of a class involving more than one form of
inheritance.
Problem Solving and Computer Programming 61
(f)Multipath Inheritance: Derivation of a class from other derived classes, which are
derived from the same base class.
Constructors of the base class and the derived class are automatically invoked when
the
derived class is instantiated. The constructors of the base class are invoked first and
then the constructors of the derived class.
Abstract Classes:
An abstract class is one that has no instances and is not designed to create objects.
An
abstract class is only designed to be inherited.
Example codes:
multipath_inheritance.cpp
multiple_inheritance.cpp
hierarchical_inheritance.cpp
Problem Solving and Computer Programming 62
multilevel_inheritance.cpp
hybrid_inheritance.cpp
File Management
File management involves reading from and writing to files on a computer's file
system. We can use the fstream library to handle file operations in C++.
Opening Files:
To open a file for reading or writing, you can use the open method. You specify the
file's name and the mode (e.g., ios::in for input or ios::out for output) in the open call.
If the file doesn't exist, it will be created when opened for writing.
Closing Files:
It's important to close the files once you are done with them using the close method.
This ensures that all data is written to the file, and the file resources are released.
#include <iostream>
#include <fstream>
using namespace std;
fstream fin, fout;
int main(){
fin.open("input.txt", ios::in);
fout.open("output.txt", ios::out);
fin.close();
fout.close();
}
Problem Solving and Computer Programming 63
Reading from Files :
To read from a file, use the >> operator along with the fstream object. You can read
various data types from the file, including integers, strings, and more.
Writing to Files:
To write to a file, use the << operator along with the fstream object. You can write
data of various types, similar to how you read data.
Example :
int value = 1;
fin >> value; // Reads an integer from the file
int a = 3;
fout << text; // Writes the string to the file
File modes
ios::in : Input mode, used for reading from a file.
ios::out : Output mode, used for writing to a file.
ios::ate : Open the file and seek to the end.
ios:app : Append mode, it always appends the data (writes data at the end of the
file).
ios::trunc : Truncates the file if it already exists.
ios::nocreate : Open fails if the file does not exist.
ios::binary : Opens the file as a binary file (rather than text).
ios::noreplace : Open fails if the file already exists.
Seek calls
Seek calls refer to functions or methods that manipulate the position of the file
pointer within a file. The file pointer is an indicator that points to the current position
in a file, and seek operations allow you to move this pointer to different locations
within the file. This is particularly useful when reading from or writing to files.
seekg : Used with input file streams to move the input file pointer.
seekp : Used with output file streams to move the output file pointer.
Problem Solving and Computer Programming 64
Example:
inputFile.seekg(10, ios::beg); // Move 10 bytes from the begi
Strings
Strings are used in programming languages for storing and manipulating text, such
as
words, names, and sentences.
A string is represented as an array of characters and the end of the string is marked
by the
NULL (‘0’) character.
String constants are enclosed in double quotes. For instance, “Hello World” is a
string.
An array of characters representing a string is defined as follows:
char array-name[size];
Menu Driven C++ Code for String Operations without using STL of C++:
#include <iostream>
using namespace std;
class mystring
{
private:
char str[100]; // Assuming a character array of size 1
public:
mystring()
{
str[0] = '0'; // Initialize the character array
}
// Function to get mystring length
Problem Solving and Computer Programming 65
int length() const
{
int len = 0;
while (str[len] != '0')
{
++len;
}
return len;
}
// Function to concatenate mystrings
mystring concatenate(const mystring& other) const
{
mystring result;
int len = this->length();
for (int i = 0; i < len; ++i)
{
result.str[i] = this->str[i];
}
int j = 0;
while (other.str[j] != '0')
{
result.str[len + j] = other.str[j];
++j;
}
result.str[len + j] = '0'; // Null-terminate the result
return result;
}
// Function to compare mystrings
int compare(const mystring& other) const
{
int i = 0;
while (this->str[i] != '0' && other.str[i] != '0' && thi
{
++i;
}
return this->str[i] - other.str[i];
Problem Solving and Computer Programming 66
}
// Function to reverse the mystring
mystring reverse() const
{
mystring result;
int len = this->length();
for (int i = 0; i < len; ++i)
{
result.str[i] = this->str[len - i - 1];
}
result.str[len] = '0'; // Null-terminate the result
return result;
}
// Operator overloading for concatenation using +
mystring operator+(const mystring& other) const
{
return this->concatenate(other);
}
// Function to enter the mystring
void enter()
{
cout << "Enter the mystring: ";
cin.ignore(); // Clear the input buffer
cin.getline(str, sizeof(str));
}
// Function to display the mystring
void display() const
{
cout << "mystring: " << str << endl;
}
};
int main()
{
Problem Solving and Computer Programming 67
mystring str1, str2, result;
int choice;
do
{
cout<< "nmystring Operations Menu:n"
<< "1. Enter mystring 1n"
<< "2. Enter mystring 2n"
<< "3. mystring Lengthn"
<< "4. Concatenate mystringsn"
<< "5. Compare mystringsn"
<< "6. Reverse mystringn"
<< "7. Exitn"
<< "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
str1.enter();
break;
case 2:
str2.enter();
break;
case 3:
cout << "mystring 1 Length: " << str1.length() <<
cout << "mystring 2 Length: " << str2.length() <<
break;
case 4:
result = str1 + str2;
cout << "Concatenated mystring: ";
result.display();
break;
case 5:
if (str1.compare(str2) == 0)
{
cout << "mystrings are equal.n";
}
else
Problem Solving and Computer Programming 68
{
cout << "mystrings are not equal.n";
}
break;
case 6:
cout << "Reversed mystring 1: ";
str1.reverse().display();
cout << "Reversed mystring 2: ";
str2.reverse().display();
break;
case 7:
cout << "Exiting program.n";
break;
default:
cout << "Invalid choice. Please try again.n";
}
} while (choice != 7);
return 0;
}

More Related Content

Similar to Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf

Similar to Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf (20)

C operators
C operatorsC operators
C operators
 
Token and operators
Token and operatorsToken and operators
Token and operators
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
 
Types of Operators in C
Types of Operators in CTypes of Operators in C
Types of Operators in C
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Intro to CS Lec03 (1).pptx
Intro to CS Lec03 (1).pptxIntro to CS Lec03 (1).pptx
Intro to CS Lec03 (1).pptx
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C language
C languageC language
C language
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
TOPIC-2-Expression Variable Assignment Statement.pdf
TOPIC-2-Expression Variable Assignment Statement.pdfTOPIC-2-Expression Variable Assignment Statement.pdf
TOPIC-2-Expression Variable Assignment Statement.pdf
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdf
 

Recently uploaded

KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 

Recently uploaded (20)

KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 

Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf

  • 1. Problem Solving and Computer Programming 1 Problem Solving and Computer Programming Data Types Operators- arithmetic, relational, logical, bitwise, pointer, miscalleneous Decision making Statements Loops Jump statements Escape sequences Arrays Searching Sorting Pointers and references Functions Methods of passing parameters Recursion Function overloading/polymorphism, Function templating Storage classes Structures Unions OOP and Classes: Class Constructor
  • 2. Problem Solving and Computer Programming 2 Destructor Binary operator overloading Friend functions Friend Classes Inheritance File management Strings Data Types Data types define the type of data that a variable can hold. Primary/Fundamental Data Types 1. Integer Types: int : Integer type, representing whole numbers. short : Short integer type.
  • 3. Problem Solving and Computer Programming 3 long : Long integer type. 2. Floating-Point Types: float : Single-precision floating-point type. double : Double-precision floating-point type. long double : Extended precision floating-point type. 3. Character Types: char : Character type, representing a single character. wchar_t : Wide character type. 4. Boolean Type: bool : Boolean type, representing true or false values. Derived Data Types 1. Function : A derived data type that encapsulates executable code, declared with a return type and parameters. 2. Array : Collection of elements of the same data type arranged in a fixed-size sequence. 3. Pointer : A variable that stores the memory address of another variable. 4. Reference : An alternative name for an existing variable. User-defined Data Types 1. Class : A user-defined data type that can encapsulate data members and member functions. 2. Structure : A user-defined composite data type that groups variables of different data types under a single name. 3. Union : Similar to a structure, but it uses the same memory location for all its members, allowing different data types to share the same memory space. 4. Enum : A user-defined data type consisting of named integer constants. typedef : It is a keyword used to create an alternate name for a data type, enhancing code readability and providing a convenient way to declare complex or compound data types.
  • 4. Problem Solving and Computer Programming 4 Example: typedef long int lint; lint x1,x2;//declares long integers x1 and x2 Operators Operators are symbols that perform operations on operands, which can be variables, constants, or expressions. They can be classified into the following major types: Unary operators Unary operators operate on a single operand. Prefix Increment ( ++x ): Increments the value of x before its current value is used and the updated value is immediately available for use in the expression. Example: int x = 5; int y = ++x; // y is 6, x is 6 Postfix Increment ( x++ ): Uses the current value of x in an expression before incrementing it and the update occurs after the current value is used. Example: int x = 5; int y = x++; // y is 5, x is 6 Add and Assign ( += ): Adds the right operand to the left operand and assigns the result to the left operand.
  • 5. Problem Solving and Computer Programming 5 int a = 3; a += 2; // Equivalent to a = a + 2; a is now 5 Operators like -- , -= , *= , /= , %= also work accordingly. Binary operators Binary operators operate on two operands. Arithmetic Operators: 1. + (Addition): Adds two operands. 2. - (Subtraction): Subtracts the right operand from the left operand. 3. * (Multiplication): Multiplies two operands. 4. / (Division): Divides the left operand by the right operand. 5. % (Modulus): Returns the remainder of the division of the left operand by the right operand. Relational Operators: 1. == (Equal to): Checks if the values of two operands are equal. 2. != (Not equal to): Checks if the values of two operands are not equal. 3. > (Greater than): Checks if the value of the left operand is greater than the value of the right operand. 4. < (Less than): Checks if the value of the left operand is less than the value of the right operand. 5. >= (Greater than or equal to): Checks if the value of the left operand is greater than or equal to the value of the right operand. 6. <= (Less than or equal to): Checks if the value of the left operand is less than or equal to the value of the right operand. Logical Operators: 1. && (Logical AND): Returns true if both operands are true. 2. || (Logical OR): Returns true if at least one of the operands is true. 3. ! (Logical NOT): Returns true if the operand is false and vice versa.
  • 6. Problem Solving and Computer Programming 6 Bitwise Operators: 1. & (Bitwise AND): Performs bitwise AND operation on corresponding bits of two operands. 2. | (Bitwise OR): Performs bitwise OR operation on corresponding bits of two operands. 3. ^ (Bitwise XOR): Performs bitwise XOR (exclusive OR) operation on corresponding bits of two operands. 4. ~ (Bitwise NOT): Flips the bits of the operand, changing 1s to 0s and vice versa. 5. << (Left Shift): Shifts the bits of the left operand to the left by a specified number of positions. 6. >> (Right Shift): Shifts the bits of the left operand to the right by a specified number of positions. Pointer operators: 1. & (Address-of Operator): Returns the memory address of a variable. 2. * (Pointer Declaration): Declares a pointer variable or dereferences a pointer, depending on the context. Miscalleneous Operators: 1. = (Assignment Operator): Assigns the value of the right operand to the left operand. 2. sizeof : Returns the size, in bytes, of an object or data type. 3. :: (Scope Resolution Operator): Specifies the scope of a variable or function, especially in the context of namespaces and classes. 4. new : Dynamically allocates memory for a variable or object during runtime. 5. delete : Deallocates memory that was previously allocated using new . 6. ? : (Ternary Conditional Operator): A shorthand way of writing an if-else statement, allowing conditional expressions. 7. . ( Dot operator): Member access 8. -> (Arrow operator): Member access through pointer
  • 7. Problem Solving and Computer Programming 7 Decision-Making Statements Decision-making statements are used to control the flow of a program based on certain conditions. If statement Executes a block of code if the specified condition is true. If the condition is false, the code block is skipped. Syntax: if (condition) { // Code to execute if the condition is true } Example: int x = 10; if (x > 5) { cout << "x is greater than 5." << endl; } If - else Statement Executes one block of code if the condition is true and another block if the condition is false. Syntax: if (condition) { // Code to execute if the condition is true } else {
  • 8. Problem Solving and Computer Programming 8 // Code to execute if the condition is false } Example: int x = 3; if (x > 5) { cout << "x is greater than 5." << endl; } else { cout << "x is not greater than 5." << endl; } If - else if - else Statement Allows you to specify multiple conditions and execute different code blocks based on which condition is true. It's used for choosing from several options. Syntax: if (condition1) { // Code to execute if condition1 is true } else if (condition2) { // Code to execute if condition2 is true } //... else { // Code to execute if neither condition1 nor conditio } Example:
  • 9. Problem Solving and Computer Programming 9 int x = 7; if (x < 5) { cout << "x is less than 5." << endl; } else if (x == 5) { cout << "x is equal to 5." << endl; } else { cout << "x is greater than 5." << endl; } //Output: x is greater than 5. Switch Statement Provides a way to select one of many code blocks to execute based on the value of an expression. It's often used for menu-like selection. Syntax: switch (expression) { case value1: // Code to execute if expression matches value1 break; case value2: // Code to execute if expression matches value2 break; // ... default: // Code to execute if none of the cases match } Example: int choice = 2; switch (choice)
  • 10. Problem Solving and Computer Programming 10 { case 1: cout << "You chose option 1." << endl; break; case 2: cout << "You chose option 2." << endl; break; case 3: cout << "You chose option 3." << endl; break; default: cout << "Invalid choice." << endl; } //Output: You chose option 2. Conditional (Ternary) Operator Offers a concise way to choose between two expressions based on a condition. It returns one of two values depending on whether the condition is true or false. Syntax: (condition) ? expression_if_true : expression_if_false; Example: int x = 7; string result = (x > 5) ? "x is greater than 5" : "x is not g cout << result << endl; return 0; //Output : x is greater than 5 These decision making statements can be nested to handle more complex decision- making scenarios where you need to evaluate multiple conditions within a hierarchical structure.
  • 11. Problem Solving and Computer Programming 11 Loop Statements Loop statements are used to repeatedly execute a block of code as long as a specific condition is met. for Loop The for loop is commonly used for iterating over a range or sequence of values. It includes an initialization step, a condition to check before each iteration, and an updation step that is executed after each iteration. Syntax: for (initialization; condition; update) { // Code to repeat while the condition is true } Example: for (int i = 0; i < 5; ++i) { cout<<i<<" "; } //output: 0 1 2 3 4 while Loop The while loop repeatedly executes a block of code as long as the specified condition is true. It does not require an initialization step, but it's crucial to ensure that the condition eventually becomes false to avoid an infinite loop. Syntax: while (condition) { // Code to repeat while the condition is true }
  • 12. Problem Solving and Computer Programming 12 Example: int i = 0; while (i < 5) { cout<< i<<" "; i++; } //output: 0 1 2 3 4 do-while Loop The do-while loop is similar to the while loop, but it guarantees that the code block is executed at least once before checking the initial condition. The loop continues as long as the condition remains true. Syntax: do { // Code to repeat at least once } while (condition); Example: int i = 0; do { cout << i << " "; i++; } while (i < 5); //output: 0 1 2 3 4 Example to show the difference between the working of while and do-while loops: int i = 0; while (i < 0) { cout << i << " "; i++;
  • 13. Problem Solving and Computer Programming 13 } // No output In a while loop with the condition i < 0 , the loop body would not be executed at all because the initial value of i is 0, which does not satisfy the condition. int i = 0; do { cout << i << " "; i++; } while (i < 0); //output: 0 In a do-while loop with the condition i < 0 , the loop body would be executed at least once before checking the condition. The output would be 0 , and the loop would terminate after the first iteration. The do-while loop guarantees at least one execution of the loop body before evaluating the condition. Nesting of these loop statements allows for the creation of complex and structured control flow, enabling the execution of repetitive tasks within other repetitive tasks. Nesting loop statements with decision-making (conditional) statements allows for executing certain blocks of code repeatedly based on conditions, leading to more flexible and powerful program logic. Jumping Statements Jumping statements change the normal flow of control within a program. The main jumping statements are break , continue , return and goto . The break and continue statements are generally used within loops ( for , while , do- while ) and switch statements. 1. break : Terminates the innermost loop or switch statement and transfers control to the statement following the terminated loop or switch.
  • 14. Problem Solving and Computer Programming 14 2. continue : Skips the rest of the loop's code and proceeds to the next iteration of the loop. 3. return : Terminates the execution of a function and returns a value (if applicable) to the calling function. 4. goto : Transfers control to a labeled statement in the program. Note: Using goto is generally discouraged due to its potential to create unreadable and unmaintainable code. Escape Sequences Escape sequences are special combinations of characters that represent non- printable or special characters. Commonly used escape sequences: 1. t : Horizontal tab character 2. v : Vertical tab character 3. n : Newline character, indicating a new line 4. a : Produces an audible alert or beep 5. : Represents a backslash character 6. " : Represents a double quote character within a string 7. ' : Represents a single quote character within a string 8. b : Backspace character 9. r : Carriage return character → move the cursor or print-head back to the beginning of the line. Arrays Arrays are used to store a collection of elements of the same data type under a single name. They provide a way to efficiently manage and access multiple values
  • 15. Problem Solving and Computer Programming 15 using a single identifier. They provide a convenient way to manage and iterate over sequential data. Syntax: data_type array_name[array_size]={element1, element2, element3 //The number of elements the array can store is the value of a data_type : Specifies the type of elements the array will hold. array_name : The name assigned to the array. array_size : The number of elements the array can hold. Indexing: Array elements are accessed using their index, starting from 0 for the first element and incrementing by 1 for each subsequent element. array_name[index] Examples: #include <iostream> using namespace std; int main() { // Declaration and initialization of an integer array int numbers[5] = {10, 20, 30, 40, 50}; // Accessing and printing array elements cout << "Element at index 0: " << numbers[0] << endl; cout << "Element at index 2: " << numbers[2] << endl; return 0; } //Output: //Element at index 0: 10 //Element at index 2: 30 Taking input from the user:
  • 16. Problem Solving and Computer Programming 16 #include <iostream> using namespace std; int main() { cout<<"Enter the size of the array: "; cin>>size; int numbers[size]; cout<<"Enter the elements: "; for(int i=0;i<size;i++){ cin>>numbers[i]; } return 0; } 2D Arrays A two-dimensional array is a data structure that represents a grid or matrix of elements arranged in rows and columns. It can be visualized as an array of arrays, where each element in the array is itself an array. This structure allows for the representation of tables, matrices, and other two-dimensional data. Accessing elements in a 2D array requires specifying both the row and column indices. Example: #include <iostream> using namespace std; int main() { int rows1, cols1, rows2, cols2; //Inputting the matrices cout<<"Enter the number of rows of matrix 1: "; cin>>rows1; cout<<"Enter the number of columns of matrix 1: ";
  • 17. Problem Solving and Computer Programming 17 cin>>cols1; cout<<"Enter the number of rows of matrix 2: "; cin>>rows2; cout<<"Enter the number of columns of matrix 2: "; cin>>cols2; int matrix1[rows1][cols1]; int matrix2[rows2][cols2]; cout<<"Enter the elements of matrix 1: "; for(int i=0;i<rows1;i++){ for(int j=0;j<cols1;j++){ cin>>matrix1[i][j]; } } cout<<"Enter the elements of matrix 2: "; for(int i=0;i<rows2;i++){ for(int j=0;j<cols2;j++){ cin>>matrix2[i][j]; } } //Displaying the matrices cout<<"Matrix 1: "<<endl; for(int i=0;i<rows1;i++){ for(int j=0;j<cols1;j++){ cout<<matrix1[i][j]<<" "; } cout<<endl; } cout<<"Matrix 2: "<<endl; for(int i=0;i<rows2;i++){ for(int j=0;j<cols2;j++){ cout<<matrix2[i][j]<<" ";
  • 18. Problem Solving and Computer Programming 18 } cout<<endl; } //Adding the matrices if(rows1==rows2 && cols1==cols2){ int result[rows1][cols1]; for(int i=0;i<rows1;i++){ for(int j=0;j<cols1;j++){ result[i][j] = matrix1[i][j] + matrix2[i][j]; } } cout<<"Addition matrix: "; for(int i=0;i<rows1;i++){ for(int j=0;j<cols1;j++){ cout<<result[i][j]<<" "; } cout<<endl; } } else{ cout<<"Matrix addition is not possible!"<<endl; } //Subtracting the matrices if(rows1==rows2 && cols1==cols2){ int result[rows1][cols1]; for(int i=0;i<rows1;i++){ for(int j=0;j<cols1;j++){ result[i][j] = matrix1[i][j] - matrix2[i][j]; } } cout<<"Subtraction matrix: "; for(int i=0;i<rows1;i++){
  • 19. Problem Solving and Computer Programming 19 for(int j=0;j<cols1;j++){ cout<<result[i][j]<<" "; } cout<<endl; } } else{ cout<<"Matrix subtraction is not possible!"<<endl; } //Multiplying the matrices if(cols1==rows2){ int common = cols1; int result[rows1][cols1]; for(int i=0;i<rows1;i++){ for(int j=0;j<cols1;j++){ result[i][j] =0; for(int k=0;k<common;k++){ result[i][j] += matrix1[i][k]*matrix2[k][j } } } cout<<"Multiplication matrix: "; for(int i=0;i<rows1;i++){ for(int j=0;j<cols1;j++){ cout<<result[i][j]<<" "; } cout<<endl; } } else{ cout<<"Matrix multiplication is not possible!"<<endl; } return 0; }
  • 20. Problem Solving and Computer Programming 20 Character arrays A character array is an array of characters. It is a data structure that allows you to store a sequence of characters under a single identifier. Character arrays are used to represent strings in C++. They are null-terminated, meaning that the end of the string is marked by a null character ( 0 ). This null character is automatically appended when a character array is initialised. #include <iostream> using namespace std; int main() { const int arraySize = 10; char greeting[arraySize] = "Hello"; cout << "The greeting is " << greeting << endl; return 0; } //Output: The greeting is Hello Searching Searching is an operation that finds the location of a given element in a list. The search is said to be successful or unsuccessful depending on whether the element that is to be searched is found or not. Here, we will discuss two standard searching methods - Linear search and Binary search. Linear Search
  • 21. Problem Solving and Computer Programming 21 #include <iostream> using namespace std; // Function to perform linear search int linearSearch(int arr[], int size, int key) { for (int i = 0; i < size; ++i) { if (arr[i] == key) { return i; // Return the index if the key is found } } return -1; // Return -1 if the key is not found } int main() { const int size = 5; int arr[size] = {10, 25, 30, 15, 20}; int key; cout << "Enter the element to search: "; cin >> key; int index = linearSearch(arr, size, key); if (index != -1) { cout << "Element found at index: " << index << endl; } else { cout << "Element not found in the array." << endl;
  • 22. Problem Solving and Computer Programming 22 } return 0; } Binary Search Example: #include <iostream> using namespace std; // Function to perform binary search int binarySearch(int arr[], int size, int key) { int low = 0; int high = size - 1; while (low <= high) { int mid = (low + (high - low)) / 2;
  • 23. Problem Solving and Computer Programming 23 if (arr[mid] == key) { return mid; // Return the index if the key is fou } else if (arr[mid] < key) { low = mid + 1; // Search in the right half } else { high = mid - 1; // Search in the left half } } return -1; // Return -1 if the key is not found } int main() { int size = 10; int arr[size] = {1, 2, 3, 9, 11, 13, 17, 25, 57, 90}; int key; cout << "Enter the element to search: "; cin >> key; int index = binarySearch(arr, size, key); if (index != -1) { cout << "Element found at index: " << index << endl; } else { cout << "Element not found in the array." << endl; } return 0; }
  • 24. Problem Solving and Computer Programming 24 Binary search using Recursion (refer Recursion topic) Sorting Sorting refers to arranging elements of a set in some order. The data is generally sorted in ascending or descending order. Bubble sort
  • 25. Problem Solving and Computer Programming 25 #include <iostream> using namespace std; // Function to perform bubble sort on an array void bubbleSort(int arr[], int size) { for (int i = 0; i < size - 1; i++) { // Outer loop for t for (int j = 0; j < size - i - 1; j++) { // Inner loo if (arr[j] > arr[j + 1]) { // If the current element is greater than the nex int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } // Display the sorted array cout << "The sorted array is: "; for (int i = 0; i < size; i++) { cout << arr[i] << " "; } } int main() { // Set the size of the array int size = 5; // Initialize the array with values int arr[size] = {25, 17, 31, 13, 2}; // Call the bubbleSort function to sort the array bubbleSort(arr, size);
  • 26. Problem Solving and Computer Programming 26 return 0; } Selection sort
  • 27. Problem Solving and Computer Programming 27 #include <iostream> using namespace std; // Function to perform selection sort on an array void selectionSort(int arr[], int size) { for (int i = 0; i < size - 1; i++) { // Outer loop for i for (int j = i + 1; j < size; j++) { // Inner loop fo if (arr[i] > arr[j]) { // If the current element i int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } // Display the sorted array cout << "The sorted array is: "; for (int i = 0; i < size; i++) { cout << arr[i] << " "; } } int main() { int size = 5; int arr[size] = {25, 17, 31, 13, 2};
  • 28. Problem Solving and Computer Programming 28 // Call the selectionSort function to sort the array selectionSort(arr, size); return 0; }
  • 29. Problem Solving and Computer Programming 29 Pointers and references Pointers Pointers are variables that store the memory address of another variable. They allow direct manipulation of memory and facilitate dynamic memory allocation. int x = 10; int* ptr = &x;//declares a pointer ptr to an integer and initi References References are alternative names for existing variables. They provide a way to manipulate variables indirectly. The reference must be initialized upon declaration and always refers to the same object. int x = 10; int& ref = x; //declares and initializes a reference to x //Now ref can be used like x to read or modify the value of t Dereferencing Dereferencing is retrieving the value at the memory address held by a pointer. It involves using the dereference operator * to retrieve the value associated with the pointer. int x = 10; int* ptr = &x; // ptr holds the address of x // Dereferencing the pointer to access the value at the memory int value = *ptr; // value now holds the value of x (10) Pointer to Pointer int x = 10; int* ptr1 = &x; // ptr1 holds the address of x
  • 30. Problem Solving and Computer Programming 30 int** ptr2 = &ptr1; // ptr2 holds the address of ptr1 // Dereferencing the double pointer to access the value of x int value = **ptr2; // value now holds the value of x (10) Here, ptr2 is a pointer to a pointer. It stores the memory address of ptr1 , which itself holds the address of the integer variable x . Functions A function in programming is a set of program statements used to perform a specific task. When invoked, a function operates as if its code is seamlessly integrated at the point of the function call. The interaction between the caller (the function making the call) and the callee (the function being called) occurs through parameters, allowing for effective communication and data exchange between different parts of the program. The advantages of functions include the following: 1. Modular programming 2. Reduction in the amount of work and development time 3. Program and function debugging is easier 4. Division of work is simplified due to the use of divide-and-conquer principle 5. Reduction in size of the program due to code reusability 6. Functions can be accessed repeatedly without redevelopment, which in turn promotes reuse of code 7. Library of functions can be implemented by combining well-designed, tested, and proven functions Syntax: return_type function_name(parameter1_type parameter1_name, pa // Function body
  • 31. Problem Solving and Computer Programming 31 // Statements to perform the desired task // Optional: return statement to return a value if the functio return return_value; } Function prototype A function prototype is a declaration of a function that tells the compiler about the function's name, return type, and the types of its parameters. A function prototype is typically placed at the beginning of a program or in a header file. return_type function_name(parameter_type parameter_name, ...) Function Calling Function calling involves invoking a function to execute its code. If the function has parameters, values are passed to the function during the call. Examples: // Function prototype int add(int a, int b); // Function definition int add(int a, int b) { return a + b; } // Function call int sum = add(3, 4); Roots of a quadratic equation : #include<iostream> #include<cmath> using namespace std;
  • 32. Problem Solving and Computer Programming 32 void quadratic(int a,int b,int c){ double disc,root1,root2,real,imag,root; disc = b*b-4*a*c; if(disc>0){ root1 = (-b + sqrt(disc))/2*a; root2 = (-b - sqrt(disc))/2*a; cout<<"The 2 real roots of this equation are: "<<root1 } else if(disc == 0){ root = -b/2*a; cout<<"There are 2 equal roots.Hence the root is: "<< } else{ real = -b/2*a; imag = sqrt(disc)/2*a; root1 = real + imag; root2 = real - imag; cout<<"The imaginary roots are: "<<root1<<" and "<<roo } } int main() { int a,b,c; cout<<"Enter the values of a , b , c: "; cin>>a>>b>>c; quadratic(a,b,c); } Sine of an angle: #include<iostream> #include<cmath> using namespace std; //factorial function
  • 33. Problem Solving and Computer Programming 33 double factori(double num) { double fact=1; for(int i=1;i<=num;i++){ fact = fact * i; } return fact; } //sine function void sine(double rad,int terms){ double sum=0; for(int i=0;i<terms;i++){ sum = sum +(pow(rad,2*i+1)*pow(-1,i))/factori(2*i+1); } cout<<"Sine of the angle is: "<<sum<<endl; } int main(){ int degree,terms; double rad; cout<<"Enter the angle in degrees: "; cin>>degree; rad = (M_PI*degree)/180; cout<<"Enter the no of terms till which you want to c cin>>terms; sine(rad,terms); } Methods of passing parameters
  • 34. Problem Solving and Computer Programming 34 Pass by Value In "pass by value," a copy of the argument is passed to the function. Any changes made to the parameter within the function do not affect the original argument. It is suitable for situations where you want to work with a local copy of the data and not modify the original. It's the default way of passing arguments to functions in C++. Example: void increment(int x) { x++; // Changes the local copy of x, not the original } int main() { int num = 5; increment(num); // num remains 5, as the function works with a copy of num return 0; } Pass by Pointer In "pass by pointer," a pointer to the argument is passed to the function. The function can modify the original data by dereferencing the pointer. Any changes made to the pointed-to data within the function affect the original data outside the function. Example: void increment(int* ptr) { (*ptr)++; // Modifies the original data } int main() { int num = 5; increment(&num);
  • 35. Problem Solving and Computer Programming 35 // num is now 6, as the function modified the original da return 0; } Pass by Reference In "pass by reference," a reference to the argument is passed to the function. The function operates directly on the original data, not on a copy. Changes made to the reference parameter within the function affect the original data outside the function. It's often used when you want to modify the original data without the overhead of pointer syntax. Example: void increment(int& ref) { ref++; // Modifies the original data } int main() { int num = 5; increment(num); // num is now 6, as the function modified the original da return 0; } Pass by Const Reference In "pass by const reference," a constant reference to the argument is passed to the function. The function can access the original data but cannot modify it. It's useful when you want to avoid making a copy of the data and ensure that the function does not accidentally modify it. It's commonly used for efficiency and safety. Example:
  • 36. Problem Solving and Computer Programming 36 void print(const int& ref) { // Can read the original data, but cannot modify it cout << ref << endl; } int main() { int num = 5; print(num); // The original data remains unchanged return 0; } Recursion A function which calls itself is called a recursive function. Recursive functions can be powerful and elegant tools for solving certain types of problems. Two important conditions which must be satisfied by any recursive function are the following: 1. Each time a function calls itself, it must be nearer, in some sense, to a solution. 2. There must be a decision criterion for stopping the process or computation. Example: // Recursive function to calculate factorial long factorial(int n) { // Base case if (n == 1) { return 1; } // Recursive case else { return n * factorial(n - 1); } }
  • 37. Problem Solving and Computer Programming 37 Binary search using Recursion #include <iostream> using namespace std; int recBinarySearch(int arr, int lower, int upper int key){ int mid = (lower + (upper - lower))/2; if(arr[mid] == key){ return mid; // Return the index if the key is found } else if(arr[mid] < key){ recBinarySearch(arr, lower, mid-1, key); // Search in } else if(arr[mid] > key) { recBinarySearch(arr, mid+1, upper, key); // Search } return -1; // Return -1 if the key is not found } int main() { int size = 10; int arr[size] = {1, 2, 3, 9, 11, 13, 17, 25, 57, 90}; int key; cout << "Enter the element to search: "; cin >> key; int index = recBinarySearch(arr, 0, size-1, key); if (index != -1) { cout << "Element found at index: " << index << endl; } else { cout << "Element not found in the array." << endl; } return 0; }
  • 38. Problem Solving and Computer Programming 38 Function Overloading Function polymorphism, also known as function overloading, is a concept that enables multiple functions to use the same name but with different parameter types. This allows a single function name to have multiple forms, each tailored to handle specific argument types. Function overloading, or function-name overloading, is the practice of associating one or more function bodies with the same function name.
  • 39. Problem Solving and Computer Programming 39 #include <iostream> using namespace std; void swap ( char& x, char& y ) { char t; // temporary used in swapping t = x; x = y; y = t; } void swap( int& x, int& y ) { int t; // temporary used in swapping t = x; x = y; y = t; } void swap( float& x, float& y ) { float t; // temporary used in swapping t = x; x = y; y = t; } int main() { char chl, ch2; cout << "Enter two Characters <chl, ch2>: "; cin >> chl >> ch2; swap( chl, ch2 ); cout << "On swapping <chl, ch2>: " << chl << " " << ch2 << int a, b; cout << "Enter two integers <a, b>: "; cin >> a >> b; swap( a, b );
  • 40. Problem Solving and Computer Programming 40 cout << "On swapping <a, b>: " << a << " " << b << endl; float c, d; cout << "Enter two floats <c, d>: "; cin >> c >> d; swap( c, d ); cout << "On swapping <c, d>: " << c << " " << d; return 0; } //Output: //Enter two Characters <chl, ch2>: a b //On swapping <chl, ch2>: b a //Enter two integers <a, b>: 3 5 //On swapping <a, b>: 5 3 //Enter two floats <c, d>: 3.6 2.4 //On swapping <c, d>: 2.4 3.6 Function Template A function template, also called a generic function, combines the functionalities of several functions differing only in data types. This allows us to write a single source declaration that can generate multiple functions tailored to various data types. Function templates provide a concise and flexible way to express the same logic for different types, promoting code reusability and simplicity. Syntax:
  • 41. Problem Solving and Computer Programming 41 Example: #include <iostream> using namespace std; template <class T> void my_swap( T& x, T& y ) { T t; // temporarily used in my_swap, template variable t = x; x = y; y = t; } int main() { char chl, ch2; cout << "Enter two Characters <chl, ch2>: "; cin >> chl >> ch2; my_swap( chl, ch2 ); // compiler calls my_swap( char &x, c cout << "On swapping <chl, ch2>: " << chl << " " << ch2 << int a, b; cout << "Enter two integers <a, b>: "; cin >> a >> b; my_swap( a, b ); // compiler creates and calls my_swap( i cout << "On swapping <a, b>: " << a << " " << b << endl;
  • 42. Problem Solving and Computer Programming 42 float c, d; cout << "Enter two floats <c, d>: "; cin >> c >> d; my_swap( c, d ); // compiler creates and calls my_swap( fl cout << "On swapping <c, d>: " << c << " " << d; return 0; } //Output: //Enter two Characters <chl, ch2>: a b //On swapping <chl, ch2>: b a //Enter two integers <a, b>: 3 5 //On swapping <a, b>: 5 3 //Enter two floats <c, d>: 3.5 6.8 //On swapping <c, d>: 6.8 3.5 Storage Classes C++ provides several storage classes that determine the scope, lifetime, and accessibility of variables. The main storage classes are auto , register , static , and extern . auto Storage Class The auto storage class is the default storage class for all local variables. It specifies that the variable has a local scope and a lifetime limited to the block in which it is defined. auto is rarely used for local variables since it's the default. Scope: Local scope within the block or function where they are defined. Extent: Limited to the block or function execution; destroyed upon block or function exit. register Storage Class
  • 43. Problem Solving and Computer Programming 43 The register storage class suggests that the variable should be stored in a CPU register for faster access. However, the compiler may ignore this suggestion since modern compilers are optimized. The register keyword is rarely used because compilers are often better at optimizing variable storage than programmers. Scope: Local scope within the block or function where they are defined. Extent: Limited to the block or function execution; destroyed upon block or function exit. static Storage Class The static storage class is used for variables that persist throughout the program's lifetime. Static variables have local scope within the function or block but retain their values between function calls . They are initialised only once. Scope: Local (if within a block or function) or global (if outside any function). Extent: Local static variables persist throughout program execution, retaining values across function calls. Global static variables are accessible from any part of the program. extern Storage Class The extern storage class is used to declare variables that are defined in other files. It tells the compiler that the variable is defined externally and should be linked at the linking phase. Scope: Global within the file where declared; used for accessing variables defined in other files. Extent: Depends on the storage duration of the referenced variable. // File1.cpp int globalVar = 42; // File2.cpp #include <iostream> extern int globalVar; // Declare 'globalVar' defined in anothe int main() {
  • 44. Problem Solving and Computer Programming 44 cout << "GlobalVar: " << globalVar << endl; return 0; } //Output: //GlobalVar: 42 Structures Structures combine logically related data items into a single unit. The data items enclosed within a structure are known as members and they can be of the same or different data types. Hence, a structure can be viewed as a heterogeneous user- defined data type. It can be used to create variables, which can be manipulated in the same way as variables of standard data types. It encourages better organization and management of data in a program. The individual members of a structure can be variables of built-in data types, pointers, arrays, or even other structures. The period or dot(.) operator is used to access the members of a structure independently. The dot operator connects a structure variable and its member. Syntax: struct struct_name { // Member variables (fields) data_type member1_name; data_type member2_name; // ... }; Example: #include <iostream> using namespace std; struct student {
  • 45. Problem Solving and Computer Programming 45 int roll_no; char name[25]; char branch[15]; int marks; }; int main() { // Creating a variable of type student and initializing i struct student s1 = {1, "Om", "Mechanical", 100}; // Using // Accessing and printing the 'name' member of the struct cout << s1.name << endl; return 0; } Array of structures #include <iostream> using namespace std; struct student { int roll_no; char name[25]; char branch[15]; int marks; }; int main() { cout<<"Enter the size of the array: "<<endl; cin>>size; student students[size]; // Array of structures to store s // Inputting data for each student using a for loop for (int i = 0; i < size; ++i) { cout << "Enter details for student " << i + 1 << ": cout << "Roll No: ";
  • 46. Problem Solving and Computer Programming 46 cin >> students[i].roll_no; cout << "Name: "; cin>>students[i].name; cout << "Branch: "; cin>>students[i].branch; cout << "Marks: "; cin >> students[i].marks; cout << endl; } return 0; } Nesting of structures A member of a structure may itself be a structure. Such nesting enables building of very powerful data structures. For example, here, the student structure can be enhanced to accommodate the date of birth of a student. #include <iostream> using namespace std; struct date { int day; int month; int year; } struct student { int roll_no; char name[25]; struct date birthday; char branch[15]; int marks;
  • 47. Problem Solving and Computer Programming 47 }; int main() { // Creating a variable of type student and initializing i student s1 = {1, "Vivek", "Mechanical", 100}; // Accessing and printing the 'name' member of the struct cout << s1.name << endl; return 0; }
  • 48. Problem Solving and Computer Programming 48 Structures and Functions Structure variables or an array of structure variables may be passed to functions just like any other variables. It is also possible for functions to return structure variables through the use of the return statement. //Passing Structure to a Function Passing Structure to a Function void show(student stu) //taking structure type parameter { cout<<"Name"<<stu.name<<endl; cout<<"Roll number:"<<stu.roll_no<<endl; cout<<"Branch:"<<stu.branch<<endl; cout<<"Marks:"<<stu.marks<<endl; } //Returning Structure from Function student read() { student stu; cout<<"Name"<<endl; cin>>stu.name; cout<<"Roll number:"<<endl; cin>>stu.roll_no; cout<<"Branch:"<<endl; cin>>stu.branch; cout<<"Marks:"<<endl; cin>>stu.marks; return stu; //returning structure type variable } Unions A union is a user-defined data type that allows you to store different data types in the same memory location. Unlike structures, where each member has its own
  • 49. Problem Solving and Computer Programming 49 memory space, members of a union share the same memory location. The amount of memory required to store a structure variable is the sum of the size of all the members. On the other hand, in the case of unions, the amount of memory required is always equal to that required by its largest member. Members of the union can be accessed using either the dot . or the arrow -> operator. It is similar to accessing the structure variable. Only one member of a union can be accessed at any given time. This is because, at any instant, only one of the union variables can be active. Syntax: Object Oriented Programming and Classes Object-oriented modeling is a modern approach to problem-solving that revolves around real-world concepts. In this methodology, objects are the fundamental building blocks, created through programming constructs known as classes. These classes encapsulate both data and functions related to a specific concept into a single unit. Class
  • 50. Problem Solving and Computer Programming 50 A class is a user-defined data type which is like a blueprint, defining the structure and behavior of the objects of that class. The process of creating variables (instances) based on a class is called class instantiation, and these variables are referred to as objects. Each object is a unique instance of its class. Within a class, we find two key components: 1. Data Members: These represent the variables of an object. By default, these are private. 2. Member Functions: These define the actions or operations that can be performed on the data members. By default, these are public. private , public , and protected are access specifiers that determine the visibility and accessibility of class members (data members and member functions) within the class and from outside the class. private members are only accessible within the class. public members are accessible from anywhere. protected members are accessible within the class and its derived classes. Syntax: class ClassName { private: data_type privateMember1; data_type privateMember2; // ... public: return_type memberFunction1(data_type param1, data_ty return_type memberFunction2(data_type param1, data_ty // ... }; return_type CLassName::memberFunction1(data_type param1, data_ //function body of memberFunction1 } return_type CLassName::memberFunction2(data_type param1, data_ //function body of memberFunction2
  • 51. Problem Solving and Computer Programming 51 } //... Example: class ratio{ private: int num, den; public: void read(){ cout<<"Enter the numerator: "; cin>>num; cout<<"Enter the denominator: "; cin>>den; } void print(){ cout<<num<<"/"<<den<<endl; } double convert(){ double r = num/den; return r; } }; The difference between structures and classes is that all the members of structures are public by default whereas, the members of classes are private by default. Class follows the principle that the information about a module should be private to the module unless it is specifically declared public. Constructor A constructor is a special member function that allocates memory and initializes the object of a class. It is automatically called when an object is created to set its initial state or perform any necessary setup.
  • 52. Problem Solving and Computer Programming 52 It has the same name as the class to which it belongs. It has no return type and return statement. A constructor which takes no arguments is called a default constructor. Example of a constructor: #include <iostream> using namespace std; class ComplexNumber { private: double real; double imaginary; public: //Default constructor ComplexNumber() { real = 0; imaginary = 0; } }; Constructor overloading An interesting feature of the constructors is that a class can have multiple constructors. This is called constructor overloading. All the constructors have the same name as the corresponding class, and they differ only in terms of their signature (in terms of the number of arguments, or data types of their arguments, or both). In such a case, a constructor is invoked during the creation of an object depending on the number and type of arguments passed. Example:
  • 53. Problem Solving and Computer Programming 53 Destructor A destructor is a special (public) member function of a class that is responsible for releasing resources held by an object. The destructor has the same name as the class but is preceded by a tilde ~ . Destructors are automatically called when an object goes out of scope or is explicitly deleted using the delete operator. Destructors have no return type, and they don't take any parameters/arguments. Binary Operator Overloading Binary operator overloading allows you to define custom behaviors for operators when they are applied to objects of user-defined classes. This means you can use operators like + , - , * , / , and more with your custom data types, making your code more intuitive and readable. It provides a way to define how two objects of your class should interact when operated upon with a binary operator. Here's an example of how you can create a class for complex numbers and overload the + operator for two complex numbers: #include <iostream> using namespace std; class Complex { private: double real; double imag; public: Complex(double r, double i){
  • 54. Problem Solving and Computer Programming 54 real = r; imag = i; } // Overloading the + operator for adding two complex Complex operator+(Complex other){ Complex temp; temp.real = real + other.real; temp.imag = imag + other.imag; return temp; } // Display the complex number void display(){ cout << real << " + " << imaginary << "i" << endl } }; int main() { Complex num1(3, 4); Complex num2(1, 2); Complex sum = num1 + num2; cout << "Result of addition: "; sum.display(); return 0; } In this code: 1. We define a Complex class to represent complex numbers, with real and imaginary parts. 2. Inside the class, we overload the + operator by defining the operator+ member function. This function takes another Complex object ( other ) as a parameter and returns a new Complex object that represents the sum of the two complex numbers.
  • 55. Problem Solving and Computer Programming 55 3. The display member function is used to display the complex number. 4. In the main function, we create two Complex objects, num1 and num2 , and then add them using the + operator. 5. The result of the addition is stored in the sum object, and we display the result using the display member function. Friend Functions A friend function is a function that is not a member of a class but has access to its private and protected members. A friend function is declared within a class, but it is defined outside of the class scope. A friend function can access private and protected members of the class for which it is declared as a friend. Friend functions are declared within the class using the friend keyword. A function can be friend to any number of classes. A friend function is used to bridge classes. Friend function allows a more obvious syntax for calling a function rather than what a member function can do. It is used to increase the versatility of overloaded functions. Example: #include <iostream> using namespace std; class Car { private: int speed; public: Car(int initialSpeed) { speed = initialSpeed; }
  • 56. Problem Solving and Computer Programming 56 // Friend function declaration friend bool isCarMoving(const Car& car1); }; // Friend function definition bool isCarMoving(const Car& car1) { // Compare the speed of the car return (car1.speed > 0); } int main() { Car car1(50); // Speed of car1 is 50 // Check if the caris moving using the friend function if (isCarMoving(car1)) { cout << "The car is moving!" << endl; } else { cout << "The car is not moving." << endl; } return 0; } Friend Classes Similar to friend functions, we can also declare an entire class as a friend of another class. This allows all the member functions of the friend class to access the private and protected members of the other class. #include <iostream> using namespace std; class Boy { private: int boyNumber;
  • 57. Problem Solving and Computer Programming 57 int age; public: Boy(const int phNum, int age){ boyNumber = phNum; age = age; } // Declaration of Girl class as a friend friend class Girl; }; class Girl { public: // Function to access private members of Boy void displayBoyInfo(const Boy& boy); private: int girlNumber; }; // Definition of the function to access private members of Boy void Girl::displayBoyInfo(const Boy& boy) { cout << "Girl accessing Boy's info:" << endl; cout << "Boy's Number: " << boy.boyNumber << endl; cout << "Boy's Age: " << boy.age << endl; } int main() { Boy Pradeep(123456789, 26); Girl Nikitha; // Girl accesses and displays information from Boy Nikitha.displayBoyInfo(Pradeep);
  • 58. Problem Solving and Computer Programming 58 return 0; } In this example: The Girl class is declared as a friend of the Boy class, allowing the Girl class to access private members of the Boy class. The Boy class has private members boyNumber and age . The Girl class has a function displayBoyInfo that takes a Boy object as a parameter and can access and display the private information of the Boy class. Inheritance Inheritance is a technique of organizing information in a hierarchical form. It is like a child inheriting the features of its parents. Inheritance allows new classes to be built from older and less specialized classes instead of being rewritten from scratch. Inheritance, a prime feature of OOP, can be stated as the process of creating new classes (called derived classes), from the existing classes (called base classes). The derived class inherits the features of the base class (depending on the visibility mode and level of inheritance) and adds its own features.
  • 59. Problem Solving and Computer Programming 59 Derived class accesses features of the base class and not vice versa. Syntax: The visibility mode enclosed within the square brackets implies that it is optional. The default visibility mode is private. It specifies whether the features of the base class are publicly or privately inherited.
  • 60. Problem Solving and Computer Programming 60 Forms of inheritance (a)Single Inheritance: Derivation of a class from only one base class. (b)Multiple Inheritance: Derivation of a class from several (two or more) base classes. (c)Hierarchical Inheritance: Derivation of several classes from a single base class, i.e., the traits of one class may be inherited by more than one class. (d)Multilevel Inheritance: Derivation of a class from another derived class. (e)Hybrid Inheritance: Derivation of a class involving more than one form of inheritance.
  • 61. Problem Solving and Computer Programming 61 (f)Multipath Inheritance: Derivation of a class from other derived classes, which are derived from the same base class. Constructors of the base class and the derived class are automatically invoked when the derived class is instantiated. The constructors of the base class are invoked first and then the constructors of the derived class. Abstract Classes: An abstract class is one that has no instances and is not designed to create objects. An abstract class is only designed to be inherited. Example codes: multipath_inheritance.cpp multiple_inheritance.cpp hierarchical_inheritance.cpp
  • 62. Problem Solving and Computer Programming 62 multilevel_inheritance.cpp hybrid_inheritance.cpp File Management File management involves reading from and writing to files on a computer's file system. We can use the fstream library to handle file operations in C++. Opening Files: To open a file for reading or writing, you can use the open method. You specify the file's name and the mode (e.g., ios::in for input or ios::out for output) in the open call. If the file doesn't exist, it will be created when opened for writing. Closing Files: It's important to close the files once you are done with them using the close method. This ensures that all data is written to the file, and the file resources are released. #include <iostream> #include <fstream> using namespace std; fstream fin, fout; int main(){ fin.open("input.txt", ios::in); fout.open("output.txt", ios::out); fin.close(); fout.close(); }
  • 63. Problem Solving and Computer Programming 63 Reading from Files : To read from a file, use the >> operator along with the fstream object. You can read various data types from the file, including integers, strings, and more. Writing to Files: To write to a file, use the << operator along with the fstream object. You can write data of various types, similar to how you read data. Example : int value = 1; fin >> value; // Reads an integer from the file int a = 3; fout << text; // Writes the string to the file File modes ios::in : Input mode, used for reading from a file. ios::out : Output mode, used for writing to a file. ios::ate : Open the file and seek to the end. ios:app : Append mode, it always appends the data (writes data at the end of the file). ios::trunc : Truncates the file if it already exists. ios::nocreate : Open fails if the file does not exist. ios::binary : Opens the file as a binary file (rather than text). ios::noreplace : Open fails if the file already exists. Seek calls Seek calls refer to functions or methods that manipulate the position of the file pointer within a file. The file pointer is an indicator that points to the current position in a file, and seek operations allow you to move this pointer to different locations within the file. This is particularly useful when reading from or writing to files. seekg : Used with input file streams to move the input file pointer. seekp : Used with output file streams to move the output file pointer.
  • 64. Problem Solving and Computer Programming 64 Example: inputFile.seekg(10, ios::beg); // Move 10 bytes from the begi Strings Strings are used in programming languages for storing and manipulating text, such as words, names, and sentences. A string is represented as an array of characters and the end of the string is marked by the NULL (‘0’) character. String constants are enclosed in double quotes. For instance, “Hello World” is a string. An array of characters representing a string is defined as follows: char array-name[size]; Menu Driven C++ Code for String Operations without using STL of C++: #include <iostream> using namespace std; class mystring { private: char str[100]; // Assuming a character array of size 1 public: mystring() { str[0] = '0'; // Initialize the character array } // Function to get mystring length
  • 65. Problem Solving and Computer Programming 65 int length() const { int len = 0; while (str[len] != '0') { ++len; } return len; } // Function to concatenate mystrings mystring concatenate(const mystring& other) const { mystring result; int len = this->length(); for (int i = 0; i < len; ++i) { result.str[i] = this->str[i]; } int j = 0; while (other.str[j] != '0') { result.str[len + j] = other.str[j]; ++j; } result.str[len + j] = '0'; // Null-terminate the result return result; } // Function to compare mystrings int compare(const mystring& other) const { int i = 0; while (this->str[i] != '0' && other.str[i] != '0' && thi { ++i; } return this->str[i] - other.str[i];
  • 66. Problem Solving and Computer Programming 66 } // Function to reverse the mystring mystring reverse() const { mystring result; int len = this->length(); for (int i = 0; i < len; ++i) { result.str[i] = this->str[len - i - 1]; } result.str[len] = '0'; // Null-terminate the result return result; } // Operator overloading for concatenation using + mystring operator+(const mystring& other) const { return this->concatenate(other); } // Function to enter the mystring void enter() { cout << "Enter the mystring: "; cin.ignore(); // Clear the input buffer cin.getline(str, sizeof(str)); } // Function to display the mystring void display() const { cout << "mystring: " << str << endl; } }; int main() {
  • 67. Problem Solving and Computer Programming 67 mystring str1, str2, result; int choice; do { cout<< "nmystring Operations Menu:n" << "1. Enter mystring 1n" << "2. Enter mystring 2n" << "3. mystring Lengthn" << "4. Concatenate mystringsn" << "5. Compare mystringsn" << "6. Reverse mystringn" << "7. Exitn" << "Enter your choice: "; cin >> choice; switch (choice) { case 1: str1.enter(); break; case 2: str2.enter(); break; case 3: cout << "mystring 1 Length: " << str1.length() << cout << "mystring 2 Length: " << str2.length() << break; case 4: result = str1 + str2; cout << "Concatenated mystring: "; result.display(); break; case 5: if (str1.compare(str2) == 0) { cout << "mystrings are equal.n"; } else
  • 68. Problem Solving and Computer Programming 68 { cout << "mystrings are not equal.n"; } break; case 6: cout << "Reversed mystring 1: "; str1.reverse().display(); cout << "Reversed mystring 2: "; str2.reverse().display(); break; case 7: cout << "Exiting program.n"; break; default: cout << "Invalid choice. Please try again.n"; } } while (choice != 7); return 0; }