Gaidakot Notes2
Gaidakot Notes2
system.
Data structures help us to process the data easily.
work with hierarchal data sets. For example, if the user has
searched a then he/she will search b, so it is widely used in
searching related fields.
Data structures provide us with data abstraction so that the
user need not be worried about how the data is being stored
on the system.
Data structures provided by various programming languages
come with various built-in functions (or methods) that help us
to utilize the particular database more efficiently.
If a program is working with huge data sets, then the efficient
working of such a program depends widely on the type of data
structure used. So, an adequate selection of data structure is
very important.
Data structures are also used in the database management
system (DBMS) field for creating an index, storing the data
using B and B+ trees, etc.
Data structures have many practical uses such as dynamic
memory allocation, process scheduling, file system
organization, dictionary, etc.
The Array, Linked List, Stack, and Queue are all kinds
of linear data structure types. Let's look at each in
greater detail.
1. Array
An Array is a type of framework that stores
homogeneous parts in connected memory locations. It
is precisely the same kinds of objects that are saved
sequentially inside an array. The fundamental concept
behind linear arrays in the data structure is that
multiple pieces of data similar can be stored together.
Before saving the data in an array, it is essential that
the size of an array need to be established. Every
aspect of the array can be accessed or modified, and
the data is stored in an index to identify their places of
their own.
2. Linked List
It is this type of data system where individual objects
are stored sequentially. Each object within the system
has a reference and information for the next object.
The last node on the linked list has an identifier for
null.
4. Queue
The queue is the type of system that stores data in
which components are stored in accordance with an
order of First In, First Out (FIFO). The exact sequence
is followed to carry out the required actions by the
components. The main difference between the queue
and stacks lies in eliminating an element. It is in the
area where the object that was added the most
recently is removed first in the stack. At the same
time, the case with a queue element that was initially
added is removed first.
1. Trees
A tree can be described as a nonlinear information
system comprised of a variety of nodes. The nodes of
the tree data structure are organized in order of
hierarchy.
2. Graphs
A graph can be described as a nonlinear information
system with a restricted number of vertices and
edges, and these edges are used to join the vertex
pairs. The graph is classified by certain characteristics.
When we talk about a large graph, it is composed of a
set of vertex together with every vertex that is
attached to the various vertex sets, gaining an
advantage over the two. The vertices hold the data
elements, whereas they are the tip of the link between
the vertex sets.
Linear data
structures are
data elements
that are Data elements
organized in a nonlinear
Data
linearly. Each data system
Arrangements:
element is are attached
attached to hierarchically.
the next and
previous
adjacent.
Multilevels are
A linear data
possible in
Levels: structure only
nonlinear data
has one level.
structures.
It is more
It is much complicated
Implementatio easier than than a linear
n: nonlinear data data structure
structures. but can be
implemented.
Linear Data Nonlinear Data
Basis of
Structure Structure
Nonlinear data
structures can
Data elements be traversed
in linear data over multiple
Transferring
structures can runs, but data
Data Elements:
only be elements
traversed once cannot be
traversed in
one run.
Memory is
Memory is not
used efficiently
Memory used efficiently
in nonlinear
Usage: in a linear data
data
structure.
structures.
Its examples
are queue, Its examples
Examples: linked list, include graphs
array, stack, and trees.
etc.
and Image
linear data Processing are
structures is two examples
mainly used in of applications
software for nonlinear
development. data
structures.
// Driver Code
int main()
{
// Initialise array
int arr[] = { 1, 2, 3, 4 };
// size of array
int N = sizeof(arr) / sizeof(arr[0]);
return 0;
}
Output:
1 2 3 4
Below is the program to illustrate traversal in an array:
C++
Java
Python3
C#
Javascript
// Driver Code
int main()
{
// Initialise array
int arr[] = { 1, 2, 3, 4 };
// size of array
int N = sizeof(arr)/sizeof(arr[0]);
C++
Java
Python3
C#
Javascript
#include <iostream>
#include <stack>
using namespace std;
int main() {
// Initialise stack
stack<int> St;
Array
Stack
Queue
LinkedList
// Driver Code
int main()
{
// Initialise array
int arr[] = { 1, 2, 3, 4 };
// Element to be found
int K = 3;
// size of array
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
findElement(arr, N, K);
return 0;
}
Output:
Element found!
// size of array
int N = 4;
// Driver Code
int main()
{
// Initialise stack
stack<int> St;
Auto Keyword
The idea of the auto keyword was to form the C++ compiler to
deduce the data type while compiling instead of making you
declare the data type every freaking time. Do keep in mind that
you cannot declare something without an initializer. There
must be some way for the compiler to deduce your type.
Example:
C++
// C++ program to demonstrate
// working of auto keyword
#include <bits/stdc++.h>
using namespace std;
// Driver Code
int main()
{
// Variables
auto an_int = 26;
auto a_bool = false;
auto a_float = 26.24;
auto ptr = &a_float;
// Print typeid
cout << typeid(a_bool).name() << "\
n";
cout << typeid(an_int).name() << "\
n";
return 0;
}
Output:
b
i
4. High-Level Language
C++ is a High-Level Language, unlike C which is a Mid-Level
Programming Language. It makes life easier to work in C++ as
it is a high-level language it is closely associated with the
human-comprehensible English language.
5. Popular
C++ can be the base language for many other programming
languages that supports the feature of object-oriented
programming. Bjarne Stroustrup found Simula 67, the first
object-oriented language ever, lacking simulations, and
decided to develop C++.
6. Case-sensitive
It is clear that C++ is a case-sensitive programming language.
For example, cin is used to take input from the input stream.
But if the “Cin” won’t work. Other languages like HTML and
MySQL are not case-sensitive languages.
7. Compiler Based
C++ is a compiler-based language, unlike Python. That is C++
programs used to be compiled and their executable file is used
to run them. C++ is a relatively faster language than Java and
Python.
8. Dynamic Memory Allocation
When the program executes in C++ then the variables are
allocated the dynamical heap space. Inside the functions, the
variables are allocated in the stack space. Many times, We are
not aware in advance how much memory is needed to store
particular information in a defined variable and the size of
required memory can be determined at run time.
9. Memory Management
C++ allows us to allocate the memory of a variable or
an array in run time. This is known as Dynamic
Memory Allocation.
In other programming languages such
as Java and Python, the compiler automatically
manages the memories allocated to variables. But this
is not the case in C++.
In C++, the memory must be de-allocated dynamically
allocated memory manually after it is of no use.
The allocation and deallocation of the memory can be
done using the new and delete operators respectively.
10. Multi-threading
Multithreading is a specialized form of multitasking and
multitasking is a feature that allows your system to
execute two or more programs concurrently. In general,
there are two sorts of multitasking: process-based and
thread-based.
Process-based multitasking handles the concurrent
execution of programs. Thread-based multitasking
deals with the multiprogramming of pieces of an
equivalent program.
A multithreaded program contains two or more parts
that will run concurrently. Each part of such a program
is named a thread, and every thread defines a
separate path of execution.
Its main aim is to improve and Its main aim is to improve and
increase quality, clarity, and increase both quality and
development time of computer productivity of system analysis
program. and design.
It is a method of organizing,
managing and coding
programs that can give or It is a method in which set of
provide much easier objects can vary dynamically and
modification and can execute just by acting and
understanding. reading to each other.
# Character Sets.
C++ Character Set
The character set is a combination of English language comprising of
the Alphabets and the White spaces and some symbols from the
mathematics including the Digits and the Special symbols. C++
character set means the characters and the symbols that are
understandable and acceptable by the C++ Program. These are grouped
to create and give the commands, expressions, words, c-statements, and
some of the other tokens for the C++ Language.
It is basically the combination of alphabets or characters, special
symbols, digits, and white spaces that are similar as the learning
English is to initially learns the alphabets, then learn how to combine
these alphabets to create words, which in turn are joined to make
sentences and sentences are joined to create the paragraphs. More about
a C++ program we can say is that it is basically an order of the
characters arranged in a sequence. These characters come from the
character set and play various roles in many ways in the C++ compiler.
In addition to characters, C++ also uses a mixture of characters to
represent some special conditions as well. For example; Character
combinations like ‘\nt, ‘\b’ and ‘\t’ are used for the representation of the
newline, backspace, and the horizontal tab correspondingly.
C++ Tokens :
A token is the smallest element of a program that is
meaningful to the compiler. Tokens can be classified as
follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1.Keywords: Keywords are pre-defined or reserved words in
a programming language. Each keyword is meant to perform a
specific function in a program. Since keywords are referred
names for a compiler, they can’t be used as variable names
because by doing so, we are trying to assign a new meaning
to the keyword which is not allowed. You cannot redefine
keywords. However, you can specify the text to be substituted
for keywords before compilation by using C/C++ preprocessor
directives. C language supports 32 keywords which are given
below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
While in C++ there are 31 additional keywords other
than C Keywords they are:
asm bool catch class
const_cast delete dynamic_cast
explicit
export false friend inline
mutable namespace new
operator
private protected public
reinterpret_cast
static_cast template this throw
true try typeid
typename
using virtual wchar_t
2.Identifiers: Identifiers are used as the general terminology
for the naming of variables, functions and arrays. These are
user-defined names consisting of an arbitrarily long sequence
of letters and digits with either a letter or the underscore(_) as
a first character. Identifier names must differ in spelling and
case from any keywords. You cannot use keywords as
identifiers; they are reserved for special use. Once declared,
you can use the identifier in later program statements to refer
to the associated value. A special kind of identifier, called a
statement label, can be used in goto statements.
There are certain rules that should be followed while
naming c identifiers:
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’,
‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;
when we declare char as “string[20]”, 20 bytes of
memory space is allocated for holding the string value.
When we declare char as “string[]”, memory space will
be allocated as per the requirement during the
execution of the program.
5.Special Symbols: The following special symbols are used
in C having some special meaning and thus, cannot be used
for some other purpose.[] () {}, ; * = #
C++
// C++ Program to Demonstrate the correct
size
// of various data types on your
computer.
#include <iostream>
using namespace std;
int main()
{
cout << "Size of char : " <<
sizeof(char) << endl;
cout << "Size of int : " <<
sizeof(int) << endl;
return 0;
}
Output
C++ comes with libraries that provide us with many ways for
performing input and output. In C++ input and output are
performed in the form of a sequence of bytes or more
commonly known as streams.
Input Stream: If the direction of flow of bytes is from
the device(for example, Keyboard) to the main memory
then this process is called input.
Output Stream: If the direction of flow of bytes is
opposite, i.e. from main memory to device( display
screen ) then this process is called output.
Header files available in C++ for Input/Output operations
are:
1. iostream: iostream stands for standard input-output
stream. This header file contains definitions of objects
like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators.
The methods declared in these files are used for
manipulating streams. This file contains definitions of
setw, setprecision, etc.
3. fstream: This header file mainly describes the file
stream. This header file is used to handle the data
being read from a file as input or data being written into
the file as output.
4. bits/stdc++: This header file includes every standard
library. In programming contests, using this file is a
good idea, when you want to reduce the time wasted in
doing chores; especially when your rank is time
sensitive. To know more about this header file
refer this article.
In C++ after the header files, we often use ‘using namespace
std;‘. The reason behind it is that all of the standard library
definitions are inside the namespace std. As the library
functions are not defined at global scope, so in order to use
them we use namespace std. So, that we don’t need to write
STD:: at every line (eg. STD::cout etc.). To know more
refer this article.
The two instances cout in C++ and cin in C++ of iostream
class are used very often for printing outputs and taking inputs
respectively. These two are the most basic methods of taking
input and printing output in C++. To use cin and cout in C++
one must include the header file iostream in the program.
This article mainly discusses the objects defined in the header
file iostream like the cin and cout.
Standard output stream (cout): Usually the standard
output device is the display screen. The C+
+ cout statement is the instance of the ostream class.
It is used to produce output on the standard output
device which is usually the display screen. The data
needed to be displayed on the screen is inserted in the
standard output stream (cout) using the insertion
operator(<<).
C++
#include <iostream>
int main()
{
char sample[] = "GeeksforGeeks";
return 0;
}
Output:
GeeksforGeeks - A computer science portal for
geeks
In the above program, the insertion operator(<<) inserts the
value of the string variable sample followed by the string “A
computer science portal for geeks” in the standard output
stream cout which is then displayed on the screen.
standard input stream (cin): Usually the input device
in a computer is the keyboard. C++ cin statement is the
instance of the class istream and is used to read input
from the standard input device which is usually a
keyboard.
The extraction operator(>>) is used along with the
object cin for reading inputs. The extraction operator
extracts the data from the object cin which is entered
using the keyboard.
C++
#include <iostream>
using namespace std;
int main()
{
int age;
return 0;
}
Input :
18
Output:
Enter your age:
Your age is: 18
Linking Section:
The linking section contains two parts:
Header Files:
Generally, a program includes various programming
elements like built-in functions, classes,
keywords, constants, operators, etc. that are already
defined in the standard C++ library.
In order to use such pre-defined elements in a
program, an appropriate header must be included in
the program.
Standard headers are specified in a program through
the preprocessor directive #include. In Figure, the
iostream header is used. When the compiler processes
the instruction #include<iostream>, it includes the
contents of the stream in the program. This enables the
programmer to use standard input, output, and error
facilities that are provided only through the standard
streams defined in <iostream>. These standard
streams process data as a stream of characters, that
is, data is read and displayed in a continuous flow. The
standard streams defined in <iostream> are listed
here.
#include<iostream>
Namespaces:
A namespace permits grouping of various entities like
classes, objects, functions, and various C++ tokens,
etc. under a single name.
Any user can create separate namespaces of its own
and can use them in any other program.
In the below snippets, namespace std contains
declarations for cout, cin, endl, etc. statements.
using namespace std;
Namespaces can be accessed in multiple ways:
using namespace std;
using std :: cout;
Definition Section:
It is used to declare some constants and assign them
some value.
In this section, anyone can define your
own datatype using primitive data types.
In #define is a compiler directive which tells the
compiler whenever the message is found to replace it
with “Factorial\n”.
typedef int INTEGER; this statement tells the compiler
that whenever you will encounter INTEGER replace it
by int and as you have declared INTEGER as datatype
you cannot use it as an identifier.
Global Declaration Section:
Here, the variables and the class definitions which are
going to be used in the program are declared to make
them global.
The scope of the variable declared in this section lasts
until the entire program terminates.
These variables are accessible within the user-defined
functions also.
Function Declaration Section :
It contains all the functions which our main functions
need.
Usually, this section contains the User-defined
functions.
This part of the program can be written after the main
function but for this, write the function prototype in this
section for the function which for you are going to write
code after the main function.
C++
// Function to implement the
// factorial of number num
INTEGER factorial(INTEGER num)
{
// Iterate over the loop from
// num to one
for (INTEGER i = 1; i <= num; i++) {
fact *= i;
}
Main Function:
The main function tells the compiler where to start the
execution of the program. The execution of the
program starts with the main function.
All the statements that are to be executed are written in
the main function.
The compiler executes all the instructions which are
written in the curly braces {} which encloses the body
of the main function.
Once all instructions from the main function are
executed, control comes out of the main function and
the program terminates and no further execution occur.
Below is the program to illustrate this:
C++
// Documentation Section
/* This is a C++ program to find the
factorial of a number
The basic requirement for writing
this
program is to have knowledge of loops
To find the factorial of a number
iterate over the range from number to
1
*/
// Linking Section
#include <iostream>
using namespace std;
// Definition Section
#define msg "FACTORIAL\n"
typedef int INTEGER;
// Function Section
INTEGER factorial(INTEGER num)
{
// Iterate over the loop from
// num to one
for (INTEGER i = 1; i <= num; i++) {
fact *= i;
}
// Main Function
INTEGER main()
{
// Given number Num
INTEGER Num = 5;
// Function Call
storeFactorial = factorial(Num);
cout << msg;
return 0;
}
Output
FACTORIAL
5! = 120
In C++, Control Statements are usually jumped from
one part of the C++ code to another depending on
whether a particular condition is satisfied or not. There
are three types of C++ Control Statements are given as
follows:
1. Sequence Statement
2. Selection Statement
3. Loop Statement
if-else statement:
if-else statement is used to execute a statement block.
It has the following syntax :
if(expression is true
{
action 1;
}
else
{
action 2;
}
switch statement:
It is a multiple branching statement where based on a
condition, the control is transferred to one of the many
possible points. It has the following syntax:
switch(expression)
{
case1:
{
action 1;
}
case 2:
{
action 2;
}
case 3:
{
action 3;
}
default:
{
default statement;
}
}
for statement:
for is an entry controlled loop. It is used when an action
is to be repeated for a predetermined time. It has the
following syntax:
for(initial value; test condition; increment or
decrement)
{
action 1;
}
while statement:
It is also a loop control structure but it’s an entry-
controlled loop.
It has the following syntax:
while(condition is true)
{
action 1;
}
action 2;
do-while statement:
do-while is an exit controlled loop based on a
condition, the control is transferred back to a particular
point in the program. It has the following syntax:
do
{
action;
}
while(condition is true);
action 2;
LOOPS program
#include <iostream>
using namespace std;
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
C++ Classes and Objects
Class:
A class in C++ is the building block that leads to Object-
Oriented programming. It is a user-defined data type, which
holds its own data members and member functions, which can
be accessed and used by creating an instance of that class. A
C++ class is like a blueprint for an object. For Example:
Consider the Class of Cars. There may be many cars with
different names and brand but all of them will share some
common properties like all of them will have 4 wheels, Speed
Limit, Mileage range etc. So here, Car is the class and wheels,
speed limits, mileage are their properties.
A Class is a user defined data-type which has data
members and member functions.
Data members are the data variables and member
functions are the functions used to manipulate these
variables and together these data members and
member functions defines the properties and behavior
of the objects in a Class.
In the above example of class Car, the data member
will be speed limit, mileage etc and member functions
can be apply brakes, increase speed etc
OBJECT:
An Object is an instance of a Class. When a class is defined,
no memory is allocated but when it is instantiated (i.e. an
object is created) memory is allocated.
Defining Class and Declaring Objects
A class is defined in C++ using keyword class followed by the
name of class. The body of class is defined inside the curly
brackets and terminated by a semicolon at the end.
Declaring Objects: When a class is defined, only the
specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the
class, you need to create objects. Syntax: ClassName
ObjectName;
Access Specifiers
Example
class MyClass { // The class
public: // Access specifier
// class members goes here
};
Try it Yourself »
Example
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
Inside Example
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function
defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of
MyClass
myObj.myMethod(); // Call the method
return 0;
}
Try it Yourself »
Outside Example
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function
declaration
};
int main() {
MyClass myObj; // Create an object of
MyClass
myObj.myMethod(); // Call the method
return 0;
}
Try it Yourself »
The variables which are declared in any class by using
any fundamental data types (like int, char, float etc) or
derived data type (like class, structure, pointer etc.) are
known as Data Members. And the functions which are
declared either in private section of public section are
known as Member functions.
There are two types of data members/member
functions in C++:
1. Private members
2. Public members
1) Private members
The members which are declared in private section of
the class (using private access modifier) are known as
private members. Private members can also be
accessible within the same class in which they are
declared.
2) Public members
The members which are declared in public section of
the class (using public access modifier) are known as
public members. Public members can access within the
class and outside of the class by using the object name
of the class in which they are declared.
Consider the example:
class Test
{
private:
int a;
float b;
char *name;
...;
};
Here, a, b, and name are the private data members
and count is a public data member. While, getA() is a
private member function and getB() is public member
functions.
ADVERTISEMENT
C++ program that will demonstrate, how to
declare, define and access data members an
member functions in a class?
#include <iostream>
#include <string.h>
using namespace std;
#define MAX_CHAR 30
//class definition
class person
{
//private data members
private:
char name [MAX_CHAR];
int age;
//public member functions
public:
//function to get name and age
void get(char n[], int a)
{
strcpy(name , n);
age = a;
}
//function to print name and age
void put()
{
cout<< "Name: " << name <<endl;
cout<< "Age: " <<age <<endl;
}
};
//main function
int main()
{
//creating an object of person class
person PER;
return 0;
}
Output
Name: Manju Tomar
Age: 23
the object.
It is generally used to initialize variables.
FEATURE:
Characteristics of Constructors
o The name of the constructor must be same as that of the
class
Default Constructor
A constructor that doesn’t have parameters. It is invoked
automatically and can carry default values. If we do not define
constructor it will still define an empty constructor implicitly.
class A
{
public:
int a,b;
A() //Default cosntructor
{
a=10; //random values
b=20;
}
};
int main()
{
A obj; //constructor invoked
cout<<"a= "<<obj.a<<endl;
cout<<"b= "<<obj.b<<endl;
return 0;
}
Output:
a= 10
b= 20
Class A
{
private:
int x,y;
public:
A(int a,int b) //Parameterized Constructor
{
x=a;
y=b;
}
};
int main()
{
A obj(10,20); //constructor called
cout<<"x= "<<obj.x<<endl; //accessing value by
constructor
cout<<"y= "<<obj.y<<endl;
}
Output:
x= 10
y= 20
class A{
private:
int a,b;
public:
A(int x,int y)
{
a=x;
b=y;
}
A(const A &obj1) //copy constructor
{
a=obj1.x;
b=obj1.y;
}
};
int main()
{
A obj1(10,20); //Normal constructor
cout<<obj1.a<<" "<<obj1.b<<endl;
A obj2(obj1); //copy constructor call
cout<<obj2.a<<" "<<obj2.b<<endl;
return 0;
}
Output:
What is a destructor?
Destructor is an instance member function which is invoked
automatically whenever an object is going to be destroyed.
Meaning, a destructor is the last function that is going to be
called before an object is destroyed.
Destructor is also a special member function like
constructor. Destructor destroys the class objects
created by constructor.
Destructor has the same name as their class name
preceded by a tilde (~) symbol.
It is not possible to define more than one destructor.
The destructor is only one way to destroy the object
create by constructor. Hence destructor can-not be
overloaded.
Destructor neither requires any argument nor returns
any value.
It is automatically called when object goes out of
scope.
Destructor release memory space occupied by the
objects created by constructor.
In destructor, objects are destroyed in the reverse of
an object creation.
}
Syntax for defining the destructor outside the
class
<class-name>: : ~ <class-name>()
{
C++
// Example:
#include<iostream>
using namespace std;
class Test
{
public:
Test()
{
cout<<"\n Constructor
executed";
}
~Test()
{
cout<<"\n Destructor
executed";
}
};
main()
{
Test t;
return 0;
}
Output
Constructor executed
Destructor executed
C++
// Example:
Whereas destructor is
Constructor helps to initialize used to destroy the
1. the object of a class. instances.
While it can’t be
6. Constructor can be overloaded. overloaded.