C++ 123
C++ 123
OOP POP
1 Object oriented programming Procedural oriented programming
2 Follows bottom-up approach Follows top to down approach
3 Emphasis on Objects Emphasis on Functions
4 Programs are divided into Programs are divided into objects
objects functions
5 It deals with data It deals with algorithm
6 It has access specifiers like Most functions use global data
public, private, protected.
7 It is possible to hide data by using There is no data hiding mechanism so it
encapsulation so provides more is less secure
security
8 Modifications are easier and Modifications are difficult as they can
objects are independent affect the entire program
9 Inheritance property is used Inheritance property is not allowed
10 Concept of virtual function No virtual function
11 Overloading is possible in the Overloading is not possible
form of function overloading
and operator overloading
12 C++, Python, Java, .NET C, Pascal, Fortran
INHERITANCE:
Mechanism to reuse an existing class to build a new class
The new class inherits all the behavior of the original class
The class whose properties are inherited by another class is called as super class or
parent class
The class that inherits properties from parent class is call as sub class or child class
Powerful feature in OOP.
class <derived_class_name> : <access-specifier> <base_class_name>
//body
POLYMORPHISM
An OOP concept that refers to the ability of a variable, function or object to take on
multiple forms.
Ability to redefine methods for derived classes.
Types:
a. Compile time polymorphism Ex. Method overloading.
b. Run time polymorphism Ex. Method overriding.
Helps programmers to reuse the code once written, tested & implemented.
ABSTRACTION
Abstraction is the process of hiding internal data and implementation from the end
user
Key feature in OOP
Types:
a. Data abstraction
b. Process abstraction
ADVANTAGES:
If any class member (data members/member functions) is declared under public then –
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
protected // protected access specifier
int z; // Protected attribute
};
EXAMPLES:
1]PUBLIC:
class base
{
private:
int x;
protected:
int y;
public:
int z;
public:
void showdata()
{
cout << "x is not accessible"<< endl;
cout << "value of y is " << y << endl;
cout << "value of z is " << z << endl;
}
};
int main()
{
derive a; //object of derived class
a.showdata();
return 0;
}
Output
Enter your age: 20
Age = 20
2] PRIVATE:
#include <iostream>
using namespace std;
// define a class
class Example {
// private elements
private:
int age;
// public elements
public:
void displayAge(int a) {
age = a;
cout << "Age = " << age << endl;
}
};
int main() {
int ageInput;
// declare an object
Example obj1;
cout << "Enter your age: ";
cin >> ageInput;
// call function and pass ageInput as argument
obj1.displayAge(ageInput);
return 0;
}
Output
Enter your age: 20
Age = 20
3] PROTECTED
#include <iostream>
using namespace std;
// declare parent class
class Example {
// protected elements
protected:
int age;
};
// declare child class
class ExampleChild : public Example {
public:
void displayAge(int a) {
age = a;
cout << "Age = " << age << endl;
}
};
int main() {
int ageInput;
// declare object of child class
ExampleChild child;
cout << "Enter your age: ";
cin >> ageInput;
// call child class function
// pass ageInput as argument
child.displayAge(ageInput);
return 0;
}
Output
Enter your age: 20
Age = 20
3. What is data type? Explain basic and user defined data types in C+
+?
A data type specifies the type of data that a variable can store such as integer, floating,
character etc.
1. Integer:
o Represents whole numbers without the fractional or decimal part.
o Ex. Int x = 5;
2. Character
o Represents individual character from a character set like ASCII or Unicode.
o Ex. Char x = ‘A’;
3. Boolean
o Represents binary values used for true (1) or false (0) for conditions.
o Bool keyword is used for Boolean data type.
o Ex. Bool isTrue = true;
4. Floating Point
o Represents numbers with a fractional part.
o Ex. Float x = 3.14567;
5. Double Floating Point
o Represents numbers with higher range and precision than float.
o Ex. Double x = 3.147875465;
6. Valueless or Void
o Indicates that a function does not return any value.
o Ex. void function () { // code }
7. Wide Character
o Wide char is similar to char data type, except that wide char takes up twice the space
and can take on much larger values as a result.
o Ex. wchar_t X = L 'A';
1. Class
o Class is a user-defined data type that represents a blueprint for creating objects
o It encapsulates data (attributes) and function (methods) that operate on that
data.
o Class class-name () {};
2. Structure
o User-defined data type that stores different data type in separate memory
locations.
o struct Point {
int x;
char y;
};
3. Union
o User-defined data type that stores different data types in the same memory
location.
o union GFG {
int x;
char y;
};
4. Enum (Enumeration)
o Consists of a set of named integer constants.
5. Typedef
o Allows you to create aliases for existing data types.
2. Identifiers
o In C++, an identifier is a name given to a variable, function, or another object in the
code.
3. Constants
o In C++, a constant is a value that cannot be changed during the execution of the
program.
4. String:
o In C++, a string is a sequence of characters that represents text.
5. Special symbols:
o Special symbols are the characters having specific meaning within the syntax.
o Ex. semicolon (;)
6. Operators:
o In C++, operators are special symbols that are used to perform operations on one or
more operands.
o Ex. Increment operator (++)
5. Write a note on
1. Array
An array is a collection of items of same data type stored at continuous memory
locations.
Individual array elements are accessed by their index.
Index numbering starts from 0.
int x [6];
2. Type Conversion
Conversion of one data type to another data type
There are 2 types
a. Implicit conversion
i. Automatically done by the compiler.
b. Explicit conversion (type casting)
ii. Conversion is done manually.
3. Operators [ARLBA]
In C++, operators are special symbols that are used to perform operations on one or
more operands.
1) Arithmetic operator
Used to perform arithmetic operations on variables and data.
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after division)
2) Logical operator
Used to check whether an expression is true or false.
If it is true, it returns 1 and returns 0 for false.
Logical AND.
&& expression1 && expression2
True only if all the operands are true.
Logical OR.
|| expression1 || expression2
True if at least one of the operands is true.
Logical NOT.
! ! expression
True only if the operand is false.
3) Relational operator
Used to check relation between two operands
== Is Equal To 3 == 5 gives us false
!= Not Equal To 3! = 5 gives us true
> Greater Than 3 > 5 gives us false
< Less Than 3 < 5 gives us true
>= Greater Than or Equal To 3 >= 5 give us false
<= Less Than or Equal To 3 <= 5 gives us true
4) Bitwise operator
Used to perform operations on individual bits
& Binary AND
| Binary OR
^ Binary XOR
~ Binary One's Complement
<< Binary Shift Left
>> Binary Shift Right
5) Assignment operator
Used to assign values to variables
Symbol: example: equivalent to
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
4. Identifiers
5. Variable
6. Constants
In C++, a constant is a value that cannot be changed during the execution of the
program.
const int PI = 3.14;
# include <iostream>
using namespace std;
int main(){
int size = 10;
int num[size];
// input
cout << "enter 10 numbers: "<< endl;
for(int i = 0; i < size; ++i){
cout << "eneter number " << (i + 1) << ":" << endl;
cin >> num[i];
}
// display
for(int i = 0; i < size; ++i){
cout << num[i] << " ";
}
cout << endl;
return 0;
}
Theory Assignment II
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;
return 0;
}
return result;
};
Example:
#include <iostream>
using namespace std;
// function declaration
int max(int num1,int mun2);
int main(){
//calling of the function
int a=5;
int b=6;
int result;
result=max(a,b);
cout<<"max no. is:"<<result<<endl;
return 0;
}
//fun definition
int max(int num1, int num2) {
// local variable declaration
int result;
return result;
};
3 Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location
Call by value
In call by value method of parameter passing, the values of actual parameters are copied to the
function’s formal parameters.
#include <iostream>
using namespace std;
// function declaration
void swapx(int x,int y);
int main(){
//calling of the function
int a=5;
int b=6;
swapx(a,b);
cout<<"\n"<<"int_main"<<"\n";
cout<<"a="<< a << "b="<< b;
return 0;
}
//fun definition
void swapx(int x, int y) {
// local variable declaration
int t;
t=x;
x=y;
y=t;
cout<< "def"<<"\n";
cout<<"x="<< x << "y="<< y;
Call by reference:
In call by reference method of parameter passing, the address of the actual parameters is passed to
the function as the formal parameters.
#include <iostream>
using namespace std;
// function declaration
void swapx(int&,int&);
int main(){
//calling of the function
int a=5, b=6;
swapx(a,b);
cout<<"\n"<<"int_main"<<"\n";
cout<<"a="<< a << "b="<< b;
return 0;
}
//fun definition
void swapx(int& x, int& y) {
// local variable declaration
int t;
t=x;
x=y;
y=t;
cout<< "def"<<"\n";
cout<<"x="<< x << "y="<< y;
class base
{
private:
int x;
protected:
int y;
public:
int z;
public:
void showdata()
{
cout << "x is not accessible"<< endl;
cout << "value of y is " << y << endl;
cout << "value of z is " << z << endl;
}
};
int main()
{
derive a; //object of derived class
a.showdata();
return 0;
}
};
A. Default Constructors:
o which doesn’t take any arguments & has no parameters.
o also called a zero-argument constructor.
B. Parameterized Constructors:
C. Copy constructor
o Member function that initializes an object using another object of the same class.
1. Default Constructors:
#include <iostream>
using namespace std;
class construct{
public:
int x, y;
construct() {
x=1;
y=2;
};
};
int main() {
construct c;
cout<<c.x<<c.y;
return 0;
}
output
12
2. Parameterized Constructors:
#include <iostream>
using namespace std;
class pc{
private:
int x, y;
public:
pc(int x1, int y1) {
x=x1;
y=y1;
};
int getx(){return x;}
int gety(){return y;}
};
int main() {
pc p1(1,2);
cout<<p1.getx()<<endl;
cout<<p1.gety();
return 0;
}
output:
1
2
3. Copy Constructor:
#include <iostream>
using namespace std;
class pc{
private:
int x;
public:
pc(int x1) {
x=x1;
};
int getx(){return x;}
};
int main() {
pc p1;
cout<<p1.getx()<<endl;
pc p2(p1);
cout<<"copy constructor"<<endl;
cout<<p2.getx();
return 0;
}
o/p:
1
copy constructor
1
class student{
int x, y, z;
public:
student() {
x=1;
y=2;
z=3;
};
void display() {
cout<<x<<y<<z;
};
};
int main() {
student a;
a.display();
return 0;
}
1. Write a note on
1. Function Overloading
o Process of having two or more function with the same name but with different
parameters.
o Same name is used for two or more functions
o void add(int a, int b);
o void add(double a, double b);
#include <iostream>
using namespace std;
void add(int a, int b)
{
cout << "sum_int = " << (a + b);
}
// Driver code
int main()
{
add(10, 2);
add(5.3, 6.2);
return 0;
}
sum_int = 12
sum_double = 11.5
2. Default Arguments
// Driver Code
int main()
{
// Statement 1
cout << sum(10, 15) << endl;
// Statement 2
cout << sum(10, 15, 25) << endl;
// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
25
50
80
3. Destructor
o Like constructor, destructor is a member function whose name is same as the class
name but is preceded by a tilde (~)
o Special member function that is used to destroy objects that have been created by a
destructor.
o Destructor never takes any arguments, nor does it return any value.
o Ex. ~Name () {}
6. Array of Objects
o Collection of objects of the same class type that are stored in continuous memory
locations.
class className {
//variables and functions
};
className objectName[number of obj];
Theory Assignment 3
1. What is Operator Overloading? Explain unary operator
overloading with example.
o Operator overloading is a compile-time polymorphism, in which the operator is
overloaded to provide a special meaning to the user-defined data type.
o Used to perform operations on user defined data types.
o Return-type class-name :: operator symbol(arguments) {//body}
o Operators that cannot be overloaded are
i. Scope operator (::)
ii. Sizeof
iii. Member selector (.)
iv. Member pointer selector (*)
v. Ternary operator (:?)
#include <iostream>
using namespace std;
class NUM
{
private:
int num;
public:
void getNum(int x) { num = x; }
int main(){
NUM num;
num.getNum(6);
++num;
cout << endl << "After increment: ";
num.print();
return 0;
}
Output:
Before increment: 6
After increment: 7
class NUM {
private:
int n;
public:
void getNum (int x) {n = x;}
void print () {cout << n;}
NUM operator + (NUM & obj) {
NUM x;
x.n = n + obj.n;
return x;
}
};
int main () {
NUM a, b, sum;
a.getNum(3);
b.getNum(2);
sum = a + b;
sum.print();
return 0;
}
In C++, inheritance is a process in which one object acquires all the properties and
behaviours of its parent object automatically.
In such way, you can reuse, extend or modify the attributes and behaviours which are defined
in other class.
o Parent class: The class from which the child class inherits its properties is called the
parent class or base class.
o Child class: The class that inherits the characteristics of another class is known as the
child class or derived class
1) Single inheritance
2) Multiple inheritance
o Multiple inheritance is a type of inheritance in which a class derives from more than
one class.
3) Hierarchical inheritance
o Hierarchical inheritance more that one class inherits from a single base class.
o This gives it a structure of a hierarchy.
4) Multilevel inheritance
5) Hybrid inheritance
class base{
public:
void display(){
cout << "this is inside the base class" << endl;
}
};
class derived : public base{
public:
void show(){
cout << "this is inside derived class";
}
};
int main() {
base a;
a.display();
derived b;
b.display();
b.show();
return 0;
}
Output:
this is inside the base class
this is inside the base class
this is inside derived class
B. DERIVED CLASS:
a. The class that inherits the properties of another class. (child class)
b. class derived-class: access-specifier base-class {
};
2) Friend Function
o A friend function in is the one who can access private, protected and public members
of the class.
o A friend function is declared using friend keyword inside the body of a class.
o Class class-name {
friend return-type function-name(arguments); };
o Friend keyword is only placed in the declaration and not in the function definition.
o Cannot be called using objects of that class.
3) Virtual Function
4) Hybrid Inheritance
o Has at least one pure virtual function (function that has no definition)
o The classes inheriting the abstract class must provide a definition for the pure virtual
function, otherwise the subclass would become an abstract class itself.
o We cannot create object of the abstract classes.
class Shape {
public:
#include <iostream>
using namespace std;
class Student {
public:
int rollno;
char name[50];
float marks;
void display() {
cout<<"Roll Number: "<< rollno <<endl;
cout<<"Name: "<< name <<endl;
cout<<"Marks: "<< marks <<endl;
}
};
int main() {
Student stu1 = {1, "Harry", 91.5};
stu1.display();
return 0;
}
Assignment 4
Theory Assignment 4
The elements in the array can be in random the elements in the array need to be in the
order sorted order.
CMOTPDT
//swap
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
//print
void print(int a[], int n){
for(int i = 0; i < n; i++){
cout << a[i] << " ";
}
}
//selection sort
void selectionSort(int a[], int n){
for(int i = 0; i < n - 1; i++){
int minIdx = i;
for(int j = i + 1; j < n; j++){
if(a[j] < a[minIdx]){
minIdx = j;
}
}
swap(a[minIdx], a[i]);
}
}
int main(){
int n = 5;
int a[n] = {1, 5, 6, 0, 7};
print(a, n);
selectionSort(a, n);
cout << endl << "After selection sort: ";
print(a, n);
return 0;
}
OUTPUT:
15607
After selection sort: 0 1 5 6 7
// print
void print (int a[], int n){
for(int i = 0; i < n; i++){
cout << a[i] << " ";
}
}
// insertion sort
void insertionSort(int a[], int n){
for(int i = 1; i < n; i++){
int current = a[i];
int j = i - 1;
while(current < a[j] && j >= 0){
a[j + 1] = a[j];
--j;
}
a[j + 1] = current;
}
}
int main(){
int n = 5;
int a[] = {5, 3, 8, 6, 1};
print(a, n);
cout << endl << "After insertion sort: ";
insertionSort(a, n);
print(a, n);
return 0;
}
Output:
53861
After insertion sort: 1 3 5 6 8
General Algorithm
#include <iostream>
using namespace std;
// swap
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
// print
void print(int a[], int n){
for(int i = 0; i < n; i++){
cout << a[i] << " ";
}
}
// bubble sort
void bubbleSort(int a[], int n){
for(int i = 0; i < n; i++){
for(int j = 0; j < n - 1; j++){
if(a[j] > a[j + 1]){
swap(a[j], a[j + 1]);
}
}
}
}
int main(){
int n = 5;
int a[] = {5, 3, 8, 4, 1};
print(a, n);
bubbleSort(a, n);
cout << endl << "After bubble sort: ";
print(a, n);
return 0;
}
53841
After bubble sort: 1 3 4 5 8
size of the structure is not fixed and can be modified during the operations performed on
it.
Lists, Trees (with variable size), Hash tables
nn
ASSIGNMENT 5
Q1. What is Linked List? Explain its types in detail.
o Stack is a linear data structure that follows LIFO (Last in First out) principle.
o It is a container in which insertion and deletion can be done from one end known as
top.
o Stack is an abstract data type with pre-defined capacity; hence it can store limited
elements.
OPERATIONS:
o Push (): insert an element in a stack. If the stack is full then the overflow condition
occurs.
o Pop (): delete an element from the stack. If the stack is empty, this state is known as
an underflow state.
o Peek (): It returns the element at the given position.
o isEmpty (): It determines whether the stack is empty or not.
o isFull (): It determines whether the stack is full or not.
o Count (): It returns the total number of elements available in a stack.
o Change (): It changes the element at the given position.
o Display (): It prints all the elements available in the stack.
TYPES:
OPERATIONS: