0% found this document useful (0 votes)
3 views134 pages

C++ Programming

C++ is a versatile programming language that supports object-oriented, procedural, and generic programming, and is known for its features such as strong typing, memory management, and a rich library. It includes core concepts of object-oriented programming like inheritance, polymorphism, encapsulation, and abstraction, and provides standard libraries for various functionalities. The tutorial covers basic syntax, control statements, loops, and data structures like arrays, along with examples and explanations of operators and input/output operations.

Uploaded by

Eduskill Academy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views134 pages

C++ Programming

C++ is a versatile programming language that supports object-oriented, procedural, and generic programming, and is known for its features such as strong typing, memory management, and a rich library. It includes core concepts of object-oriented programming like inheritance, polymorphism, encapsulation, and abstraction, and provides standard libraries for various functionalities. The tutorial covers basic syntax, control statements, loops, and data structures like arrays, along with examples and explanations of operators and input/output operations.

Uploaded by

Eduskill Academy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 134

C++ Tutorial

What is C++?
 C++ is a general purpose, case-sensitive, free-form programming language that supports object-
oriented, procedural and generic programming.
 C++ is an object-oriented programming language. It is an extension to C programming.
 C++ is a middle-level language, as it encapsulates both high and low level language features.

Object-Oriented Programming (OOPs)


 C++ supports the object-oriented programming, the four major pillar of object-oriented
programming (OOPs) used in C++ are:

1) Inheritance
2) Polymorphism
3) Encapsulation
4) Abstraction

C++ Standard Libraries


 Standard C++ programming is divided into three important parts:

1) The core library includes the data types, variables and literals, etc.
2) The standard library includes the set of functions manipulating strings, files, etc.
3) The Standard Template Library (STL) includes the set of methods manipulating a data
structure.

Usage of C++
 By the help of C++ programming language, we can develop different types of secured and
robust applications:

1) Window application
2) Client-Server application
3) Device drivers
4) Embedded firmware etc
C++ Features
 C++ is a widely used programming language.
 It provides a lot of features that are given below.

1) Simple
2) Abstract Data types
3) Machine Independent or Portable
4) Mid-level programming language
5) Structured programming language
6) Rich Library
7) Memory Management
8) Quicker Compilation
9) Pointers
10) Recursion
11) Extensible
12) Object-Oriented
13) Compiler based
14) Reusability
15) National Standards
16) Errors are easily detected
17) Power and Flexibility
18) Strongly typed language
19) Redefine Existing Operators
20) Modelling Real-World Problems
21) Clarity
C++ Program
 #include<iostream.h> includes the standard input output library functions. It
provides cin and cout methods for reading from input and writing to output respectively.
 void main() The main() function is the entry point of every program in C++ language. The void
keyword specifies that it returns no value.
 cout << "Hello World" <<endl;is used to print the data on the console.

C++ Basic Input/Output


 C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow of data.
It makes the performance fast.
 If bytes flow from main memory to device like printer, display screen, or a network connection,
etc, this is called as output operation.
 If bytes flow from device like printer, display screen, or a network connection, etc to main
memory, this is called as input operation.

I/O Library Header Files


 Let us see the common header files used in C++ programming are:

Header Function and Description


File

<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard outputstream,
standard input stream and standard error stream, respectively.

<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision and
setw.

<fstream> It is used to declare services for user-controlled file processing.

Standard output stream (cout)


 The cout is a predefined object of ostream class.
 It is connected with the standard output device, which is usually a display screen.
 The cout is used in conjunction with stream insertion operator (<<) to display the output on a
console
Standard input stream (cin)

 The cin is a predefined object of istream class.


 It is connected with the standard input device, which is usually a keyboard.
 The cin is used in conjunction with stream extraction operator (>>) to read the input from a
console.
Standard end line (endl)
 The endl is a predefined object of ostream class.
 It is used to insert a new line characters and flushes the stream.

C++ Variable
 A variable is a name of memory location. It is used to store data. Its value can be changed and
it can be reused many times.
 It is a way to represent memory location through symbol so that it can be easily identified.
 The example of declaring variable is given below:

1) int x;
2) float y;
3) char z;

 Here, x, y, z are variables and int, float, char are data types.

Rules for defining variables


 A variable can have alphabets, digits and underscore.
 A variable name can start with alphabet and underscore only. It can't start with digit.
 No white space is allowed within variable name.
 A variable name must not be any reserved word or keyword e.g. char, float etc.
 Valid variable names:

1) int a;
2) int _ab;
3) int a30;

 Invalid variable names:

1) int 4;
2) int x y;
3) int double;

Operators in C++
 An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise etc.
 There are following types of operators to perform different types of operations in C language.

1) Arithmetic Operators
2) Relational Operators
3) Logical Operators
4) Assignment Operator
5) Unary operator
6) Ternary or Conditional Operator

Arithmetic Operators
 These operators used to perform common mathematical operations

Relational Operators
 These operators are used to compare two values.

Assignment Operator
 These operators are used to assign values to variables.
Logical Operators
 These operators are used to determine the logic between variables or values.

C++ Control Statements


 In C++ programming, if statement is used to test the condition. There are various types of if
statements in C++.

1) if statement
2) if-else statement
3) nested if statement
4) if-else-if ladder

C++ IF Statement
 The C++ if statement tests the condition. It is executed if condition is true.

1) if(condition){
2) //code to be executed
3) }
C++ IF-else Statement
 The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwise else block is executed.

1) if(condition){
2) //code if condition is true
3) }else{
4) //code if condition is false
5) }

C++ IF-else-if ladder Statement


 The C++ if-else-if ladder statement executes one condition from multiple statements.

1) if(condition1){
2) //code to be executed if condition1 is true
3) }else if(condition2){
4) //code to be executed if condition2 is true
5) }
6) else if(condition3){
7) //code to be executed if condition3 is true
8) }
9) ...
10) else{
11) //code to be executed if all the conditions are false
12) }
C++ nested if
 if inside if.
Syntax:
1. If(condition)
2. {
3. If(condition)
4. {
5. //code to be executed
6. }
7. else
8. {
9. //code to be executed
10.}
11.}

C++ switch
 The C++ switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement in C++.
 A switch statement is a conditional statement used in C programming to check the value of a
variable and compare it with all the cases.
 If the value is matched with any case, then its corresponding statements will be executed. Each
case has some name or number known as the identifier.
 The value entered by the user will be compared with all the cases until the case is found. If the
value entered by the user is not matched with any case, then the default statement will be
executed.
 Syntax:

1) switch(expression){
2) case value1:
3) //code to be executed;
4) break;
5) case value2:
6) //code to be executed;
7) break;
8) ......
9)
10) default:
11) //code to be executed if all cases are not matched;
12) break;
13) }
C++ Ternary Operator
 Ternary Operator works as if-else statement.
 We use this operator to run code when the condition is true and another code when the
condition is false.
Syntax:
(condition) ? (expression 1//true part) : (expression 2//false part)

Program:
Program to check whether a character is a vowel or consonant.

C++ Loops

C++ for Loop


 The C++ for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop than while or do-while loops.
 The C++ for loop is same as C/C#. We can initialize variable, check condition and
increment/decrement value.
 When you know exactly how many times you want to loop through a block of code, use the for
loop instead of a while loop:
 Syntax:

1) for(initialization; condition; incr/decr)


2) {
3) //code to be executed
4) }

Example:

C++ while loop


 In C++, while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop than for loop.

1) while(condition){
2) //code to be executed
3) }

C++ do-while Loop


 The C++ do-while loop is used to iterate a part of the program several times.
 If the number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop.
 The C++ do-while loop is executed at least once because condition is checked after loop body.
 Syntax:

1) do{
2) //code to be executed
3) }while(condition);
C++ break Statement
 The C++ break is used to break loop or switch statement.
 It breaks the current flow of the program at the given condition. In case of inner loop, it breaks
only inner loop.

Syntax:

1) jump-statement;
2) break;
Program:
C++ continue Statement
 The C++ continue statement is used to continue loop.
 It continues the current flow of the program and skips the remaining code at specified
condition. In case of inner loop, it continues only inner loop.
 Syntax:
1) jump-statement;
2) continue;

C++ goto Statement


 The C++ goto statement is also known as jump statement. It is used to transfer control to the
other part of the program. It unconditionally jumps to the specified label.
 It can be used to transfer control from deeply nested loop or switch case label.
What is the purpose of flag in C?
 A “flag” variable is simply a boolean variable whose contents is “true” or “false”. You can use
either the bool type with true or false , or an integer variable with zero for “false” and non-zero
for “true”.
 Flag is used as a signal in a program. Its use is not limited to just C programming, it can be used
in just about any code, language independent.
 Its purpose is to control the program’s execution and is also used to debug the program in
some cases.

Prime Number program in C/C++


 Prime number in C: Prime number is a number that is greater than 1 and divided by 1 or itself.
 In other words, prime numbers can't be divided by other numbers than itself or 1. For example
2, 3, 5, 7, 11, 13, 17, 19, 23 .... are the prime numbers.
 Note: Zero (0) and 1 are not considered as prime numbers. Two (2) is the only one even prime
number because all the numbers can be divided by 2.
Calculate the sum of n natural numbers program in C/C++

Multiplication table program in C/C++

C++ Array
 An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Arrays are the derived data type in C++ programming language which can store the
primitive type of data such as int, char, double, float, etc.
 It also has the capability to store the collection of derived data types, such as pointers,
structure, etc.
 The array is the simplest data structure where each data element can be randomly accessed by
using its index number.
 C++ array is beneficial if you have to store similar elements.
 For example, if we want to store the marks of a student in 6 subjects, then we don't need to
define different variables for the marks in the different subject.
 Instead of that, we can define an array which can store the marks in each subject at the
contiguous memory locations.
 By using the array, we can access the elements easily. Only a few lines of code are required to
access the elements of the array.
Advantages of C Array
1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantages of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the
limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.

Properties of Array
 The array contains the following properties.
 Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
 Elements of the array are stored at contiguous memory locations where the first element is
stored at the smallest memory location.
 Elements of the array can be randomly accessed since we can calculate the address of each
element of the array with the given base address and the size of the data element.
Declaration of C Array

 To declare an array, define the variable type, specify the name of the array followed by square
brackets and specify the number of elements it should store.
 data_type array_name[array_size];
 Now, let us see the example to declare the array.

1) int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is the array size.

C Array: Declaration with Initialization


 We can initialize the c array at the time of declaration. Let's see the code.

1) int marks[5]={20,30,40,50,60};

 In such case, there is no requirement to define the size. So it may also be written as the
following code.
1) int marks[]={20,30,40,50,60};

 Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Two or multidimensional Array in C++


 The two-dimensional array can be defined as an array of arrays.
 The 2D array is organized as matrices which can be represented as the collection of rows and
columns.
 However, 2D arrays are created to implement a relational database lookalike data structure.
 It provides ease of holding the bulk of data at once which can be passed to any number of
functions wherever required.

Declaration of two or multidimensional Array in C++


 The syntax to declare the 2D array is given below.
1) data_type array_name[rows][columns];

 Consider the following example.

2) int twodimen[4][3];

 Here, 4 is the number of rows, and 3 is the number of columns.

Initialization of 2D Array in C
 In the 1D array, we don't need to specify the size of the array if the declaration and initialization
are being done simultaneously.
 However, this will not work with 2D arrays. We will have to define at least the second dimension
of the array.
 The two-dimensional array can be declared and defined in the following way.

1) int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Addition of matrix:
C++ Functions
 In C++, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}.
 A function can be called multiple times to provide reusability and modularity to the C program.
In other words, we can say that the collection of functions creates a program.
 The function is also known as procedure or subroutine in other programming languages.
 A function is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a function.
 Functions are used to perform certain actions, and they are important for reusing code: Define
the code once, and use it many times.

Advantages of functions in C
 There are the following advantages of C functions.

1) By using functions, we can avoid rewriting same logic/code again and again in a program.
2) We can call C functions any number of times in a program and from any place in a program.
3) We can track a large C program easily when it is divided into multiple functions.
4) Reusability is the main achievement of C functions.
5) However, Function calling is always a overhead in a C program.

Types of Functions
 There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C++ header files such as ceil(x), cos(x),
exp(x), etc.

2. User-defined functions: are the functions which are created by the C++ programmer, so that
he/she can use it many times. It reduces complexity of a big program and optimizes the code.
Declaration of a function
 The syntax of creating function in C++ language is given below,

1) return_type function_name(data_type parameter...)


2) {
3) //code to be executed
4) }

Create a Function
 C++ provides some pre-defined functions, such as main(), which is used to execute code. But
you can also create your own functions to perform certain actions.

 To create (often referred to as declare) a function, specify the name of the function, followed
by parentheses ():

 Syntax

1) void myFunction()

2) {
//code
}
Example Explained

1) myFunction() is the name of the function


2) void means that the function does not have a return value. You will learn more about return
values later in the next chapter
3) inside the function (the body), add code that defines what the function should do

Call a Function
 Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are called.

 To call a function, write the function's name followed by two parentheses () and a semicolon ;

 In the following example, myFunction() is used to print a text (the action), when it is called:
Call by value and call by reference in C++
 There are two ways to pass value or data to function in C language: call by value and call by
reference.
 Original value is not modified in call by value but it is modified in call by reference.

Call by value in C++


 In call by value, original value is not modified.
 In call by value, value being passed to the function is locally stored by the function parameter
in stack memory location.
 If you change the value of function parameter, it is changed for the current function only.
 It will not change the value of variable inside the caller method such as main().
Call by reference in C++
 In call by reference, original value is modified because we pass reference (address).Here,
address of the value is passed in the function, so actual and formal arguments share the same
address space.
 Hence, value changed inside the function, is reflected inside as well as outside the function.
 Note: To understand the call by reference, you must have the basic knowledge of pointers.
Difference between call by value and call by reference in C++

Recursion in C++
 Recursion is the process which comes into existence when a function calls a copy of itself to
work on a smaller problem. Any function which calls itself is called recursive function, and such
function calls are called recursive calls.
 Recursion involves several numbers of recursive calls. However, it is important to impose a
termination condition of recursion.
 Recursion code is shorter than iterative code however it is difficult to understand.
 Recursion is the technique of making a function call itself.
 This technique provides a way to break complicated problems down into simple problems
which are easier to solve.
 Recursion may be a bit difficult to understand. The best way to figure out how it works is to
experiment with it.
 Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be
defined in terms of similar subtasks.
 For Example, recursion may be applied to sorting, searching, and traversal problems.
 Example: Adding two numbers together is easy to do, but adding a range of numbers is more
complicated. In the following example, recursion is used to add a range of numbers together
by breaking it down into the simple task of adding two numbers:
Default arguments in C++
 You can also use a default parameter value, by using the equals sign (=).

 In a function, arguments are defined as the values passed when a function is called. Values
passed are the source, and the receiving function is the destination.

Definition

 A default argument is a value in the function declaration automatically assigned by the compiler
if the calling function does not pass any value to that argument.

Characteristics for defining the default arguments


 Following are the rules of declaring default arguments -

1) The values passed in the default arguments are not constant. These values can be overwritten
if the value is passed to the function. If not, the previously declared value retains.
2) During the calling of function, the values are copied from left to right.
3) All the values that will be given default value will be on the right.
C++ Strings
 Strings are used for storing text.

 A string variable contains a collection of characters surrounded by double quotes:


String Concatenation
 The + operator can be used between strings to add them together to make a new string. This is
called concatenation.

 However, you could also add a space with quotes (" " or ' '). And you can also concatenate
strings with the append() function.

 Note: C++ uses the + operator for both addition and concatenation.
 Numbers are added. Strings are concatenated.

String Length
To get the length of a string, use the length() function.
Access Strings
 You can access the characters in a string by referring to its index number inside square
brackets [].

What is OOP?
 OOP stands for Object-Oriented Programming.

 Procedural programming is about writing procedures or functions that perform operations on


the data, while object-oriented programming is about creating objects that contain both data
and functions.

 Object-oriented programming has several advantages over procedural programming:

1) OOP is faster and easier to execute


2) OOP provides a clear structure for the programs
3) OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the code easier to
maintain, modify and debug
4) OOP makes it possible to create full reusable applications with less code and shorter
development time

 Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You
should extract out the codes that are common for the application, and place them at a single
place and reuse them instead of repeating it.

 C++ supports the object-oriented programming, the four major pillar of object-oriented
programming (OOPs) used in C++ are:

1) Inheritance
2) Polymorphism
3) Encapsulation
4) Abstraction
C++ Classes/Objects
 C++ is an object-oriented programming language.

 Everything in C++ is associated with classes and objects, along with its attributes and methods.
For example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.

 Attributes and methods are basically variables and functions that belongs to the class. These
are often referred to as "class members".

 A class is a user-defined data type that we can use in our program, and it works as an object
constructor, or a "blueprint" for creating objects.

 Classes and objects are the two main aspects of object-oriented programming.

Create an Class
To create a class, use the class keyword.
Example explained
1) The class keyword is used to create a class called MyClass.
2) The public keyword is an access specifier, which specifies that members (attributes and
methods) of the class are accessible from outside the class. You will learn more about access
specifiers later.
3) Inside the class, there is an integer variable myNum and a string variable myString. When
variables are declared within a class, they are called attributes.
4) At last, end the class definition with a semicolon ;.

Create an Object
 In C++, an object is created from a class. We have already created the class named MyClass, so
now we can use this to create objects.

 To create an object of MyClass, specify the class name, followed by the object name.

 To access the class attributes (myNum and myString), use the dot syntax (.) on the object:

Example
Create an object called "myObj" and access the attributes:
 Here, student is class name, getmarks() and putmarks() are the public functions but int marks;
is private because by default anything in c++ is private, therefore int marks; is private data
member.
 Then
s is the object of the class student and accessed all methods using object name.
Another example of class and object:

Multiple Objects
 You can create multiple objects of one class.

Class Methods
 Methods are functions that belongs to the class.

 There are two ways to define functions that belongs to a class:

1) Inside class definition


2) Outside class definition

 Note: You access methods just like you access attributes; by creating an object of the class and
using the dot syntax (.)
Inside class example:

Outside class example:


 To define a function outside the class definition, you have to declare it inside the class and then
define it outside of the class. This is done by specifying the name of the class, followed the
scope resolution (::) operator, followed by the name of the function.
Arrays within a class:

 Arrays can be declared as the members of a class.


 The arrays can be declared as private, public or protected members of the class.
 To understand the concept of arrays as members of a class, consider this example. A program
to demonstrate the concept of arrays as class members
C++ Constructor
 In C++, constructor is a special method which is invoked automatically at the time of object
creation. It is used to initialize the data members of new object generally.
 The constructor in C++ has the same name as class or structure.
 There can be two types of constructors in C++.

1) Default constructor
2) Parameterized constructor
3) Copy constructor

 In C++, a constructor has the same name as that of the class and it does not have a return type.
For example,
Here, the function Wall() is a constructor of the class Wall. Notice that the constructor
1) has the same name as the class,

2) does not have a return type, and

3) is public
C++ Default Constructor
 A constructor with no parameters is known as a default constructor. In the example above,
Wall() is a default constructor.
 A constructor which has no argument is known as default constructor.
 It is invoked at the time of creating object.

 Here, when the f object is created, the fruit() constructor is called.


 Note: If we have not defined a constructor in our class, then the C++ compiler will automatically
create a default constructor with an empty code and no parameters.
C++ Parameterized Constructor
 In C++, a constructor with parameters is known as a parameterized constructor. This is the
preferred method to initialize member data.

 It is used to provide different values to distinct objects.


C++ Copy Constructor
 The copy constructor in C++ is used to copy data of one object to another.

 copy constructor is a special constructor for creating a new object as a copy of an existing
object.
C++ Destructor
 A destructor works opposite to constructor; it destructs the objects of classes. It can be defined
only once in a class. Like constructors, it is invoked automatically.
 A destructor is defined like constructor. It must have same name as class. But it is prefixed with
a tilde sign (~).
 Note: C++ destructor cannot have parameters. Moreover, modifiers can't be applied on
destructors.

Constructor overloading
 As there is a concept of function overloading, similarly constructor overloading is applied. When
we overload a constructor more than a purpose it is called constructor overloading.
 The declaration is the same as the class name but as they are constructors, there is no return
type.
 The criteria to overload a constructor is to differ the number of arguments or the type of
arguments.
C++ this Pointer
 In C++ programming, this is a keyword that refers to the current instance of the class. There can
be 3 main usage of this keyword in C++.

1) It can be used to pass current object as a parameter to another method.


2) It can be used to refer current class instance variable.
3) It can be used to declare indexers.
C++ Static Keyword
 Static is a keyword in C++ used to give special characteristics to an element.
 Static elements are allocated storage only once in a program lifetime in static storage
area. And they have a scope till the program lifetime.
 Static Keyword can be used with following,

1) Static variable in functions


2) Static Class Objects
3) Static member Variable in class
4) Static Methods in class
C++ Static Field
 A field which is declared as static is called static field. Unlike instance field which gets memory
each time whenever you create object, there is only one copy of static field created in the
memory.
 It is shared to all the objects.

C++ Inheritance
 Inheritance is one of the key features of Object-oriented programming in C++. It allows us to
create a new class (derived class) from an existing class (base class).
 The derived class inherits the features from the base class and can have additional features of
its own.
 inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically. In such way, you can reuse, extend or modify the attributes and
behaviors which are defined in other class.
 In C++, the class which inherits the members of another class is called derived class and the
class whose members are inherited is called base class. The derived class is the specialized class
for the base class.

Advantage of C++ Inheritance


 Code reusability: Now you can reuse the members of your parent class. So, there is no need to
define the member again. So less code is required in the class.
 For example,

Here, the Dog class is derived from the Animal class. Since Dog is derived from Animal, members
of Animal are accessible to Dog.
 We can also use the keywords private and protected instead of public. We will learn about the
differences between using private, public and protected later in this tutorial.
 The various ways we can derive classes are known as access modes. These access modes have
the following effect:
1) public: If a derived class is declared in public mode, then the members of the base class
are inherited by the derived class just as they are.
2) private: In this case, all the members of the base class become private members in the
derived class.
3) protected: The public members of the base class become protected members in the
derived class.
 The private members of the base class are always private in the derived class.
Types Of Inheritance
 C++ supports five types of inheritance:

1) Single inheritance
2) Multiple inheritance
3) Hierarchical inheritance
4) Multilevel inheritance
5) Hybrid inheritance

C++ Single Inheritance


 Single inheritance is defined as the inheritance in which a derived class is inherited from the
only one base class.
 Where 'A' is the base class, and 'B' is the derived class.
 User defined example of single inheritance:
C++ Multilevel Inheritance

 In multilevel inheritance, a child class inherits all the properties from all of its parent classes.
The base class is the parent class of all sub-classes in multilevel inheritance.
 Inheritance goes from parent to child. Parent classes cannot access the properties of the child
class.
C++ Multiple Inheritance
 Multiple Inheritance is the concept of inheritance in C++ by which we can inherit data members
and member functions from multiple(more than one) base/parent class(es) so that the derived
class can have properties from more than one parent class.
 Multiple inheritance is the process of deriving a new class that inherits the attributes from two
or more classes.
Ambiquity problem in Inheritance
 Ambiguity can be occurred in using the multiple inheritance when a function with the same
name occurs in more than one base class.
Ambiguity Resolution in inheritance
 This problem can be solved using the scope resolution (::) operator. By using the scope
resolution operator, we can specify the base class from which the function is called.
 We need to use the scope resolution (::) operator in the main() body of the code after we
declare the object and while calling the member function by the object.
 The above issue can be resolved by using the class resolution operator with the function. In the
above example, the derived class code can be rewritten as:

How Does Multiple Inheritance Differ from Multilevel Inheritance?


 In multiple inheritance, the derived class inherits the properties from more than one base class.
 But, in multilevel inheritance, the properties are derived to one class from another class, and
then again, the class derived for the previous level acts as the base class for another.
C++ Hybrid Inheritance
 Hybrid inheritance is a combination of more than one type of inheritance.
 Hybrid inheritance is a combination of various types of inheritance like multiple, simple, and
hierarchical inheritance.
 In hybrid inheritance, there is a combination of one or more inheritance types. For instance,
the combination of single and hierarchical inheritance.
 Therefore, hybrid inheritance is also known as multipath inheritance.
C++ Hierarchical Inheritance
 Hierarchical inheritance is defined as the process of deriving more than one class from a base
class.
 When more than one classes are inherited from a single base class, we call it Hierarchical
Inheritance. The child classes inherit the features of the parent class.
 Hierarchical Inheritance is used in C++ in cases where a hierarchical structure is needed to be
formed. It allows code reusability and improves the readability of code.
 As the features of the base class are reused as many times as needed, it improves
maintainability and reduces development costs.
Advantages of Inheritance in C++
 The advantages of inheritance are:

1) Inheritance in C++ promotes Code reusability. When a derived class inherits the base
class, then the derived class can access all the functionality, and the base class's code can
be reused in the derived class.
2) It improves code readability as you don’t have to rewrite the same code repeatedly;
hence, the code looks cleaner and readable.
3) It saves time and effort as the code is already written and is inherited; therefore, it saves
time to write code again.
4) Inheritance supports extensibility as new classes can be easily added to existing classes.

C++ Pointers
 The pointer in C++ language is a variable, it is also known as locator or indicator that points to
an address of a value.
 When we declare a variable in C++, a specific location in memory is assigned to it to store a
value in this variable. This location is called the memory address of the variable.
 Pointers in C++ are special variables that store the memory address of other variables.
 Pointers add more features and flexibility to the C++ programming language.

Dereference Operator (*)


 The Asterisk symbol (*) is called dereference operator when it is used with pointers. We can
access the values stored in a variable to which pointer points to, by using the pointer's identifier
and the dereference operator.
 In relation to pointers, the asterisk symbol (*) has two different meanings. When * is used in a
variable declaration, the value written on the right-hand side of the = sign should be an address
of a variable (present in the memory).
 The unary operator (*) when used with a pointer allows us to retrieve or assign a value stored
in the memory location pointed by the pointer. The unary operator can be read as "value
pointed by".

Reference Operator (&)


 The reference operator (&) returns the address of any variable (including pointers).

Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc.
and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.

Usage of pointer
 There are many usage of pointers in C++ language.

1) Dynamic memory allocation

 In c language, we can dynamically allocate memory using malloc() and calloc() functions where
pointer is used.

2) Arrays, Functions and Structures


 Pointers in c language are widely used in arrays, functions and structures. It reduces the code
and improves the performance.

Symbols used in pointer

Symbol Name Description

& (ampersand sign) Address operator Determine the address of a variable.

∗ (asterisk sign) Indirection operator Access the value of an address.

Declaring a pointer
 The pointer in C++ language can be declared using ∗ (asterisk symbol).

1) int ∗ a; //pointer to int


2) char ∗ c; //pointer to char

Pointer Program to swap 2 numbers without using 3rd variable


Pointer to Object in C++?
 A pointer is a variable that stores the memory address of another variable (or object) as its
value.
 A pointer aims to point to a data type which may be int, character, double, etc. Pointers to
objects aim to make a pointer that can access the object, not the variables.
 Pointer to object in C++ refers to accessing an object.
 There are two approaches by which you can access an object. One is directly and the other is
by using a pointer to an object in c++.
 A pointer to an object in C++ is used to store the address of an object. For creating a pointer to
an object in C++, we use the following syntax:

classname*pointertoobject;

 For storing the address of an object into a pointer in c++, we use the following syntax:

pointertoobject= &objectname;

 The above syntax can be used to store the address in the pointer to the object.
 After storing the address in the pointer to the object, the member function can be called using
the pointer to the object with the help of an arrow operator.
C++ Exception Handling
 Errors are the problems that occur in the program due to an illegal operation performed by the
user or by the fault of a programmer.
 Exception Handling is the process of handling errors and exceptions such that the normal
execution of the system is not halted.
 Exception handling in C++ consists of three keywords namely- try, catch, and throw.
 Exception Handling in C++ is a process to handle runtime errors. We perform exception handling
so the normal flow of the application can be maintained even after runtime errors.
 In C++, exception is an event or object which is thrown at runtime.
 All exceptions are derived from std::exception class. It is a runtime error which can be handled.
If we don't handle the exception, it prints exception message and terminates the program.

Errors in C++
 Errors are the problems that occur in the program due to an illegal operation performed by the
user or by the fault of a programmer, which halts the normal flow of the program.
 Errors are also termed bugs or faults. There are mainly two types of errors in programming. Let
us learn about both the errors:

1) Compile Time Errors


o Compile Time Errors are those errors that are caught during compilation time. Some of the most
common compile-time errors are syntax errors, library references, incorrect import of library
functions and methods, uneven bracket pair(s), etc.
2) Run-Time Errors
o Run-Time Errors are those errors that cannot be caught during compilation time. As we cannot
check these errors during compile time, we name them Exceptions. Exceptions can cause some
serious issues so we should handle them effectively.
o As we now know what exceptions are, let us now learn what is exception handling in c++.

What is Exception Handling in C++?


 Exception Handling was not a part of C Language which is said to be the predecessor of C++. Exception handling
in C++ was introduced to deal with abnormal run-time anomalies and abnormal conditions caused during run
time.
 As we know exception(s) or error(s) hinder the normal execution flow of a program so exception handing in
C++ is one of the most important topics. We can formally define exception handling as - Exception Handling is
the process of handling errors and exceptions such that the normal execution of the system is not halted.
 One of the most common run time exceptions can be 0 division error. When we try to divide a number by 0,
then the program will get executed successfully but during compile time, we will face an error causing an
application crash.
 For exception handling in C++, we use the try-catch-finally block.
 Syntax:

try {
// Block of code to try
throw exception;
}
catch () {
// Block of code to handle errors
}
Why Exception Handling?
 Exception handling in C++ checks the exception so that the normal execution of the system is
not halted.
 The main aim of Exception handling in c++ is to separate the error handling code from the
normal code. We can try to handle exceptions without exception handing in c++.
 We can always use multiple if-else conditions to handle errors.
 As normal code also contains conditional statements like if-else so, these conditions can get
mixed up with our error handling if-else conditions making the entire code less readable and
less maintainable.
 So, we use try-catch blocks to easily manage exceptional handing in c++.

Basic Keywords in Exception Handling


 As we know errors and exceptions can hinder the normal flow of program execution, so we use
exception handling in C++.
 The exception handing in C++ is mainly performed using three keywords namely - try, catch,
and throw.

1) C++ try
 The try block is used to keep the code that is expected to throw some exception. Whenever our
code leads to any exception or error, the exception or error gets caught in the catch block.
 In simple terms, we can say that the try block is used to define the block of code that needs to
be tested for errors while it is being executed.
 Example: Suppose we are dealing with databases, we should put the code that is handling the
database connection inside a try block as the database connection may raise some exceptions
or errors.

2) C++ catch
 The catch block is used to catch and handle the error(s) thrown from the try block. If there are
multiple exceptions thrown from the try block, then we can use multiple catch blocks after the
try blocks for each exception.
 In this way, we can perform different actions for the various occurring exceptions.
 In simple terms, we can say that the catch block is used to define a block of code to be executed
if an error occurs in the try block.

3) C++ throw
 The throw block is used to throw exceptions to the exception handler which further
communicates the error.
 The type of exception thrown should be same in the catch block. The throw keyword accepts
one parameter which is passed to the exception handler.
 We can throw both pre-defined as well as custom exception(s) as per the requirements.
 Whenever we want to explicitly throw an exception, we use the throw keyword.
 The throw keyword is also used to generate the custom exception.
C++ User-Defined Exceptions
 The new exception can be defined by overriding and inheriting exception class functionality.
 Note: In above example what() is a public method provided by the exception class. It is used to
return the cause of an exception.

Conclusion
1) Compile Time Errors are those errors that are caught during compilation time.
2) Run-Time Errors are those errors that cannot be caught during compilation time. As we cannot
check these errors during compile time, we name them Exceptions.
3) Exception Handling is the process of handling errors and exceptions such that the normal
execution of the system is not halted.
4) The main aim of Exception handling in C++ is to separate the error handling code from the
normal code.
5) Exception handling in C++ can throw both the basic data type as well as user-defined objects as
exceptions. For throwing an exception in C++, we use the throw keyword.
6) The try block is used to keep the code that is expected to throw some exception.
7) The catch block is used to catch and handle the error(s) thrown from the try block. If we have
multiple exceptions thrown from the try block, then we can use multiple catch blocks for
different exceptions.
8) The throw block is used to throw exceptions to the exception handler which further
communicates the error. The throw keyword accepts one parameter which is passed to the
exception handler.
C++ Polymorphism
 The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms.
It is a greek word.
 We can define polymorphism as the ability of a message to be displayed in more than one
form. In object-oriented programming, we use 3 main concepts: inheritance, encapsulation,
and polymorphism.
 Polymorphism in C++ allows us to reuse code by creating one function that’s usable for
multiple uses. We can also make operators polymorphic and use them to add not only
numbers but also combine strings. This saves time and allows for a more streamlined
program.

Real Life Example of Polymorphism


 Let's consider a real-life example of polymorphism. A lady behaves like a teacher in a classroom,
mother or daughter in a home and customer in a market. Here, a single person is behaving
differently according to the situations.

Compile time polymorphism


 The overloaded functions are invoked by matching the type and number of arguments. This
information is available at the compile time and, therefore, compiler selects the appropriate
function at the compile time.
 It is achieved by function overloading and operator overloading which is also known as static
binding or early binding. Now, let's consider the case where function name and prototype is
same.

Run time polymorphism


 Run time polymorphism is achieved when the object's method is invoked at the run time
instead of compile time. It is achieved by method overriding which is also known as dynamic
binding or late binding.
Differences b/w compile time and run time polymorphism.

Compile time polymorphism Run time polymorphism

The function to be invoked is known at the The function to be invoked is known at the run time.
compile time.

It is also known as overloading, early binding It is also known as overriding, Dynamic binding and
and static binding. late binding.

Overloading is a compile time polymorphism Overriding is a run time polymorphism where more
where more than one method is having the than one method is having the same name, number
same name but with the different number of of parameters and the type of the parameters.
parameters or the type of the parameters.

It is achieved by function overloading and It is achieved by virtual functions and pointers.


operator overloading.

It provides fast execution as it is known at the It provides slow execution as it is known at the run
compile time. time.

It is less flexible as mainly all the things execute It is more flexible as all the things execute at the run
at the compile time. time.

C++ Overloading (Function and Operator)


 If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload:

1) methods,
2) constructors, and
3) indexed properties

 It is because these members have parameters only.


Types of overloading in C++ are:
1) Function overloading
2) Operator overloading
C++ Function Overloading
 Function Overloading is defined as the process of having two or more function with the same
name, but different in parameters is known as function overloading in C++.
 In function overloading, the function is redefined by using either different types of arguments
or a different number of arguments.
 It is only through these differences compiler can differentiate between the functions.
 The advantage of Function overloading is that it increases the readability of the program
because you don't need to use different names for the same action.

Different ways to overload a Function


1) By changing number of Arguments.
2) By having different types of argument.

Example of changing number of arguments:


Example different types of arguments:

Function Overloading and Ambiguity


 When the compiler is unable to decide which function is to be invoked among the overloaded
function, this situation is known as function overloading.
 When the compiler shows the ambiguity error, the compiler does not run the program.

Causes of Function Overloading:


1) Type Conversion.
2) Function with default arguments.
3) Function with pass by reference.
C++ Operator Overloading
 Operator overloading is a compile-time polymorphism in which the operator is overloaded to
provide the special meaning to the user-defined data type. Operator overloading is used to
overload or redefines most of the operators available in C++.
 It is used to perform the operation on the user-defined data type. For example, C++ provides
the ability to add the variables of the user-defined data type that is applied to the built-in data
types.
 The advantage of Operators overloading is to perform different operations on the same
operand.

Operator that cannot be overloaded are as follows:

1) Scope operator (::)


2) Sizeof operator
3) member selector(.)
4) member pointer selector(*)
5) ternary operator(?:)

Syntax of Operator Overloading


1. return_type class_name : : operator op(argument_list)
2. {
3. // body of the function.
4. }

Where the return type is the type of value returned by the function.

class_name is the name of the class.

operator op is an operator function where op is the operator being overloaded, and the operator is
the keyword.

Rules for Operator Overloading


1) Existing operators can only be overloaded, but the new operators cannot be overloaded.
2) The overloaded operator contains atleast one operand of the user-defined data type.
3) We cannot use friend function to overload certain operators. However, the member function
can be used to overload those operators.
4) When unary operators are overloaded through a member function take no explicit arguments,
but, if they are overloaded by a friend function, takes one argument.
5) When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit arguments.
C++ Function Overriding
 If derived class defines same function as defined in its base class, it is known as function
overriding in C++. It is used to achieve runtime polymorphism.
 It enables you to provide specific implementation of the function which is already provided by
its base class.
 As we know, inheritance is a feature of OOP that allows us to create derived classes from a base
class. The derived classes inherit features of the base class.
 Suppose, the same function is defined in both the derived class and the based class. Now if we
call this function using the object of the derived class, the function of the derived class is
executed.

 This is known as function overriding in C++. The function in derived class overrides the function
in base class.
C++ virtual function
 A C++ virtual function is a member function in the base class that you redefine in a derived class.
It is declared using the virtual keyword.
 It is used to tell the compiler to perform dynamic linkage or late binding on the function.
 There is a necessity to use the single pointer to refer to all the objects of the different classes.
So, we create the pointer to the base class that refers to all the derived objects. But, when base
class pointer contains the address of the derived class object, always executes the base class
function. This issue can only be resolved by using the 'virtual' function.
 A 'virtual' is a keyword preceding the normal declaration of a function.
 When the function is made virtual, C++ determines which function is to be invoked at the
runtime based on the type of the object pointed by the base class pointer.

Late binding or Dynamic linkage


 In late binding function call is resolved during runtime. Therefore compiler determines the type
of object at runtime, and then binds the function call.

Rules of Virtual Function


1) Virtual functions must be members of some class.
2) Virtual functions cannot be static members.
3) They are accessed through object pointers.
4) They can be a friend of another class.
5) A virtual function must be defined in the base class, even though it is not used.
6) The prototypes of a virtual function of the base class and all the derived classes must be
identical. If the two functions with the same name but different prototypes, C++ will consider
them as the overloaded functions.
7) We cannot have a virtual constructor, but we can have a virtual destructor

Consider the situation when we don't use the virtual keyword.

Virtual Function Example:


Abstraction
 Let’s say you are driving a car. When you increase the speed, do you ever think about what is
happening inside the engine? Or, when you shift gears, do you know how the gearbox works?
A better question would be do you even need to know?
 The same goes for many things we do daily. When we switch on the TV, we press a button from
the remote trusting the remote to do its job, and we don’t care how it does what it does.
 This is called abstraction.
 Abstraction removes the implementation details and gives users a simple way to interact with
things.
 Another example would be when you go to Google. You are presented with a simple box to
type your query and a cute little search icon. You don’t need to worry about how Google gives
you all the results.
 Another way to frame this would be, with the help of abstraction, for a programmer hides all
the implementation details that the user does not need to see.

Abstract Class in C++


 An abstract class is a class that contains at least one pure virtual function, and these classes
cannot be instantiated.
 Abstract Classes came from the idea of abstraction.

In the above example, pow() function is used to calculate n raised to the power p. The pow() function
is present in the math.h header file in which all the implementation details of the pow() function is
hidden.
Pure Virtual Function and Abstract Classes
 Sometimes implementations of all function cannot be provided in a base class because we don’t
know the implementation. Such a class is called abstract class.
 A pure virtual function is a virtual function in C++ for which we need not to write any function
definition and only we have to declare it.
 It is declared by assigning 0 in the declaration. An abstract class is a class in C++ which have at
least one pure virtual function.

Characteristics of Abstract Classes


1) Abstract Classes must have at least one pure virtual function.
2) Abstract Classes cannot be instantiated, but pointers and references of Abstract Class types
can be created. You Abstract Classes are mainly used for Upcasting, which means its derived
classes can use its interface.
3) Classes that inherit the Abstract Class must implement all pure virtual functions. If they do
not, those classes will also be treated as abstract classes.

What is pure virtual function?


 A pure virtual function is a virtual function that has no definition within the class. A pure virtual
function is a virtual function in C++ for which we need not to write any function definition and
only we have to declare it. It is declared by assigning 0 in the declaration.

Why Can’t We Make an Abstract Class Object?


 Abstract classes in C++ cannot be instantiated because they are “abstract”. It’s like someone is
telling you to draw an animal without telling you which specific animal. You can only draw if the
person asks you to draw a cat, dog, etc., but an animal is abstract.
 The same is the case with abstract classes in C++, so we can’t create objects, but we can create
a pointer of an abstract class.
 Example of pure virtual function:
Difference between virtual function and pure virtual function

Virtual function Pure virtual function

A virtual function is a member function in A pure virtual function is a member function in a base
a base class that can be redefined in a class whose declaration is provided in a base class and
derived class. implemented in a derived class.

The classes which are containing virtual The classes which are containing pure virtual function
functions are not abstract classes. are the abstract classes.

In case of a virtual function, definition of In case of a pure virtual function, definition of a


a function is provided in the base class. function is not provided in the base class.

The base class that contains a virtual The base class that contains a pure virtual function
function can be instantiated. becomes an abstract class, and that cannot be
instantiated.

If the derived class will not redefine the If the derived class does not define the pure virtual
virtual function of the base class, then function; it will not throw any error but the derived
there will be no effect on the class becomes an abstract class.
compilation.

All the derived classes may or may not All the derived classes must define the pure virtual
redefine the virtual function. function.
C++ Files and Streams
 In C++ programming, we are using the iostream standard library, it
provides cin and cout methods for reading from input and writing to output respectively.
 Files represents storage medium for storing data or information. Streams refer to sequence of
bytes.
 In Files we store data i.e. text or binary data permanently and use these data to read or write
in the form of input output operations by transferring bytes of data. So we use the term File
Stream/File handling.
 In C++, Files are mainly dealt by using three classes fstream, ofstream, ifstream available in
fstream headerfile.
1) ofstream: Stream class to write on files.
2) ifstream: Stream class to read from files.
3) fstream: Stream class to both read and write from/to files.

 Operations in File Handling


a) open():Creating a File
b) read():Reading data
c) write():Writing new data
d) close():Closing a file
C++ getline()
 The cin is an object which is used to take input from the user but does not allow to take the
input in multiple lines. To accept the multiple lines, we use the getline() function.
 It is a pre-defined function defined in a <string.h> header file used to accept a line or a string
from the input stream until the delimiting character is encountered.

Linked List in C++


 A Linked List is a linear data structure that is a collection of objects called nodes. Each node in
a linked list consists of two parts, the first part contains the Data, and the second part contains
the address of the next node in the Linked List.
 A Linked List is a dynamic data structure, i.e., memory is allocated at run time, and memory
size can be changed at run time according to our requirements.
 A Linked List is a linear dynamic data structure in which every element is linked to another
element using pointers, sequentially. There are three types of linked lists in C++:

1) Singly Linked Lists


2) Doubly Linked Lists
3) Circular Linked Lists.

 Linked List in C++ works using pointers; each node is connected to the next node using C++
pointers.
 Linked List can be defined as collection of objects called nodes that are randomly stored in the
memory.
 A node contains two fields i.e. data stored at that particular address and the pointer which
contains the address of the next node in the memory.
 The last node of the list contains pointer to the null.
Advantages Of Linked List:
1) Dynamic data structure:
o A linked list is a dynamic arrangement so it can grow and shrink at runtime by allocating
and deallocating memory. So there is no need to give the initial size of the linked list.
2) No memory wastage:
o In the Linked list, efficient memory utilization can be achieved since the size of the linked list
increase or decrease at run time so there is no memory wastage and there is no need to
pre-allocate the memory.
3) Implementation:
o Linear data structures like stacks and queues are often easily implemented using a linked
list.
4) Insertion and Deletion Operations:
o Insertion and deletion operations are quite easier in the linked list. There is no need to shift
elements after the insertion or deletion of an element only the address present in the next
pointer needs to be updated.
Disadvantages Of Linked List:
1) Memory usage:
o More memory is required in the linked list as compared to an array. Because in a linked list,
a pointer is also required to store the address of the next element and it requires extra
memory for itself.
2) Traversal:
o In a Linked list traversal is more time-consuming as compared to an array. Direct access to
an element is not possible in a linked list as in an array by index. For example, for accessing
a node at position n, one has to traverse all the nodes before it.
3) Reverse Traversing:
o In a singly linked list reverse traversing is not possible, but in the case of a doubly-linked list,
it can be possible as it contains a pointer to the previously connected nodes with each node.
For performing this extra memory is required for the back pointer hence, there is a wastage
of memory.
4) Random Access:
o Random access is not possible in a linked list due to its dynamic memory allocation.

Singly Linked List


 A singly linked list defined as all nodes are linked together in a few sequential manners, hence, it
also knows as a linear linked list.
 therefore, clearly it has the beginning and the end. the main problem which comes with this list is
that we cannot access the predecessor of the node from the current node.

Doubly Linked List


 A doubly linked list is one in which all nodes are linked together by multiple numbers of links,
therefore these help to accessing both predecessor node and successor node from the given
node position. hence, the doubly linked list provides bi-directional traversing.
 you know, one of the most striking disadvantages is that these lists are an inability to traverse
the list in the backward direction. the most important thing is that it is necessary to traverse
the list both in the backward direction and the forward direction.
 therefore, In doubly linked list each node has two link fields. these are used for the purpose of
to point to the successor node and predecessor nodes. the given below figure shows the
structure of a node in the doubly linked list.
Circular Linked List
 The circular linked list is a linked list where all nodes are connected to form a circle. In a
circular linked list, the first node and the last node are connected to each other which forms
a circle. There is no NULL at the end.
Linked List Operations: Traverse, Insert and Delete

 There are various linked list operations that allow us to perform different actions on linked
lists. For example, the insertion operation adds a new element to the linked list.

 Here's a list of basic linked list operations that we will cover in this article.

1) Traversal
o access each element of the linked list
2) Insertion
o adds a new element to the linked list
3) Deletion
o removes the existing elements
4) Search
o find a node in the linked list
5) Sort
o sort the nodes of the linked list
Things to Remember about Linked List

 head points to the first node of the linked list


 next pointer of the last node is NULL so if the next current node is NULL, we have reached the
end of the linked list.

Basic Example
#include<iostream>

using namespace std;

class node{
public:
int data;
node* next;//pointer

node(int val){ //constuctor


data=val;
next=NULL;
}
};

//
void insertAthead(node* &head ,int val){

node* n=new node(val);

n->next=head;

head=n;

//1

void insertAtTail(node* &head, int val){

node* n=new node(val); //creating new node

if(head==NULL){

head=n;

return;

node* temp=head;
while(temp->next!=NULL){
temp=temp->next;

}
temp->next=n;
}
//

//2.

void display(node* head){

node* temp=head;

while(temp!=NULL){
cout<<temp->data<<"->";

temp=temp->next;

}
cout<<"NULL"<<endl;

}
bool search(node* &
key){
node* temp=head;

while(temp!=NULL){

if(temp->data==key){

return true;

temp=temp->next;

}
return false;

}
int main(){
node* head=NULL;
insertAtTail(head,1);
insertAtTail(head,2);
insertAtTail(head,3);
display(head);
cout<<search(head,5)<<endl;

return 0;
}

You might also like