0% found this document useful (0 votes)
4 views108 pages

Unit-2 What Is An Algorithm?: Advantages

The document provides an overview of algorithms, their advantages, characteristics, and examples of simple algorithms for basic operations. It also discusses algorithm complexity, including time and space complexity, and introduces flowcharts as a visual representation of algorithms. Additionally, it covers programming concepts, types of programming languages, programming paradigms, and the importance of program design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views108 pages

Unit-2 What Is An Algorithm?: Advantages

The document provides an overview of algorithms, their advantages, characteristics, and examples of simple algorithms for basic operations. It also discusses algorithm complexity, including time and space complexity, and introduces flowcharts as a visual representation of algorithms. Additionally, it covers programming concepts, types of programming languages, programming paradigms, and the importance of program design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 108

Unit- 2

What is an Algorithm?
A finite set of steps that must be followed to solve any problem is called an algorithm. Algorithm
is generally developed before the actual coding is done.
In computer programming terms, an algorithm is a set of well-defined instructions to solve a
particular problem. It takes a set of input(s) and produces the desired output.

Advantages −

 Promotes effective communication between team members


 Enables analysis of problem at hand
 Acts as blueprint for coding
 Assists in debugging
 Becomes part of software documentation for future reference during maintenance phase

These are the characteristics of a good and correct algorithm −

 Has a set of inputs


 Steps are uniquely defined
 Has finite number of steps
 Produces desired output

Algorithm 1: Add two numbers entered by the user

Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop

Algorithm 2: Find the largest number among three numbers

Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a > b
If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

Algorithm 3: Find Roots of a Quadratic Equation ax2 + bx + c = 0

Step 1: Start
Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;
Step 3: Calculate discriminant
D ← b2-4ac
Step 4: If D ≥ 0
r1 ← (-b+√D)/2a
r2 ← (-b-√D)/2a
Display r1 and r2 as roots.
Else
Calculate real part and imaginary part
rp ← -b/2a
ip ← √(-D)/2a
Display rp+j(ip) and rp-j(ip) as roots
Step 5: Stop

Algorithm 4: Find the factorial of a number


Step 1: Start
Step 2: Declare variables n, factorial and i.
Step 3: Initialize variables
factorial ← 1
i←1
Step 4: Read value of n
Step 5: Repeat the steps until i = n
5.1: factorial ← factorial*i
5.2: i ← i+1
Step 6: Display factorial
Step 7: Stop

Algorithm Complexity
Suppose X is an algorithm and n is the size of input data, the time and space used by
the algorithm X are the two main factors, which decide the efficiency of X.
 Time Factor − Time is measured by counting the number of key operations such as
comparisons in the sorting algorithm.
 Space Factor − Space is measured by counting the maximum memory space required by
the algorithm.

The complexity of an algorithm f(n) gives the running time and/or the storage space required by
the algorithm in terms of n as the size of input data.

Space Complexity

Space complexity of an algorithm represents the amount of memory space required by the
algorithm in its life cycle. The space required by an algorithm is equal to the sum of the
following two components −
 A fixed part that is a space required to store certain data and variables, that are
independent of the size of the problem. For example, simple variables and constants used,
program size, etc.
 A variable part is a space required by variables, whose size depends on the size of the
problem. For example, dynamic memory allocation, recursion stack space, etc.

Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and S(I)
is the variable part of the algorithm, which depends on instance characteristic I. Following is a
simple example that tries to explain the concept −
Algorithm: SUM(A, B)
Step 1 - START
Step 2 - C ← A + B + 10
Step 3 - Stop

Here we have three variables A, B, and C and one constant. Hence S(P) = 1 + 3. Now, space
depends on data types of given variables and constant types and it will be multiplied accordingly.

Time Complexity

Time complexity of an algorithm represents the amount of time required by the algorithm to run
to completion. Time requirements can be defined as a numerical function T(n), where T(n) can
be measured as the number of steps, provided each step consumes constant time.

time is (n) = c ∗ n, where c is the time taken for the addition of two bits. Here, we observe that
For example, addition of two n-bit integers takes n steps. Consequently, the total computational

T(n) grows linearly as the input size increases.

Flowchart
A flowchart is a type of diagram that represents a workflow or process. A flowchart can also be
defined as a diagrammatic representation of an algorithm, a step-by-step approach to solving a
task.

Flowchart Symbols

Here is a chart for some of the common symbols used in drawing flowcharts.

Purpose
Symbol Symbol Name
Used at the beginning and end of the
Start/Stop algorithm to show start and end of the
program.

Indicates processes like mathematical


Process
operations.

Used for denoting program inputs and


Input/ Output
outputs.

Stands for decision statements in a program,


Decision
where answer is usually Yes or No.

Arrow Shows relationships between different shapes.

Connects two or more parts of a flowchart,


On-page Connector
which are on the same page.

Off-page Connects two parts of a flowchart which are


Connector spread over different pages.

Uses of Flowcharts in Computer Programming/Algorithms

The following are the uses of a flowchart:


 It is a pictorial representation of an algorithm that increases the readability of the program.
 Complex programs can be drawn in a simple way using a flowchart.
 It helps team members get an insight into the process and use this knowledge to collect
data, detect problems, develop software, etc.
 A flowchart is a basic step for designing a new process or adding extra features.
 Communication with other people becomes easy by drawing flowcharts and sharing them.
Advantages of Flowchart
 It is the most efficient way of communicating the logic of the system.
 It acts as a guide for a blueprint during the program design.
 It also helps in the debugging process.
 Using flowcharts we can easily analyze the programs.
 Flowcharts are good for documentation.

Disadvantages of Flowchart
 Flowcharts are challenging to draw for large and complex programs.
 It does not contain the proper amount of details.
 Flowcharts are very difficult to reproduce.
 Flowcharts are very difficult to modify.

Question 1. Draw a flowchart to find the greatest number among the 2 numbers.

Solution:
Algorithm:
1. Start
2. Input 2 variables from user
3. Now check the condition If a > b, goto step 4, else goto step 5.
4. Print a is greater, goto step 6
5. Print b is greater
6. Stop

FlowChart:
Question 2. Draw a flowchart to check whether the input number is odd or even
Solution:
Algorithm:
1. Start
2. Put input a
3. Now check the condition if a % 2 == 0, goto step 5. Else goto step 4
4. Now print(“number is odd”) and goto step 6
5. Print(“number is even”)
6. Stop
FlowChart:

Example
Flowchart to calculate the average of two numbers.
What is programming?

Programming is an exercise or practices that boost our logical thinking and improves a
problem-solving skill. It teaches us how to accomplish a task with the help of a computer
program or software. Therefore, in simple terms, programming is a task to implement a solution
to a problem in the form of computer language. In this section, we will discuss the
word programming, programming languages, its type, advantages, disadvantages, and their
uses.
Definition of Programming

In computer science fields, the word program characterizes what a computer actually does and
this process is known as programming.

We can also define the term programming as it is the process that models or structure the set of
instructions that instruct the machine how to perform a task and what to perform. It can be
done using a variety of programming languages such as C, C++, C#, Python, Java, etc.

Advantages of Programming
o It enhances problem-solving skills.
o Using programming, we can solve complex problems.
o It is also learning with fun.
o It can perform multiple tasks can be bundled into one module.
o It saves time and effort.

Disadvantages of Programming
o Knowledge of computer is mandatory.
o Logical thinking should be strong.

5 major types of programming languages

While you'll find dozens of ways to classify various programming languages, they generally fall
into five major categories. Keep in mind that some languages may fall under more than one type:
1. Procedural programming languages

A procedural language follows a sequence of statements or commands in order to achieve a desired


output. Each series of steps is called a procedure, and a program written in one of these languages
will have one or more procedures within it. Common examples of procedural languages include:
 C and C++
 Java
 Pascal
 BASIC
2. Functional programming languages

Rather than focusing on the execution of statements, functional languages focus on the output of
mathematical functions and evaluations. Each function–a reusable module of code–performs a
specific task and returns a result. The result will vary depending on what data you input into the
function. Some popular functional programming languages include:
 Scala
 Erlang
 Haskell
 Elixir
 F#

3. Object-oriented programming languages (OOP)

This type of language treats a program as a group of objects composed of data and program
elements, known as attributes and methods. Objects can be reused within a program or in other
programs. This makes it a popular language type for complex programs, as code is easier to reuse
and scale. Some common object-oriented languages include:
 Java
 Python
 PHP
 C++
 Ruby

4. Scripting languages

Programmers use scripting languages to automate repetitive tasks, manage dynamic web content,
or support processes in larger applications. Some common scripting languages include:
 PHP
 Ruby
 Python
 bash
 Perl
 Node.js
5. Logic programming languages

Instead of telling a computer what to do, a logic programming language expresses a series of facts
and rules to instruct the computer on how to make decisions. Some examples of logic languages
include:
 Prolog
 Absys
 Datalog
 Alma-0

Other ways to classify programming languages

You'll find many more ways to categorize languages beyond the five listed above. Let's take a
closer look at their other ways you can think about programming languages:
Front-end vs. back-end languages

Front-end languages are primarily concerned with the ‘user’ aspect of the software. The front end
deals with all of the text, colors, buttons, images, and navigation that the user will face when
navigating your website or application. Anyone with a background in graphic design or art may be
more inspired to begin learning one of the front-end languages.

Some examples of front-end programming languages include:


 HTML
 CSS
 JavaScript
 React

High-level vs. low-level languages

The biggest factor that differentiates high- and low-level programming languages is whether the
language is meant to be easily understood by a human programmer or a computer. Low-level
languages are machine-friendly, which makes them highly efficient in terms of memory usage but
difficult to understand without the help of an assembler. Since they're not very people-friendly
because they don't use human language, they're also not widely used to code. Examples of these
machine languages include machine code, binary code, and assembly languages.

High-level languages, on the other hand, are less memory efficient but much more human-
friendly. This programming style makes it easier to write, understand, maintain, and debug. Most
popular programming languages in use today are considered high-level languages.
Interpreted vs. compiled languages

The distinction between interpreted and compiled languages has to do with how they convert high-
level code and make it readable by a computer. With interpreted languages, code goes through a
program called an interpreter, which reads and executes the code line by line. This tends to make
these languages more flexible and platform independent.

Examples of interpreted languages include:


 Python
 JavaScript
 PHP
 Ruby

Compiled languages go through a build step where the entire program is converted into machine
code. This makes it faster to execute, but it also means that you have to compile or "build" the
program again anytime you need to make a change.

Examples of compiled languages include:


 C, C++, and C#
 Rust
 Erlang

Program Design

Program design consists of the steps a programmer should do before they start coding the
program in a specific language. These steps when properly documented will make the completed
program easier for other programmers to maintain in the future. There are three broad areas of
activity:

 Understanding the Program


 Using Design Tools to Create a Model
 Develop Test Data

Understanding the Program

If you are working on a project as one of many programmers, the system analyst may have
created a variety of documentation items that will help you understand what the program is to do.
These could include screen layouts, narrative descriptions, documentation showing the
processing steps, etc. If you are not on a project and you are creating a simple program you
might be given only a simple description of the purpose of the program. Understanding the
purpose of a program usually involves understanding its:

 Inputs
 Processing
 Outputs
This IPO approach works very well for beginning programmers. Sometimes, it might help to
visualize the program running on the computer. You can imagine what the monitor will look
like, what the user must enter on the keyboard and what processing or manipulations will be
done.

Programming Paradigms

In layman's terms, programming paradigms are a fundamental style of computer programming.

In technical terms, a programming paradigm is a way to deal with tackle issues utilizing some
programming language. Additionally, we can say that it is a strategy to take care of an issue
using tools and techniques that are accessible to us following some methodology.

It differs in the concepts and methods that are used to represent the elements (such as objects,
variables, functions, and constraints) of a program. And the steps that involve a calculation
(like assignations, evaluation, continuations, and data flows). The lowest programming
paradigm is machine code.

There are lots of things for programming languages that are known. However, every one of them
needs to follow some procedure when they are executed and this approach/methodology is a
paradigm.

Types of Programming Paradigms

There is the following two programming paradigm:

o Imperative Programming Paradigm


o Declarative Programming Paradigm
Imperative Programming Paradigm

Imperative programming is a programming paradigm that uses statements that change a


program's state. An imperative program consists of commands for the computer to perform. It
describes the detail of how the results are to be obtained. How means describing the inputs and
describing how the outputs are produced.

Examples of imperative programming paradigm are C, Fortran, Basic, Java, C++, Python, Ruby,
PHP, etc.

Advantages
o Easy to implement.
o It contains loops, variables, etc.
o It is efficient.

Disadvantages
o We cannot choose it for solving complex problems.
o It is less efficient and less productive.
o It is not suitable for parallel programming.
o Order is crucial.

Types of Imperative Programming Paradigm

There are the following types of imperative programming paradigms:

o Object-oriented Programming
o Procedural Programming
o Parallel Processing Approach

Object-oriented Programming

The object-oriented programming paradigm is based on the concept of object. An object


contains data in the form of fields that are known as attributes and the procedures are known
as methods.

Since objects work independently, they are encapsulated into modules. we can communicate
with an object by using message passing.

Object-oriented programming can be achieved by using programming languages such as Java,


C++, C#, PHP, and Python, etc.
Procedural Programming

The paradigm deals with procedure calls that are called routines or functions. the functions
contain a series of computational commands to be carried out to achieve a certain outcome.

It is just like a procedure, with a list of step-by-step instructions for the computer program to
follow. The code can easily be reused in different parts of the program. The advantage of the
paradigm is that the code can be easy to learn and read in simple programs. Though, while
dealing with a complex problem, we run the risk of ending up with a huge volume of code.

Example of procedural programming is BASIC, C, and Pascal.

Parallel Processing Approach

The parallel programming paradigm breaks the problem or task into chunks that are distributed
among multiple processors. These chunks work on the same problem, simultaneously. It reduces
the total time to solve a problem. It connects multiple processors to the memory. It is either
pooled across all processors or distributed over a network.

There are several programming languages that support parallel processing.

Example of parallel programming paradigm is SISAL, Parallel Haskell, SequenceL, System C


(for FPGAs), Mitrion-C, VHDL, and Verilog, MPI.

Declarative Programming Paradigm

Declarative programming is a style of building the structure and elements of computer


programs. It expresses the logic of a computation without describing its control flow. In other
words, styles of programming that are not imperative are called declarative programming
paradigm. It emphasizes what the program should accomplish.

Examples of declarative programming paradigm are Scala, Haskell, Erlang, Lisp, ML,
Closure, SQL, XSQL, etc.

Advantages
o Efficient and shortcode
o Referential Transparency
o Idempotence
o Error recovery
o Readability
o Commutativity
o Easy optimization
Disadvantages
o Difficult to understand.
o It is abed on an unfamiliar conceptual model.
o Difficult to accept characteristics of specific applications into account while
programming.

Types of Declarative Programming Paradigms


o Functional Programming
o Logical Programming
o Database Processing Approach

Functional Programming

It is a subset of declarative programming. Programs that are written using the paradigm use
functions, blocks of codes, intended to behave like mathematical functions. It discourages
changes in the value of variables through the assignment. Instead makes a great deal with
recursion.

Examples of functional programming Haskell, SML, Clojure, Scala, Erlang, Clean, F#, etc.

Logical Programming

The Logical Paradigm adopts a decisive strategy to critical thinking. Different consistent
declarations about a circumstance are made, setting up totally known realities. The paradigm is
divided into three sections:

1. A series of definitions/affirmations that characterize the problem domain


2. Statements of facts that are relevant
3. Statement of objectives or goals in the form of query

Example of logical programming is PROLOG, SQL, etc.

Database Processing Approach

The data-driven programming paradigm depends on information and its development. In this
paradigm, the program statements are characterized by data instead of hard-coding a progression
of steps. A data set program is the core of a business data framework and gives document
creation, information section, update, query, and reporting functions.

There are a few programming dialects that are developed for the most part for data set
applications. For example, SQL. It is applied to surges of organized information, for filtering,
transforming, aggregating, or calling different projects. So, it has its own wide application.
Example of database processing approach programming is SQL (only DQL), QML,
RDQL, and SPARQL.

Apart from the imperative and declarative programming approach, there is another paradigm that
is known as the multi-paradigm.

Multi-Paradigm

The programming languages that support more than one programming paradigm fall into this
category. The design goal of such languages is to allow programmers to use the most suitable
programming style associated with languages constructs for a given job.

The example of multi-paradigm programming languages is C++, Java, Python, etc. The
languages support object-oriented programming greater or lesser degree, typically in
combination with imperative and declarative programming paradigm.

Usually, in a program, distinctive programming standards are utilized. Henceforth, programming


dialects offer help (with various degrees) for the different standards.

The following table provides a brief description of programming paradigms.

Paradigms Key Program Program Execution Result


Concept

Procedural Command Sequence of commands Execution of commands Final state of


computer
memory

Functional Function Collections of functions Executions of functions Value of the


main function

Logic Predicate Logic formulas: axioms Logic proving of the Failure of


and a theorem theorem success of
proving

Object- Object Collections of classes of Exchange of messages Final state of


oriented objects between the objects the object's
state

The object-oriented paradigms state is the most abstract, as it's basic ideas can be easily
combined with the principles and programming techniques of the other styles.
Programming Paradigm Programming Languages

Procedural FORTRAN, COBOL, ALGOL, BASIC, C, and Pascal.

Functional Haskell, SML, Clojure, Scala, Erlang, Clean, F#, etc.

Object-oriented Java, Python, C++, C#, Kotlin, Scala, Swift, Ruby, Perl, etc.

Logical PROLOG, SQL, etc.

Parallel Processing SISAL, Parallel Haskell, SequenceL, System C (for FPGAs), Mitrion-C,
VHDL, and Verilog, MPI.

Database Processing SQL (only DQL), QML, RDQL, and SPARQL.


Approach

Imperative Vs. Declarative Programming Paradigm

The following table describes the key differences between the imperative and declarative
programming paradigm.
Basis of Imperative Paradigm Declarative Paradigm
Comparison

Programming Style Its style is step by step. Define what the problem is and what
data transformations are needed.

Approach It follows a traditional approach. It follows a non-traditional approach.

Programmer It describes how to solve problems. It describes what the problem is.
Focuses

Decision Capability The user makes decisions and It allows the compiler to make decisions.
instructs the compiler.

Consist of It is a sequence of commands. It is a set of statements.

Flow It expresses control flow. It expresses data flow.

State Change It is important. It does not exist.

Primary Instances of classes and structure. Functions as first-class object and data
Manipulation Unit collections.

Order of execution Order of execution is important. Order of execution is not important.

Example C, FORTRAN, Ada, Python, etc. PROLOG, LISP, Haskell, ASP, etc.

Characteristics & Concepts of OOPS

Object Oriented Programming is basically known to be a pattern that is used to design a program
just by the use of objects and classes.

This programming method in C++ generally simplifies the software development and the
maintenance by providing some basic concepts that are as follows:
 Class
 Objects
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
 Exception Handling

1. Class
Class can be defined as a blueprint of the object. It is basically a collection of objects which act
as building blocks.

A class contains data members (variables) and member functions. These member functions are
used to manipulate the data members inside the class.
2. Object
Objects are the basic unit of OOP. They are instances of class, which have data members and use
various member functions to perform tasks.

An Object can be defined as an entity that has a state and behavior, or in other words, anything
that exists physically in the world is called an object. It can represent a dog, a person, a table, etc.
An object means a combination of data and programs, which further represent an entity. The
benefits of classes and objects include:

1. Encapsulation: Classes allow encapsulating data and related functions into a single unit,
providing data hiding and preventing direct access. Objects represent instances of classes,
enabling modular and organized code structure.

2. Reusability: Classes facilitate code reusability by allowing the creation of multiple objects
with the same structure and behavior. This promotes efficient development and maintenance of
applications.

3. Modularity: Classes provide a modular approach to programming by grouping related data and
functions together. This enhances code organization, readability, and understandability.
3. Inheritance
The things or the properties and behaviors are generally acquired by one object from its parent
object is known to be the inheritance. It enhances the code reusability and in order to achieve
runtime of polymorphism.

The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.
Inheritance is a feature or a process in which, new classes are created from the existing classes.
The new class created is called “derived class” or “child class” and the existing class is known as
the “base class” or “parent class”. The derived class now is said to be inherited from the base
class.
When we say derived class inherits the base class, it means, the derived class inherits all the
properties of the base class, without changing the properties of base class and may add new
features to its own. These new features in the derived class will not affect the base class. The
derived class is the specialized class for the base class.
 Sub Class: The class that inherits properties from another class is called Subclass or Derived
Class.
 Super Class: The class whose properties are inherited by a subclass is called Base Class or
Superclass.

Types of Inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

Types of Inheritance in C++

1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e.
one subclass is inherited by one base class only.
Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};
OR
class A
{
... .. ...
};
class B: public A
{
... .. ...
};

2. Multiple Inheritances: Multiple Inheritances is a feature of C++ where a class can inherit
from more than one class. i.e one subclass is inherited from more than one base class.

Syntax:
class subclass_name : access_mode base_class1, access_mode
base_class2, ....
{
// body of subclass
};
class B
{
... .. ...
};
class C
{
... .. ...
};
class A: public B, public C
{
... ... ...
};
Here, the number of base classes will be separated by a comma (‘, ‘) and the access mode for
every base class must be specified.
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another
derived class.

Syntax:-
class C
{
... .. ...
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};
4. Hierarchical Inheritance: In this type of inheritance, more than one subclass is inherited
from a single base class. i.e. more than one derived class is created from a single base class.

Syntax:-
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than
one type of inheritance. For example: Combining Hierarchical inheritance and Multiple
Inheritance.

Below image shows the combination of hierarchical and multiple inheritances:

Modes of Inheritance: There are 3 modes of inheritance.

1. Public Mode: If we derive a subclass from a public base class. Then the public member of the
base class will become public in the derived class and protected members of the base class
will become protected in the derived class.
2. Protected Mode: If we derive a subclass from a Protected base class. Then both public
members and protected members of the base class will become protected in the derived class.
3. Private Mode: If we derive a subclass from a Private base class. Then both public members
and protected members of the base class will become Private in the derived class.

Note: The private members in the base class cannot be directly accessed in the derived class,
while protected members can be directly accessed. For example, Classes B, C, and D all contain
the variables x, y, and z in the below example. It is just a question of access.

The below table summarizes the above three modes and shows the access specifier of the
members of the base class in the subclass when derived in public, protected and private modes:
4. Polymorphism
The word “polymorphism” means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-life
example of polymorphism is a person who at the same time can have different characteristics. A
man at the same time is a father, a husband, and an employee. So the same person exhibits
different behavior in different situations. This is called polymorphism. Polymorphism is
considered one of the important features of Object-Oriented Programming.
Types of Polymorphism

 Compile-time Polymorphism
 Runtime Polymorphism

1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator overloading.

A. Function Overloading

When there are multiple functions with the same name but different parameters, then the
functions are said to be overloaded, hence this is known as Function Overloading. Functions can
be overloaded by changing the number of arguments or/and changing the type of arguments. In
simple terms, it is a feature of object-oriented programming providing many functions that have
the same name but distinct parameters when numerous tasks are listed under one function name.
There are certain Rules of Function Overloading that should be followed while overloading a
function.

B. Operator Overloading

C++ has the ability to provide the operators with a special meaning for a data type, this ability is
known as operator overloading. For example, we can make use of the addition operator (+) for
string class to concatenate two strings. We know that the task of this operator is to add two
operands. So a single operator ‘+’, when placed between integer operands, adds them and when
placed between string operands, concatenates them.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and dynamic
polymorphism are other names for runtime polymorphism. The function call is resolved at
runtime in runtime polymorphism. In contrast, with compile time polymorphism, the compiler
determines which function call to bind to the object after deducting it at runtime.
A. Function Overriding
Function Overriding occurs when a derived class has a definition for one of the member
functions of the base class. That base function is said to be overridden.
B. Virtual Function
A virtual function is a member function that is declared in the base class using the keyword
virtual and is re-defined (Overridden) in the derived class.
Some Key Points About Virtual Functions:
Virtual functions are Dynamic in nature.
They are defined by inserting the keyword “virtual” inside a base class and are always declared
with a base class and overridden in a child class
A virtual function is called during Runtime
5. Abstraction
Abstraction is generally known as the process of hiding internal details and displaying the
functionality. Abstract class and interface is used to get the abstraction in C++.
Data abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and hiding the
details. Data abstraction refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerator will increase the speed of the car or applying brakes will stop the car but he does not
know how on pressing the accelerator the speed is actually increasing, he does not know about
the inner mechanism of the car or the implementation of the accelerator, brakes, etc in the car.
This is what abstraction is.
Types of Abstraction:
Data abstraction – This type only shows the required information about the data and hides the
unnecessary data.
Control Abstraction – This type only shows the required information about the implementation
and hides unnecessary information.

6. Encapsulation
Encapsulation is basically binding or wrapping the code and the data into a single unit.

Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
7. Exception Handling
Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at
runtime.

Advantage of OOPs over Procedure-oriented Programming Language


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.

Characteristics of OOPs Concepts

The main characteristics of OOPs concepts are as follows:

- A method that implements in which programs classify as cooperative collections of objects.

- The object's state is set by the value of its properties whereas the behavior is by the operation it
gives.

- Major importance on data rather than procedural process.

- Programs are divided into entities defined as objects.

- Data structures are storage that is used to characterize objects.

- Data is safeguarded so that it is not accessible by external functions

- Functions that operate on data of an object bind together in data structures.


- Objects communicate with each other by sending and receiving information through functions.

- Easy addition of new data and functions whenever mandatory.

- It follows a bottom-up design approach in program design.

Benefits of OOPs Concepts

The best advantages of OOPs concepts include;

- Provides modularity and enhances program for easier troubleshooting as objects exist
independently

- Real world programming

- Code reusability through inheritance

- OOPs concepts designed with lesser limitations for larger programs are hard to write.

- Enhances easier and clear modular structure for programs.

- Flexibility through polymorphism

- Effective problem solving and better software quality

- Lower maintenance cost & resilience to change and hides information

- Flexibility of upgrading systems of any size

- Improvise the creation of Graphical User Interface (GUI) applications

- Faster goals achieved for programmers

- Greater programmer productivity & data become active

- Faster, accurate, better written applications compared to a procedural program

- Simple to develop and implement

- Much easier communication with the message passing capability


Procedural programming and object-oriented programming

Comparison between Procedural programming and object-oriented programming. We are


comparing both terms on the basis of some characteristics. The difference between both
languages are tabulated as follows -

S. On the Procedural Programming Object-oriented programming


no. basis of

1. Definition It is a programming language that is Object-oriented programming is a


derived from structure programming computer programming design
and based upon the concept of calling philosophy or methodology that
procedures. It follows a step-by-step organizes/ models software design
approach in order to break down a around data or objects rather than
task into a set of variables and functions and logic.
routines via a sequence of
instructions.

2. Security It is less secure than OOPs. Data hiding is possible in object-


oriented programming due to
abstraction. So, it is more secure than
procedural programming.

3. Approach It follows a top-down approach. It follows a bottom-up approach.

4. Data In procedural programming, data In OOP, objects can move and


movement moves freely within the system from communicate with each other via
one function to another. member functions.

5. Orientation It is structure/procedure-oriented. It is object-oriented.

6. Access There are no access modifiers in The access modifiers in OOP are
modifiers procedural programming. named as private, public, and
protected.

7. Inheritance Procedural programming does not There is a feature of inheritance in


have the concept of inheritance. object-oriented programming.

8. Code There is no code reusability present in It offers code reusability by using the
reusability procedural programming. feature of inheritance.

9. Overloading Overloading is not possible in In OOP, there is a concept of function


procedural programming. overloading and operator
overloading.
10. Importance It gives importance to functions over It gives importance to data over
data. functions.

11. Virtual class In procedural programming, there are In OOP, there is an appearance of
no virtual classes. virtual classes in inheritance.

12. Complex It is not appropriate for complex It is appropriate for complex


problems problems. problems.

13. Data hiding There is not any proper way for data There is a possibility of data hiding.
hiding.

14. Program In Procedural programming, a In OOP, a program is divided into


division program is divided into small small parts that are referred to as
programs that are referred to as objects.
functions.

15. Examples Examples of Procedural programming The examples of object-oriented


include C, Fortran, Pascal, and VB. programming are -
.NET, C#, Python, Java, VB.NET,
and C++.

What is C++?
C++ is a cross-platform language that can be used to create high-performance applications.
C++ was developed by Bjarne Stroustrup, as an extension to the C language.
C++ gives programmers a high level of control over system resources and memory.

Why Use C++


C++ is one of the world's most popular programming languages.
C++ can be found in today's operating systems, Graphical User Interfaces, and embedded
systems.
C++ is an object-oriented programming language which gives a clear structure to programs and
allows code to be reused, lowering development costs.
C++ is portable and can be used to develop applications that can be adapted to multiple
platforms.
As C++ is close to C, C# and Java, it makes it easy for programmers to switch to C++ or vice
versa.

Introduction to character sets


A character set is a collection of typographically correct symbols that are usable within a specific
language. A letter, a digit, or any other sign can be represented by something called a character.

C++ has the following character set:


 Letters: A-Z, a-z
 Digits: 0-9
 Special symbols: +, *, /, ^, \, (, ), [, ], {, }, =, !=, <, >, ', ", $, ;, :, %, !, &, _, #, <=, >=, @
 White spaces: blank space, horizontal tab, carriage return, newline, form feed

Above are the list of character set, which are used most of the time, specially the first two which
are "letters" and "digits". However, C++ can process any of the 256 ASCII characters as data or
as literals.

The term "literals" refers to the character or group of characters (word) that is used to describe
the value that is used in the program.

TOKENS

A token is a group of characters that logically belong together. The programmer can write a
program by using tokens. C++ uses the following types of tokens.
Keywords, Identifiers, Literals, Punctuators, Operators.

1. Keywords
These are some reserved words in C++ which have predefined meaning to compiler called
keywords. Some commonly used Keyword are given below:

Asm Auto Break case catch


Char Class Const continue default
Delete Do Double else enum
Extern inline Int float For
friend Goto If long New
operator private Protected public register
return Short Signed sizeof static
struct switch Template this Try
typedef union Unsigned virtual void
volatile While

2. Identifiers

Symbolic names can be used in C++ for various data items used by a programmer in his
program. A symbolic name is generally known as an identifier. The identifier is a sequence of
characters taken from C++ character set. The rule for the formation of an identifier are:
An identifier can consist of alphabets, digits and/or underscores.
It must not start with a digit
C++ is case sensitive that is upper case and lower-case letters are considered different from each
other.
It should not be a reserved word.
3. Literals

Literals (often referred to as constants) are data items that never change their value during the
execution of the program. The following types of literals are available in C++.
Integer-Constants
Character-constants
Floating-constants
Strings-constants
Integer Constants: Integer constants are the whole number without any fractional part. C++
allows three types of integer constants.
Decimal integer constants: It consists of a sequence of digits and should not begin with 0 (zero).
For example, 124, - 179, +108.
Octal integer constants: It consists of a sequence of digits starting with 0 (zero). For example.
014, 012. Hexadecimal integer constant: It consists of a sequence of digits preceded by ox or
OX.

Character constants
A character constant in C++ must contain one or more characters and must be enclosed in single
quotation marks. For example, 'A', '9', etc. C++ allows nongraphic characters which cannot be
typed directly from the keyboard, e.g., backspace, tab, carriage return etc. These characters can
be represented by using an escape sequence. An escape sequence represents a single character.
The following table gives a listing of common escape sequences.
Escape
Nongraphic Character
Sequence
\a Bell (beep)
\n Newline
\r Carriage Return
\t Horizontal tab
\0 Null Character

Floating constants
They are also called real constants. They are numbers having fractional parts. They may be
written in fractional form or exponent form. A real constant in fractional form consists of signed
or unsigned digits including a decimal point between digits. For example 3.0, -17.0, -0.627 etc.

String Literals
A sequence of characters enclosed in double quotes is called a string literal. String literal is by
default
;autoŵatiĐallLJͿ added a speĐialĐharaĐter ͚\0' which denotes the end of the string. Therefore,
the size of the string is increased by one character. For example "COMPUTER" will re-
represented as "COMPUTER\0" in the memory and its size is 9 characters.

4. Punctuators
The following characters are used as punctuators in C++.
Opening and closing brackets indicate single and multidimensional
Brackets [ ]
array subscript.
Parentheses Opening and closing brackets indicate functions calls, function
() parameters for grouping expressions etc.
Opening and closing braces indicate the start and end of a compound
Braces { }
statement.
Comma, It is used as a separator in a function argument list.
Semicolon ; It is used as a statement terminator.
Colon : It indicates a labeled statement or conditional operator symbol.
Asterisk * It is used in pointer declaration or as a multiplication operator.
Equal sign = It is used as an assignment operator.
Pound sign
It is used as pre-processor directive.
#

5. Operators:
An operator is a symbol that operates on a value to perform specific mathematical or logical
computations. They form the foundation of any programming language. In C++, we have
built-in operators to provide the required functionality.
An operator operates the operands. For example,
int c = a + b;
Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators
1) Arithmetic Operators

These operators are used to perform arithmetic or mathematical operations on the operands.
For example, ‘+’ is used for addition, ‘-‘ is used for subtraction ‘*’ is used for multiplication,
etc.
Arithmetic Operators can be classified into 2 Types:
A) Unary Operators: These operators operate or work with a single operand. For example:
Increment(++) and Decrement(–) Operators.
Name Symbol Description Example

int a = 5;
Increment Increases the integer value of the
++ a++; //
Operator variable by one
returns 6

int a = 5;
Decrement Decreases the integer value of the
— a–; // returns
Operator variable by one
4

Example:
the description
Output
a++ is 10
++a is 12
b-- is 15
--b is 13
Note: ++a and a++, both are increment operators, however, both are slightly different.
In ++a, the value of the variable is incremented first and then It is used in the program. In a+
+, the value of the variable is assigned first and then It is incremented. Similarly happens for
the decrement operator.
B) Binary Operators: These operators operate or work with two operands. For example:
Addition(+), Subtraction(-), etc.
Name Symbol Description Example

Addition + Adds two operands int a = 3, b = 6;


Name Symbol Description Example

int c = a+b; // c =
9

int a = 9, b = 6;
Subtracts second operand from the
Subtraction – int c = a-b; // c =
first
3

int a = 3, b = 6;
Multiplication * Multiplies two operands int c = a*b; // c =
18

int a = 12, b = 6;
Divides first operand by the second
Division / int c = a/b; // c =
operand
2

int a = 8, b = 6;
Modulo Returns the remainder an integer
% int c = a%b; // c
Operation division
=2

Note: The Modulo operator(%) operator should only be used with integers.

2) Relational Operators

These operators are used for the comparison of the values of two operands. For example, ‘>’
checks if one operand is greater than the other operand or not, etc. The result returns a
Boolean value, i.e., true or false.
Name Symbol Description Example

Is Equal To == Checks if both operands are equal int a = 3, b


= 6;
Name Symbol Description Example

a==b;
// returns
false

int a = 3, b
= 6;
Checks if first operand is greater than the
Greater Than > a>b;
second operand
// returns
false

int a = 3, b
= 6;
Greater Than or Checks if first operand is greater than or
>= a>=b;
Equal To equal to the second operand
// returns
false

int a = 3, b
= 6;
Checks if first operand is lesser than the
Less Than < a<b;
second operand
// returns
true

int a = 3, b
= 6;
Less Than or Checks if first operand is lesser than or
<= a<=b;
Equal To equal to the second operand
// returns
true

Not Equal To != Checks if both operands are not equal int a = 3, b


Name Symbol Description Example

= 6;
a!=b;
// returns
true

// CPP Program to demonstrate the Relational Operators


#include <iostream>
using namespace std;

int main()
{
int a = 6, b = 4;

// Equal to operator
cout << "a == b is " << (a == b) << endl;

// Greater than operator


cout << "a > b is " << (a > b) << endl;

// Greater than or Equal to operator


cout << "a >= b is " << (a >= b) << endl;

// Lesser than operator


cout << "a < b is " << (a < b) << endl;

// Lesser than or Equal to operator


cout << "a <= b is " << (a <= b) << endl;

// true
cout << "a != b is " << (a != b) << endl;

return 0;
}
Output
a == b is 0
a > b is 1
a >= b is 1
a < b is 0
a <= b is 0
a != b is 1
Here, 0 denotes false and 1 denotes true. To read more about this, please refer to the article
– Relational Operators .

3) Logical Operators

These operators are used to combine two or more conditions or constraints or to complement
the evaluation of the original condition in consideration. The result returns a Boolean value,
i.e., true or false.
Symbo
Name l Description Example

int a = 3, b =
6;
Logical Returns true only if all the operands are true or
&&
AND non-zero a&&b;
// returns true

int a = 3, b =
6;
Returns true if either of the operands is true or
Logical OR ||
non-zero a||b;
// returns true

int a = 3;
Logical !a;
! Returns true if the operand is false or zero
NOT
// returns
false

// CPP Program to demonstrate the Logical Operators


#include <iostream>
using namespace std;

int main()
{
int a = 6, b = 4;

// Logical AND operator


cout << "a && b is " << (a && b) << endl;

// Logical OR operator
cout << "a ! b is " << (a > b) << endl;

// Logical NOT operator


cout << "!b is " << (!b) << endl;

return 0;
}
Output
a && b is 1
a ! b is 1
!b is 0
Here, 0 denotes false and 1 denotes true.

4) Bitwise Operators
These operators are used to perform bit-level operations on the operands. The operators are
first converted to bit-level and then the calculation is performed on the operands.
Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at
the bit level for faster processing.

Name Symbol Description Example

int a = 2, b =
Copies a bit to the evaluated result if it exists 3;
Binary AND &
in both operands (a & b);
//returns 2

int a = 2, b =
Copies a bit to the evaluated result if it exists 3;
Binary OR |
in any of the operand (a | b);
//returns 3

Binary XOR ^ Copies the bit to the evaluated result if it is int a = 2, b =


present in either of the operands but not both 3;
Name Symbol Description Example

(a ^ b);
//returns 1

int a = 2, b =
Shifts the value to left by the number of bits 3;
Left Shift <<
specified by the right operand. (a << 1);
//returns 4

int a = 2, b =
Shifts the value to right by the number of 3;
Right Shift >>
bits specified by the right operand. (a >> 1);
//returns 1

int b = 3;
One’s
~ Changes binary digits 1 to 0 and 0 to 1 (~b);
Complement
//returns -4

Note: Only char and int data types can be used with Bitwise Operators.
// CPP Program to demonstrate the Bitwise Operators
#include <iostream>
using namespace std;

int main()
{
int a = 6, b = 4;

// Binary AND operator


cout << "a & b is " << (a & b) << endl;

// Binary OR operator
cout << "a | b is " << (a | b) << endl;

// Binary XOR operator


cout << "a ^ b is " << (a ^ b) << endl;

// Left Shift operator


cout << "a<<1 is " << (a << 1) << endl;
// Right Shift operator
cout << "a>>1 is " << (a >> 1) << endl;

// One’s Complement operator


cout << "~(a) is " << ~(a) << endl;

return 0;
}
Output
a & b is 4
a | b is 6
a ^ b is 2
a<<1 is 12
a>>1 is 3
~(a) is -7

5) Assignment Operators

These operators are used to assign value to a variable. The left side operand of the assignment
operator is a variable and the right side operand of the assignment operator is a value. The
value on the right side must be of the same data type as the variable on the left side otherwise
the compiler will raise an error.

Namemultiply Symbol Description Example

int a =
Assignment Assigns the value on the right to the variable 2;
=
Operator on the left
// a = 2

int a =
Add and First adds the current value of the variable on 2, b = 4;
Assignment += left to the value on the right and then assigns
Operator the result to the variable on the left a+=b; //
a=6

Subtract and -= First subtracts the value on the right from the int a =
Namemultiply Symbol Description Example

2, b = 4;
Assignment current value of the variable on left and then
Operator assign the result to the variable on the left a-=b; //
a = -2

First multiplies the current value of the int a =


Multiply and 2, b = 4;
variable on left to the value on the right and
Assignment *=
then assign the result to the variable on the a*=b; //
Operator
left a=8

int a =
Divide and First divides the current value of the variable 4, b = 2;
Assignment /= on left by the value on the right and then
Operator assign the result to the variable on the left a /=b; //
a=2

// CPP Program to demonstrate the Assignment Operators


#include <iostream>
using namespace std;

int main()
{
int a = 6, b = 4;

// Assignment Operator
cout << "a = " << a << endl;

// Add and Assignment Operator


cout << "a += b is " << (a += b) << endl;

// Subtract and Assignment Operator


cout << "a -= b is " << (a -= b) << endl;

// Multiply and Assignment Operator


cout << "a *= b is " << (a *= b) << endl;

// Divide and Assignment Operator


cout << "a /= b is " << (a /= b) << endl;

return 0;
}
Output
a=6
a += b is 10
a -= b is 6
a *= b is 24
a /= b is 6

6) Ternary or Conditional Operators(?:)

This operator returns the value based on the condition.


Expression1? Expression2: Expression3
The ternary operator ? determines the answer on the basis of the evaluation of Expression1. If
it is true, then Expression2 gets evaluated and is used as the answer for the expression.
If Expression1 is false, then Expression3 gets evaluated and is used as the answer for the
expression.
This operator takes three operands, therefore it is known as a Ternary Operator.
Example:
// CPP Program to demonstrate the Conditional Operators
#include <iostream>
using namespace std;

int main()
{
int a = 3, b = 4;

// Conditional Operator
int result = (a < b) ? b : a;
cout << "The greatest number is " << result << endl;

return 0;
}
Output
The greatest number is 4
7) There are some other common operators available in C++ besides the operators discussed
above. Following is a list of these operators discussed in detail:
A) sizeof Operator: This unary operator is used to compute the size of its operand or
variable.
sizeof(char); // returns 1
B) Comma Operator(,): This binary operator (represented by the token) is used to evaluate
its first operand and discards the result, it then evaluates the second operand and returns this
value (and type). It is used to combine various expressions together.
int a = 6;
int b = (a+1, a-2, a+5); // b = 11
C) -> Operator: This operator is used to access the variables of classes or structures.
cout<<emp->first_name;
D) Cast Operator: This unary operator is used to convert one data type into another.
float a = 11.567;
int c = (int) a; // returns 11
E) Dot Operator(.): This operator is used to access members of structure variables or class
objects in C++.
cout<<emp.first_name;
F) & Operator: This is a pointer operator and is used to represent the memory address of an
operand.
G) * Operator: This is an Indirection Operator
.
// CPP Program to demonstrate the & and * Operators
#include <iostream>
using namespace std;

int main()
{
int a = 6;
int* b;
int c;
// & Operator
b = &a;

// * Operator
c = *b;
cout << " a = " << a << endl;
cout << " b = " << b << endl;
cout << " c = " << c << endl;

return 0;
}

Output
a=6
b = 0x7ffe8e8681bc
c=6
H) << Operator: It is called the insertion operator. It is used with cout to print the output.
I) >> Operator: It is called the extraction operator. It is used with cin to get the input.
int a;
cin>>a;
cout<<a;

Operator Precedence Chart

Precedence Operator Description Associativity

() Parentheses (function call) left-to-right

[] Brackets (array subscript)

1. . Member selection via object name

-> Member selection via a pointer

++/– Postfix increment/decrement

2. ++/– Prefix increment/decrement right-to-left

+/- Unary plus/minus

!~ Logical negation/bitwise complement

(type) Cast (convert value to temporary value of


Precedence Operator Description Associativity

type)

* Dereference

& Address (of operand)

sizeof Determine size in bytes on this implementation

3. *,/,% Multiplication/division/modulus left-to-right

4. +/- Addition/subtraction left-to-right

5. << , >> Bitwise shift left, Bitwise shift right left-to-right

< , <= Relational less than/less than or equal to left-to-right

6.

> , >= Relational greater than/greater than or equal to left-to-right

7. == , != Relational is equal to/is not equal to left-to-right

8. & Bitwise AND left-to-right

9. ^ Bitwise exclusive OR left-to-right


Precedence Operator Description Associativity

10. | Bitwise inclusive OR left-to-right

11. && Logical AND left-to-right

12. || Logical OR left-to-right

13. ?: Ternary conditional right-to-left

= Assignment right-to-left

+= , -= Addition/subtraction assignment

*= , /= Multiplication/division assignment

14.

%= , &= Modulus/bitwise AND assignment

^= , |= Bitwise exclusive/inclusive OR assignment

<>= Bitwise shift left/right assignment

15. , expression separator left-to-right


Structure of a C++ Program

Before we start learning how to write a program in C++, let us first understand what a basic
structure of a C++ program looks like.

Example

This is how a simple basic structure of a C++ program looks like.

#include <iostream>
#include <conio.h>

using namespace std;


int main()
{

return 0;
}

Now we will discuss the various parts of the basic structure of a C++ program given above.

Preprocessor Directive

The Preprocessor Directive begins with the character #. It is used to include the necessary header
file in a C++ program before compilation.

Header File

The Header File contains the function declaration and macro definition for C++ in-built library
functions which we use in our C++ program during programing. When we include header file in
C++ program using #include <filename.h> command, all codes inside the header file is included
in the C++ program and then the program is sent to the compiler for compilation.

Namespace std

When we use using namespace std into the C++ program, then it does not require to write std:: in
front of standard commands throughout the code. Namespace std contains all the classes, objects
and functions of the standard C++ library.
Definition/Declaration Section

This section is used to define macro, structure, class and global variables to be used in the
programs, that means you can use these variables throughout the program.

Program Main Function (Entry Point)

In C++, the main function is treated as the entry point of the program, it has a return type (and in
some cases accepts inputs via parameters). The main function is called by the operating system
when the user runs the program.

Main Function Return Type

In the latest standard of C++, int is used as the return type of the main function. It means that the
C++ program on its successful completion will return a value which is of type int. The default
value of the return type is 0 if the program execution is normal.

Opening Brace

This is called the Opening Brace {. Whatever we will write inside the main function, we will
write it after the Opening Brace.

Body of Main Function

In this section, we will write our C++ program, which will be executed by the main function
after compilation.
Main Function Return Value

The return value for main is used to indicate how the program exited. If the program execution is
normal, a 0 return value is used. Abnormal termination(errors, invalid inputs, segmentation
faults, etc.) is usually terminated by a non-zero return.

Closing Brace

This is called the Closing Brace }. We use the Closing Brace at the end of the program.

Function Definition Section

When we want to define our function that fulfills a particular requirement, we can define them in
this section.

DATA TYPES

C++ supports many data types. The built-in or basic data types supported by C++ are an integer,
floating point, and character. These are summarized in table along with description and memory
requirement
By
Type Range Description
te
Int 2 -32768 to +32767 Small whole number
long int 4 -2147483648 to +2147483647 Large whole number
Float 4 3.4x10-38 to 3.4x10+38 Small real number
double 8 1.7x10-308 to 1.7x10+308 Large real numbe
long double 10 3.4x10-4932 to 3.4x10+4932 Very Large real number
char 1 0 to 255 A Single Character
C++ Variables
Variables in C++ is a name given to a memory location. It is the basic unit of storage in a
program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In C++, all the variables must be declared before use.
How to Declare Variables?
A typical variable declaration is of the form:
// Declaring a single variable
type variable_name;

// Declaring multiple variables:


type variable1_name, variable2_name, variable3_name;
A variable name can consist of alphabets (both upper and lower case), numbers, and the
underscore ‘_’ character. However, the name must not start with a number.

datatype: Type of data that can be stored in this variable.


variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
Examples:
// Declaring float variable
float simpleInterest;

// Declaring integer variable


int time, speed;

// Declaring character variable


char var;
We can also provide values while declaring the variables as given below:
int a=50,b=100; //declaring 2 variable of integer type
float f=50.8; //declaring 1 variable of float type
char c='Z'; //declaring 1 variable of char type
Rules For Declaring Variable
 The name of the variable contains letters, digits, and underscores.
 The name of the variable is case sensitive (ex Arr and arr both are different variables).
 The name of the variable does not contain any whitespace and special characters (ex #,$,
%,*, etc).
 All the variable names must begin with a letter of the alphabet or an underscore(_).
 We cannot used C++ keyword(ex float,double,class)as a variable name.

Valid variable names:


int x; //can be letters
int _yz; //can be underscores
int z40;//can be letters
Invalid variable names:
int 89; Should not be a number
int a b; //Should not contain any whitespace
int double;// C++ keyword CAN NOT BE USED

C++ Expression

C++ expression consists of operators, constants, and variables which are arranged according to
the rules of the language. It can also contain function calls which return values. An expression
can consist of one or more operands, zero or more operators to compute a value. Every
expression produces some value which is assigned to the variable with the help of an assignment
operator.

Examples of C++ expression:

1. (a+b) - c
2. (x/y) -z
3. 4a2 - 5b +c
4. (a+b) * (x+y)
An expression can be of following types:

o Constant expressions

o Integral expressions

o Float expressions

o Pointer expressions

o Relational expressions

o Logical expressions

o Bitwise expressions

o Special assignment expressions

If the expression is a combination of the above expressions, such expressions are known as
compound expressions.
Constant expressions

A constant expression is an expression that consists of only constant values. It is an expression


whose value is determined at the compile-time but evaluated at the run-time. It can be composed
of integer, character, floating-point, and enumeration constants.

Constants are used in the following situations:

o It is used in the subscript declarator to describe the array bound.

o It is used after the case keyword in the switch statement.

o It is used as a numeric value in an enum

o It specifies a bit-field width.

o It is used in the pre-processor #if

In the above scenarios, the constant expression can have integer, character, and enumeration
constants. We can use the static and extern keyword with the constants to define the function-
scope.

The following table shows the expression containing constant value:

Expression containing constant Constant value

x = (2/3) * 4 (2/3) * 4

extern int y = 67 67

int z = 43 43

static int a = 56 56

Let's see a simple program containing constant expression:

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x; // variable declaration.
6. x=(3/2) + 2; // constant expression
7. cout<<"Value of x is : "<<x; // displaying the value of x.
8. return 0;
9. }

In the above code, we have first declared the 'x' variable of integer type. After declaration, we
assign the simple constant expression to the 'x' variable.

Output

Value of x is : 3

Integral Expressions

An integer expression is an expression that produces the integer value as output after performing
all the explicit and implicit conversions.

Following are the examples of integral expression:

1. (x * y) -5
2. x + int(9.0)
3. where x and y are the integers.

Let's see a simple example of integral expression:

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x; // variable declaration.
6. int y; // variable declaration
7. int z; // variable declaration
8. cout<<"Enter the values of x and y";
9. cin>>x>>y;
10. z=x+y;
11. cout<<"\n"<<"Value of z is :"<<z; // displaying the value of z.
12. return 0;
13. }

In the above code, we have declared three variables, i.e., x, y, and z. After declaration, we take
the user input for the values of 'x' and 'y'. Then, we add the values of 'x' and 'y' and stores their
result in 'z' variable.

Output

Enter the values of x and y


8
9
Value of z is :17

Let's see another example of integral expression.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. int x; // variable declaration
7. int y=9; // variable initialization
8. x=y+int(10.0); // integral expression
9. cout<<"Value of x : "<<x; // displaying the value of x.
10. return 0;
11. }

In the above code, we declare two variables, i.e., x and y. We store the value of expression
(y+int(10.0)) in a 'x' variable.

Output

Value of x : 19
Float Expressions

A float expression is an expression that produces floating-point value as output after performing
all the explicit and implicit conversions.

The following are the examples of float expressions:

1. x+y
2. (x/10) + y
3. 34.5
4. x+float(10)

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. float x=8.9; // variable initialization
7. float y=5.6; // variable initialization
8. float z; // variable declaration
9. z=x+y;
10. std::cout <<"value of z is :" << z<<std::endl; // displaying the value of z.
11.
12.
13. return 0;
14. }

Output

value of z is :14.5

Let's see another example of float expression.


1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. float x=6.7; // variable initialization
6. float y; // variable declaration
7. y=x+float(10); // float expression
8. std::cout <<"value of y is :" << y<<std::endl; // displaying the value of y
9. return 0;
10. }

In the above code, we have declared two variables, i.e., x and y. After declaration, we store the
value of expression (x+float(10)) in variable 'y'.

Output

value of y is :16.7

Pointer Expressions

A pointer expression is an expression that produces address value as an output.

The following are the examples of pointer expression:

1. &x
2. ptr
3. ptr++
4. ptr-

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. int a[]={1,2,3,4,5}; // array initialization
7. int *ptr; // pointer declaration
8. ptr=a; // assigning base address of array to the pointer ptr
9. ptr=ptr+1; // incrementing the value of pointer
10. std::cout <<"value of second element of an array : " << *ptr<<std::endl;
11. return 0;
12. }

In the above code, we declare the array and a pointer ptr. We assign the base address to the
variable 'ptr'. After assigning the address, we increment the value of pointer 'ptr'. When pointer is
incremented then 'ptr' will be pointing to the second element of the array.

Output

value of second element of an array : 2

Relational Expressions

A relational expression is an expression that produces a value of type bool, which can be either
true or false. It is also known as a boolean expression. When arithmetic expressions are used on
both sides of the relational operator, arithmetic expressions are evaluated first, and then their
results are compared.

The following are the examples of the relational expression:

1. a>b
2. a-b >= x-y
3. a+b>80

Let's understand through an example

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=45; // variable declaration
6. int b=78; // variable declaration
7. bool y= a>b; // relational expression
8. cout<<"Value of y is :"<<y; // displaying the value of y.
9. return 0;
10. }

In the above code, we have declared two variables, i.e., 'a' and 'b'. After declaration, we have
applied the relational operator between the variables to check whether 'a' is greater than 'b' or not.

Output

Value of y is :0

Let's see another example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=4; // variable declaration
6. int b=5; // variable declaration
7. int x=3; // variable declaration
8. int y=6; // variable declaration
9. cout<<((a+b)>=(x+y)); // relational expression
10. return 0;
11. }

In the above code, we have declared four variables, i.e., 'a', 'b', 'x' and 'y'. Then, we apply the
relational operator (>=) between these variables.

Output

1
Logical Expressions

A logical expression is an expression that combines two or more relational expressions and
produces a bool type value. The logical operators are '&&' and '||' that combines two or more
relational expressions.

The following are some examples of logical expressions:

1. a>b && x>y


2. a>10 || b==5

Let's see a simple example of logical expression.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=2;
6. int b=7;
7. int c=4;
8. cout<<((a>b)||(a>c));
9. return 0;
10. }

Output

Bitwise Expressions

A bitwise expression is an expression which is used to manipulate the data at a bit level. They
are basically used to shift the bits.

For example:

x=3

x>>3 // This statement means that we are shifting the three-bit position to the right.
In the above example, the value of 'x' is 3 and its binary value is 0011. We are shifting the value
of 'x' by three-bit position to the right. Let's understand through the diagrammatic representation.

Let's see a simple example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x=5; // variable declaration
6. std::cout << (x>>1) << std::endl;
7. return 0;
8. }
In the above code, we have declared a variable 'x'. After declaration, we applied the bitwise
operator, i.e., right shift operator to shift one-bit position to right.

Output

Let's look at another example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x=7; // variable declaration
6. std::cout << (x<<3) << std::endl;
7. return 0;
8. }

In the above code, we have declared a variable 'x'. After declaration, we applied the left shift
operator to variable 'x' to shift the three-bit position to the left.

Output

56

Special Assignment Expressions

Special assignment expressions are the expressions which can be further classified depending
upon the value assigned to the variable.

o Chained Assignment

Chained assignment expression is an expression in which the same value is assigned to more
than one variable by using single statement.

For example:

1. a=b=20
2. or
3. (a=b) = 20
Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4.
5. int a; // variable declaration
6. int b; // variable declaration
7. a=b=80; // chained assignment
8. std::cout <<"Values of 'a' and 'b' are : " <<a<<","<<b<< std::endl;
9. return 0;
10. }

In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we have assigned the
same value to both the variables using chained assignment expression.

Output

Values of 'a' and 'b' are : 80,80


Note: Using chained assignment expression, the value cannot be assigned to the variable at the
time of declaration. For example, int a=b=c=90 is an invalid statement.

o Embedded Assignment Expression

An embedded assignment expression is an assignment expression in which assignment


expression is enclosed within another assignment expression.

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a; // variable declaration
6. int b; // variable declaration
7. a=10+(b=90); // embedded assignment expression
8. std::cout <<"Values of 'a' is " <<a<< std::endl;
9. return 0;
10. }

In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we applied embedded
assignment expression (a=10+(b=90)).

Output

Values of 'a' is 100

o Compound Assignment

A compound assignment expression is an expression which is a combination of an assignment


operator and binary operator.

For example,

1. a+=10;

In the above statement, 'a' is a variable and '+=' is a compound statement.

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=10; // variable declaration
6. a+=10; // compound assignment
7. std::cout << "Value of a is :" <<a<< std::endl; // displaying the value of a.
8. return 0;
9. }

In the above code, we have declared a variable 'a' and assigns 10 value to this variable. Then, we
applied compound assignment operator (+=) to 'a' variable, i.e., a+=10 which is equal to
(a=a+10). This statement increments the value of 'a' by 10.
Output

Value of a is :20

Control Structure in C++

Programs that we write are not only limited to a linear set of instructions, but there are also times
when we have to repeat a certain part of code, make decisions, and change the flow of the
program based on a specific condition being fulfilled or not, and more, there come our control
structures.

They form the basic building block of structured programming languages.

For example: Suppose we are in the traffic department and have to write a program that only
allows people to drive if they are above 18 and have their driving license; now, what will we do?

We will write a specific condition check in our program and will ask the user to enter their age
and to tell if they have their driving license, and if both the conditions are satisfied, then only we
will allow the user to drive.

This is exactly what control structures are; we are already familiar with them in real life. Our
program was going linearly, executing each line one by one, and when it encountered our
conditional control structure which will only execute if the condition provided will be fulfilled.

Many times in our code, we will need that a particular piece of code should only execute if a
specific condition gets fulfilled. In C++, along with Conditional Control Structures, we also have
the Iteration or Loop Control Structure.

Types of Control Structure in C++

There are three types of Control Structures in C++, And all the program processes we write can
only be implemented with these three control structures.

Sequence Structure

This is the most simple and basic form of a control structure. It is simply the plain logic we
write; it only has simple linear instructions, no decision making, and no loop. The programs we
all wrote at the start of our programming journey were this control structure only. It executes
linearly line by line in a straight line manner.

See the below code

#include <iostream>

using namespace std;

int main() {
int num1 = 4;
int num2 = 7; // Declaring and intializing two int variables.

int sum; // Declaring an int variable "sum".


sum = num1 + num2; // Adding num1 and num2 and equating it to the sum variable.

cout << sum << endl; // Printing the sum.

return 0;
}

Try it yourself

Output:

11

Let's understand the program flow and how it happened.

 Firstly, num1 and num2 were declared and initialized.


 Then, the sum variable was declared and was assigned the numerical sum
of num1 and num2.
 We are then printing the sum.

We can see that our program came one way, in a straight-line manner, with no bending, no
reverse, simply a straight flow. This is simply what Sequence Control Structures are.

Explore and unlock the recipe to transform your career

3700+

Placed at Google Amazon and other top tech companies

93.5% Placement Rate


21.6LPA Average salary of learners

126% average salary hike

₹900CR Salary created for Scaler graduates in last 4 years

Discover & connect with Alumni who have walked the same path as you

Krishna Chaitanya

Software Engineer III

Pre-Scaler

Sigmoid

Post-Scaler

200% Hike

I am a tech enthusiast now, but that was not always the case. I come from a non-tech background
and used to be very unfamilia... Read Full Review

Sudhanshu Gera

Software Engineer III

Pre-Scaler

Wipro Limited

Post-Scaler

150% Hike

At the beginning, it was not the easiest of tasks to cope up with the classes but I was stern in my
intent which helped me la... Read Full Review
Ankit Pangasa

Senior Software Engineer

Pre-Scaler

Adobe

Post-Scaler

200% Hike

Their course structure is impeccable and has truly helped me widen the horizons of my
knowledge. They have truly established ... Read Full Review

Vikas Tiwari

Backend Developer

Pre-Scaler

Innefu

Post-Scaler

180% Hike

All thanks to Scaler Academy for providing such amazing learning resources which helped me to
become a better engineer.... Read Full Review

Abinay Bingumalla

Full Stack

Pre-Scaler
Reliance Infocomm Limited

Post-Scaler

112% Hike

With Scaler, I became a lot more disciplined and focused. Without their support, maybe it would
have taken me a few more year... Read Full Review

Saliq Saifi

Senior Software Engineer

Pre-Scaler

Mahindra Comviva

Post-Scaler

400% Hike

The best career decision I ever made was to join Scaler by InterviewBit. I was preparing myself
but couldn't get any good opp... Read Full Review

Talk to Counsellor

Read All Reviews

Selection Structure

Sometimes in our program, we will need to write certain condition checks that this part of code
should only execute if a particular condition meets or another part of code should run.

For example: The example we took at the start is that we have to write a program that will
validate if a user is eligible to drive or not based on two conditions:

 if the age is equal to or above 18


 if the user has their driving license

Let's understand it with the help of a program

#include <iostream>
using namespace std;

int main() {
// Declaring two int variables to store age and if the user has the driving license.
int age, hasDrivingLicense;

cout << "Please Enter your Age : ";


cin >> age;
cout << "Are you having your Driving License, enter 1 for 'yes', 0 for 'no' : ";
cin >> hasDrivingLicense; // Taking the user input.

// Checking the condition.


if (age >= 18 && hasDrivingLicense == 1) {
// If fulfilled, then executing if part of the code.
cout << "Yes, you are Allowed to Drive" << endl;
} else {
// Else, executing else part of the code.
cout << "Sorry, you are not Allowed to Drive" << endl;
}

return 0;
}

Try it yourself

Output:

Please Enter your Age : 20


Are you having your Driving License, enter 1 for 'yes', 0 for 'no' : 1
Yes, you are Allowed to Drive

Here,

 We are first asking the user to enter their age and then ask if they have a driving license.
 Then we are checking the condition using an if-else control statement, and if it satisfies,
then executing the first block of code, else executing the other block of the code.

A block means a group of statements enclosed in curly brackets {....}, and those specific
statements are part of that specific block.

In C++, we have two types of Selection Control statements:

 If else statements
 Switch case statements We will be understanding in-depth about each of these in the
coming section.
Loop Structure

Suppose we are asked to write a program that prints "Hello World" once. We will simply write it
as:

#include <iostream>
using namespace std;

int main()
{
cout << "Hello World" << endl;

return 0;
}

Now, we are asked to write a program that will print "Hello World" 10 times; we can write it as

#include <iostream>

using namespace std;

int main() {
cout << "Hello World" << endl; // 1 time
cout << "Hello World" << endl; // 2 time
cout << "Hello World" << endl; // ..
cout << "Hello World" << endl; // ..
cout << "Hello World" << endl; // ..
cout << "Hello World" << endl; // ..
cout << "Hello World" << endl; // ..
cout << "Hello World" << endl; // ..
cout << "Hello World" << endl; // ..
cout << "Hello World" << endl; // 10 times

return 0;
}
Try it yourself

Output:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

But this seems like, a lot of repetition, but we can manage it somehow.

Now, what if we have to print it 100 or, let's say, 1000 times? Are we going to copy-paste the
same line 1000 times? No, that will not be feasible. There comes the use of loop control
structures.

Whenever in our program we see that a certain piece of code is being repeated repeatedly, then
we can enclose that in a loop structure and provide the condition that this code should execute
these specific number of times. Taking the above example, suppose we are asked to write a
program that will print "Hello World" 1000 times.

#include <iostream>

using namespace std;

int main() {
int num; // Declaring the num variable to store how many times the user wants the loop to run.
cout << "Enter how many you want to print : \n";
cin >> num; // Taking the user input.

for (int i = 0; i < num; i++) {


// Printing it till the condition is met.
cout << "Hello World" << endl;
}

return 0;
}

Try it yourself

Input:

1000
Output:

Hello World
Hello World
Hello World
1000 times

We have three types of Loops in C++:

 While Loop
 Do While Loop
 For Loop

Read more about C++ Loops Here

Explore free courses by our top instructorsView All

TARUN LUTHRA

Java Course - Mastering the Fundamentals

88k+ enrolled

RAHUL JANGHU

Python Course for Beginners With Certification: Mastering the Essentials

80k+ enrolled

PRATEEK NARANG
C++ Course: Learn the Essentials

44k+ enrolled

35,262+ learners have attended these Courses.

Control statements in C/C++ to Implement Control Structures


Conditional Statements

In general, we have two types of conditional statements in C++:

 if statements
 if else-if ladder

if conditional statements Sometimes we only want to check one condition, and if it meets, we
want to process some statements.

Syntax:

if [condition to be checked] {
// Statements to run.
}

Example:

#include <iostream>

using namespace std;

int main() {
int age; // Declaring age variable.
cout << "Enter your age : ";
cin >> age; // Taking the user input.

// Checking the condition inside if expression.


if (age >= 18) {
// Printing if the condition is satisfied.
cout << "You can drive" << endl;
}

return 0;
}

Try it yourself

Output:

Enter your age : 20


You can drive

From this, we can also see that the else part inside an if-else statement is optional.
if else-if ladder Unlike above, here we check for multiple cases.

Syntax:

if [condition to be checked] {
// Statements to run.
}
else if [statements to be checked] {
// Statements to run.
}
...
else {
// Statements to run.
}

Example:

#include <iostream>

using namespace std;

int main() {
int age; // Declaring age variable
cout << "Enter your age : ";
cin >> age; // Taking the user input

// Checking the condition inside each expression


if (age == 18) {
// Printing if the condition satisfies
cout << "Your age is 18" << endl;
} else if (age > 18) {
cout << "Age is greater than 18" << endl;
} else {
cout << "Age is neither equal to nor greater than 18" << endl;
}

return 0;
}

Try it yourself

Output:

Enter your age : 18


Your age is 18

Explanation: Here, first, we are reading the user's age from the console. Then we check if the
age is 18. In that case, we print "Your age is 18". If the age is greater than 18, then we print a
similar message. If both the above conditions are false, the age is smaller than 18, and we notify
the user with a similar message.
Iteration Statements

As discussed above, sometimes, in our program, when we want to repeat a certain set of
instructions, we can wrap them inside a loop. In C++, we have three types of iteration or loop
statements:

 While loop
 Do while loop
 For loop

while loop While loop is used when we want to run a loop till a condition is evaluated to be true

Syntax:

while [condition of loop] {


// statements to run
}

Example:

#include <iostream>

using namespace std;

int main() {
int end; // Declaring the end variable.
cout << "Enter the number till which you want to print : ";
cin >> end; // Taking the user input.

int start = 1; // Initialzing the start.

// Loop start
while (start <= end) // Termination condition
{
// Statements.
cout << start << endl;
// Incrementing the start variable, so that at some point loop
condition
// becomes false, and the program exits the loop.
start++;
}

return 0;
}

Try it yourself

Input:

10

Output:
1
2
3
..
..
10

do-while loop This is the same as the while loop. The only difference is that the loop runs at
least once, whether the condition is true or false.

Syntax:

do {
// Statements to run.
} while (condition to be checked);

Example:

#include <iostream>

using namespace std;

int main() {
int end; // Declaring the end variable.
cout << "Enter the number till which you want to print : ";
cin >> end; // Taking the user input.

int start = 12; // Initialzing the start.

// Loop termination condition.


do {
// Statements
cout << start << endl;
// incrementing the start variable, so that at some point loop
condition
// becomes false, and the program exits the loop
start++;

} while (start <= end);

// Even if the condition is false, still,


// the loop will run once and will print 12.

return 0;
}

Try it yourself

Input

10

Output:
12

for loop for loop is used when we are exactly sure in numbers for how many times our loop has
to run.

Syntax:

for(initialization; termination; increment or decrement) {


// Statements to run.
}

Example:

#include <iostream>

using namespace std;

int main() {
int end; // Declaring the end variable.
cout << "Enter the number till which you want to print : ";
cin >> end; // Taking the user input.

// Loop start.
for (int i = 1; i <= end; i++) {
cout << i << endl;
}

return 0;
}

Try it yourself

Output:

Enter the number till which you want to print : 10


1
2
3
4
5
6
7
8
9
10

Here we have just taken a small glimpse of what Iteration Statements in C++ are.

To understand deeply about loops, visit here


Jump Statements

As the name suggests, jump statements are used to jump out of a block of code, be it a
conditional statement, an iteration statement, or something else. In C++, we generally have 4
types of jump statements:

 break
 continue
 goto
 exit()

break statements Moves the program flow out of the current block when encountered.

Example:

#include <iostream>

using namespace std;

int main() {
// Loop statement start.
for (int i = 0; i < 10; i++) {
// If the condition is met.
if (i == 5) {
// When a break statement is encountered, the program will exit
the loop.
break;
}

cout << i << endl; // Printing the i's value.


}

return 0;
}

Try it yourself

Output:

0
1
2
3
4

The point to remember is that it only exits the first block or block in scope, i.e., if we are in
nested blocks, which means, block inside a block, then it will only exit the most inner block.

continue statement When encountered, it just skips that particular iteration, which means we are
telling the compiler that as soon as you see the continue statement, forget everything written
below it for that iteration, and start with the next iteration.
Example:

#include <iostream>

using namespace std;

int main() {
// Loop statement start.
for (int i = 0; i < 10; i++) {
// If the condition is met.
if (i == 5) {
// When continue statement will be encountered,
// the program will skip that iteration.
continue;
}

cout << i << endl; // Printing the i's value.


}

return 0;
}

Try it yourself

Output:

0
1
2
3
4
6
7
8
9

We can see that after the condition of i == 5 matches, and the program encounters
the continue statement, it skipped that particular iteration by skipping 5 in the output.

goto statement the goto statement is used to move the program flow to a user-defined label. The
use of goto is discouraged, as it sometimes confuses fellow programmers and those who will
read our code.

Example:

#include <iostream>

using namespace std;

int main() {
int num = 0; // Initializing num variable.

start: // Defining the label.


cout << num << endl;
num++; // Incrementing num variable.

// Checking condition.
if (num < 10) {
// If true, execute the goto statement, and move to label "start".
goto start;
}

cout << "End Reached"; // Finally printing

return 0;
}

Try it yourself

Output:

0
1
2
3
4
5
6
7
8
9
End Reached

We can see that goto can be used as a loop, along with a jump statement, but it is advised to
avoid the use of goto statements.

exit() function The purpose of using exit() is to terminate or exit the current program with a
specific exit code.

Example:

#include <iostream>

using namespace std;

int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
exit(0);
}
cout << i << endl;
}

return 0;
}

Try it yourself
Output:

0
1
2
3
4

It will exit the program, and the value we have supplied to the exit() function, here 0, will be
returned to the operating system as the program's exit code.

Switch Statements

Switch statements are like if-else statements only, but the difference here is that they check for
specific individual cases, unlike if-else statements, which also check for logical expressions.

Syntax:

switch(expression)
{
case value1:
// statements to run
break;
case value2:
// statements to run
break;
..
..
..
default:
// statements to run
}

Example:

#include <iostream>

using namespace std;

int main() {
int num; // Declaring num variable.
cout << "Enter a number : ";
cin >> num; // Taking the user input.

// Switch expression starts.


switch (num) {
// Checking for individual cases.
case 1:
cout << "The number is 1" << endl;
break;
case 2:
cout << "The number is 2" << endl;
break;
case 5:
cout << "The number is 5" << endl;
break;
default:
cout << "The number is neither 1 nor 2 nor 5" << endl;
}

return 0;
}

Try it yourself

Input:

Output:

The number is 2

Both the if-else and switch statements are selection statements and are used to transfer the flow
of the program to a specific block of statements upon certain conditions being met. But they
indeed have some minor differences. Let's now understand them.

Differences between if-else and switch statements

 Generally, the expression inside if-else statements are used to decide whether to run their
respective block of code if a condition is being met, for example, if (age >= 18) or if (age
< 60). On the other hand, in switch statements, we check for individual cases, i.e., case:
18, case: 19, or case: 60.
 In if statements, we can place multiple checks inside the same expression
using && operator, whereas in switch statements, we can only check one case at a time.
 If else expressions check for equality and logical expression, whereas switch checks only
for equality.
 If else statements can evaluate integers, floating-point values, characters, booleans, etc.,
whereas switch statements can only evaluate integer or character datatype.
 With if-else statements, the program flow is always like, either if block will execute or
else-if will execute or else will execute, which means only 1 block will execute from the
if-else ladder.
 On the other hand, in switch statements, we can execute all the cases below the matched
case if the break statements are not applied.
 It's time taking and challenging to modify if-else expressions if we want to change the
respective cases because tracing down which case is responsible for that specific task can
take some time, whereas, with switch statements, it is easy, as here, we are checking for
individual cases only. Hence, it's easy to track down the required expression.

True and False

Until now, we have understood the selection and iteration control statements, how each function,
and how the code executes.
But the most important part here is the conditions; both works on certain conditions being
evaluated as true or false, and both involve decision-making steps. C++ has a built-in
datatype bool, specifically designed to hold true and false values.

All the statements that we have studied till now, internally, are evaluated as booleans only. In C+
+, the value 0 is considered false and the value 1 is considered true.

Logical Operators

We will not always have simple condition checks in our program, like age >= 18 or num < 10,
sometimes, we will be in need to check even more complex conditions, we might have to chain
two or more conditions together; In that case, we will be using logical operators. We have three
types of logical operators in C++:

 && (logical and operator)


 || (logical or operator)
 ! (logical not operator)

Logical AND Operator (&&)

It is a binary operator, i.e., it needs two operands and is evaluated as true only if both the
operands are true.

Syntax:

[condition1 && condition2]

Example:

#include <iostream>

using namespace std;

int main() {
int num; // Declaring the num variable.
cout << "Enter a number : ";
cin >> num; // Taking the user input.

// Checking the condition.


if (num >= 10 && num < 20) {
cout << "The number is between 10 and 20" << endl;
} else {
cout << "The number is not between 10 and 20" << endl;
}

return 0;
}

Try it yourself

Input:
12

Output:

The number is between 10 and 20

We can see that only if both the conditions are true, i.e., num is greater than or equal
to 10 and num is less than 20, then only the condition will be true.

Truth Table:

condition1 condition2 condition1 && condition2

true true true

true false false

false true false

false false false

Logical OR Operator (||)

It evaluates to true if at least one of the operands is true.

Syntax:

[condition1 || condition2]

Example:

#include <iostream>

using namespace std;

int main() {
int num; // Declaring the num variable.
cout << "Enter a number : ";
cin >> num; // Taking the user input.

// Checking the condition.


if (num >= 10 || num < 20) {
cout << "The number is either greater than or equal to 10 or less than
20" << endl;
} else {
cout << "In this case, the if condition will always be true, so else
will never be executed" << endl;
}

return 0;
}
Try it yourself

Input:

22

Output:

The number is either greater than or equal to 10 or less than 20

We can see that if either of the two conditions is true, i.e., num is greater than or equal
to 10 or num is less than 20, then only the condition will be true.

Truth Table:

condition1 condition2 condition1 && condition2

true true true

true false true

false true true

false false false

Logical NOT Operator (!)

It is a unary operator and reverses the truth value of its operand.

Syntax:

[!condition]

Example:

#include <iostream>

using namespace std;

int main() {
bool isTrue = true; // intializing a boolean variable isTrue as true

isTrue = !isTrue; // now the value of isTrue is false

if (isTrue == true) {
cout << "If case executed" << endl;
} else {
cout << "Else case executed" << endl;
}
return 0;
}

Try it yourself

Output:

Else case executed

Conditional Operator

Also called a Ternary Operator, when sometimes we just want to do a small and short check
and do not want to write the long syntax of if-else or switch statements, then we can simply use
the ternary conditional operator.

Syntax:

condition ? statements if true : statements if false

Example:

#include <iostream>

using namespace std;

int main() {
int age; // Initialzing the age variable.
cout << "Enter your age : ";
cin >> age; // Taking the user input.

// Checking the condition using conditional operator.


age >= 18 ? cout << "You can vote" : cout << "You cannot vote";

return 0;
}

Conclusion

 Control Structures are used to alter the flow of the program based on certain conditions
being met or not.
 In C++, we mainly talk about selection and loop control structures.
 There are two selection control structures, if-else ladder and switch statements. Here
the if-else checks for equality and logical expressions, whereas switch only checks for
equality.
 In C++, we have three types of loops: while, do-while, and for loop. while and do-
while is preferred when we want to iterate through the loop till a certain condition is
being evaluated to be true, whereas for loop is used when we know exactly how many
times our loop is going to run.
 Jump statements are used to manipulate the flow of a program when encountered. In C+
+, we mainly have 4 types of jump statements: break, continue, goto, and exit().
 In C++, value 0 is evaluated as false and value 1 is evaluated as true.
 Logical operators are used to combine and check even more complex conditions in our
program. In C++ we have three logical operators: &&, ||, !.
 Ternary operator can be used for a quick selection check in our program.
Syntax : condition ? statements if true: statements if false.

Input/Output Operator in C++


In C++, input and output (I/O) operators are used to take input and display output. The
operator used for taking the input is known as the extraction or get from operator (>>),
while the operator used for displaying the output is known as the insertion or put to
operator (<<).
We’ll be covering the following topics in this tutorial:
 Input Operator
 Output Operator
 Cascading of Input/Output Operators
Input Operator

The input operator, commonly known as the extraction operator (>>), is used with the
standard input stream, cin. As stated earlier, cin treats data as a stream of characters.
These characters flow from cin to the program through the input operator. The input
operator works on two operands, namely, the c in stream on its left and a variable on
its right. Thus, the input operator takes (extracts) the value through cin and stores it in
the variable.
To understand the concept of an input operator, consider this example.
A program to demonstrate the working of an input operator.
#include
using namespace, std;
int main () {
int a;
cin>>a;
a = a+1;
return 0;
}

In this example, the statement cin>> a takes an input from the user and stores it in the
variable a.
Output Operator

The output operator, commonly known as the insertion operator (<<), is used. The
standard output stream cout Like cin, cout also treats data as a stream of characters.
These characters flow from the program to cout through the output operator. The
output operator works on two operands, namely, the cout stream on its left and the
expression to be displayed on its right. The output operator directs (inserts) the value
to cout.
To understand the concept of output operator, consider this example.
A program to demonstrate the working of an output operator.
#include
using namespace std;
int main () {
int a;
cin>>a;
a=a+1;
cout<<a;
return 0;
}

This example is similar to Example 1. The only difference is that the value of the
variable a is displayed through the instruction cout << a .
Cascading of Input/Output Operators

The cascading of the input and output operators refers to the consecutive occurrence
of input or output operators in a single statement.
To understand the concept of cascading of the input/output operator, consider these
examples.
A program without cascading of the input/output operator.
#include
using namespace std;
int main () {
int a, b;
cin>>a;
cin>>b;
cout<<"The value of a is";
cout<<a;
cout<<"The value of b is";
cout<<b;
return 0;
}

In this example, all cin and cout statements use separate input and output operators
respectively However, these statements can be combined by cascading the input and
output operators accordingly as shown in this example.
A program with cascading of the input/output operator
#include
using namespace std;
int main () {
int a, b;
cin>>a>>b;
cout<<"The value of b is : "<<b;
cout<<"The value of a is "<<a;
return 0;
}

In this example, the cascaded input operators wait for the user to input two values and
the cascaded output operator first displays the message The value of a is: and then
displays the value stored in a. Similar is the case for the next statement.
It can be observed that cascading of the input/output operator improves the readability
and reduces the size of the program.
Array in C++
Arrays: When there is a need to use many variables, then there is a big problem
because we will Conflict with the name of variables. So that in this situation where we
want to Operate on many numbers, we can use array. The Number of Variables also
increases the complexity of the Program so that we use Arrays.
Arrays Set of Elements having the same data type, or we can Say that Arrays are
Collections of Elements having the same name and same data type. But Always
Remember Arrays Always started From their index value, and the index of the array
starts From 0 to n-1.
If we want to Access the 5th Element of the array, we will use the 4th Element Because
Arrays are Start From 0, and arrays always stored in Continuous Memory Locations.
The Subscript of array Elements identifies the Number of Elements and Types of the
array.
Arrays in C++ must be defined before they can be used to store information. Arrays are
defined in the same manner as that of basic types except that each array name must
be associated with its size specification. Array names must follow the same
conventions as that of an identifier. The general form for defining an array is
1 type array_name[size];

Here, type specifies the data type of each element of the array, followed by the name of the
array array_name. The size specifies the maximum number of elements that can be stored in an
array. The size must be an integer constant greater than 0.
For example, the statement.

Defines
an int array named marks that can store marks of 10 students in a subject. Since only a single
subscript is used, so it represents a one-dimensional array. The storage space allocated to the
above array is equal to the maximum number of elements (i.e., 10) multiplied by the size of the
data type used, in our example int (i.e., 2). So, at the time of array definition, a total of 20 bytes
are allocated for the above array. All the array elements are stored in
contiguous memory locations (i.e., one after the other).
Each box represents an element of an array of marks. Each array element is represented by an
array name followed by a unique index or subscript that specifies the position within the array.
The array elements are numbers starting from 0. As there are 10 elements in this array, so the
index number ranges from 0 to 9.
Some more examples of array definitions are given below.
1 float salary[5];

It defines an array salary containing 5 elements of float type,


1 double sale[20] ,temp[10];

It defines two arrays, sale and temp, containing 20 and 10 elements respectively of double type.
It is sometimes convenient to define an array size in terms of symbolic constants rather than a
fixed integer quantity. This makes it easy to modify the program by simply changing the value
of the symbolic constant.
Let us consider an example,
1 #include<iostream.h>

2 #define n 20

int main() {
3
int s[n]; //valid as value of n is pre-defined
4
...........................
5
...........................
6
}
7

Here, n is used as a symbolic constant which is defined using preprocessor directive #define. It
is initialized to a value 20 so the size of the array s is 20.
We’ll be covering the following topics in this tutorial:
 Access Array Elements
 Initialization of Array
Access Array Elements

Once the array is created, you can access an array element by using the name of the array
followed by an index enclosed between a pair of square brackets. The index or subscript of an
array indicates the position of an element in the array. The index of first element in the array is
always 0 (zero), the second element has an index 1 and so on. The index of last element is
always one less than the number of elements in the array. The syntax for accessing an array
element is
1 array_name [index];

Here, index is an integer constant or an expression that evaluates to an int.In the above Figure,
the first element of the array is marks [0],the second element is marks [1] and last element is
marks[9].
Similarly, if the user needs to access the 6th element of array marks, he has to write marks [5].
Thus, the individual elements of array marks can be referred as marks [0], marks[1], marks[2],
marks[3] ,……., marks[9].
One should make sure that array indexes must be between 0 and number of elements minus 1.
Similarly, to assign value to an element of an one dimensional array, use the following syntax
1 array_name [index] = value;

For example, in order to assign a value 25 to an element of array marks at index 1, you need to
write
1 marks[1] = 25;

1 #include <iostream.h>

2 #include <conio.h>

int main() {
3
clrscr();
4
int a[5]; //defines 5 elements array
5
cout<<"Enter elements of an array : ";
6
7
for(int i=0;i<5;i++)//reading array elements
8
{
9
cin>>a[i];
10
}
11
for(i=0;i<5;i++)//displaying array elements
12
{
13 cout<<"a["<<i<<"]="<<a[i]<<"\n";

14 }

15 getch(); return 0;

16 }

Output :
17
Enter elements of an array : 5 10 -2 3 12
18
a[O] = 5
19
a[l] = 10
20
a[2] = -2
21
a[3] = 3
22 a[4] = 12

23

Explanation: The above program first reads the elements of an array and then prints
the values stored in them. The a[i] corresponds to the (i-1)th element of an array a. The
loop variable i in for loop starts from 0 (representing index for first element) to 4 so as
to input or display 5 elements of array a.
The statement cin>>a[i]; in the for loop inputs various elements of array a
corresponding to each value of index i, which are then displayed using another for
loop.
When i=0 then in the statement cin>>a [i]; i is replaced with 0 and value for 1st element
of array is inputted. Similarly for other elements.
Initialization of Array
Definition of an array doesn’t automatically results in the initialization of the array
elements. It only allocates contiguous memory to an array with each element assigned
some garbage value. We can initialize an array definition by following the definition with
an equal to (=) sign followed by comma separated list of values enclosed in curly
braces. The order of assignment of values to array elements will be the same as they
appear in the initialization list.
The syntax of array initialization is
1 type array_name[size] = {valuel,value2, .... };

Let us consider an example,


1 int a[3]={21,31,4};

The above statement defines an integer array named a of size 3 and also initialize the
elements to 21, 31 and 4. The elements are assigned in the order of their appearance

So 21 is assigned to a[0]
31 is assigned to a[1]
and 4 is assigned to a[2]
The size of an array can be omitted during initialization. The compiler automatically
determines the array size by the number of elements enclosed in curly braces.
So, the following statement is valid.
1 int[]={21,31,4};

In, the above statement, the size of array is considered as 3, as there are three values
specified in the initialization list. This feature of not specifying the size of array provides
the benefit that on adding more elements during initialization, we· don’t need to change
the size specification of an array.
If the size of an array is specified, the number of elements specified in the initialization
list must not be greater than that size. Otherwise, the compiler generates an error.
However, if the size of an array is greater than the number of elements specified then
the remaining elements are initialized to 0. For example :
1 int a[3]={4,6,2,7};//Invalid

2 int a [4]={14,16};//Valid

The first statement is invalid as size of array is less than the number of values specified
in initialization list. The second statement is valid and the elements are assigned as
follows,
1 a[0] = l4,a[1] = l6,a[2] = 0,a[3] = 0
If the user wishes to assign 10, 20 and 30 values to the second, third and fourth
element of an array and skip the first element using the following statement,
1 int a[4]={,10,20,30}; // is illegal

1
#include<iostream.h>
2
#include<conio.h>
3
int main() {
4
clrscr();
5 int x[6] = {l0,ll,-5,20,15,18};

6 cout<<"Display even elements\n";

7 for(int i;0;i<6;i++) {

8 if(x[i]%2 ==0)

cout<<x[i]<<"\t";
9
}
10
getch();
11
return 0;
12
}
13

Explanation: In the above program, we first define and intialize an array x and then
display the even numbers stored in it. To check whether a given number is even or not,
divide the number (which is represented by x [i]) by 2 and check the remainder. If the
remainder is 0 then the number is even which is then displayed.
The Various types of Array those are provided by C++ as Follows:
1. Single Dimensional Array
2. Two Dimensional Array
3. Three Dimensional array
4. Character Array or Strings.
A dimensional is used representing the elements of the array for example
1 int a[5]
The [] is used for dimensional or the sub-script of the array that is generally used for
declaring the elements of the array For Accessing the Element from the array we can
use the Subscript of the Array like this
1 a[3]=100

This will set the value of 4th element of array. So there is only the single bracket then it
called the Single Dimensional Array. This is also called as the Single Dimensional
Array
Two Dimensional Array or the Matrix
The Two Dimensional array is used for representing the elements of the array in the
form of the rows and columns and these are used for representing the Matrix A Two
Dimensional Array uses the two subscripts for declaring the elements of the Array
1 Like this int a[3][3]

So This is the Example of the Two Dimensional Array In this first 3 represents the total
number of Rows and the Second Elements Represents the Total number of Columns
The Total Number of elements are judge by Multiplying the Numbers of Rows *
Number of Columns in The Array in the above array the Total Number of elements are
9
Multidimensional or the Three Dimensional Array :The Multidimensional Array are
used for Representing the Total Number of Tables of Matrix A Three dimensional Array
is used when we wants to make the two or more tables of the Matrix Elements for
Declaring the Array Elements we can use the way like this
1 int a[3][3][3]

In this first 3 represents the total number of Tables and the second 3 represents the
total number of rows in the each table and the third 3 represents the total number of
Columns in the Tables So this makes the 3 Tables having the three rows and the three
columns
The Main and very important thing about the array that the elements are stored always
in the Contiguous in the memory of the Computer
Character Array of String: Like an integer characters are also be in the Array The
Array of Characters are called as the Strings They are Generally used for representing
the Strings Always Remember that a String is Terminated with the \0 or Null Character.
There are the built in string Operation those are provided by the C Language in the
String.h Header file Like

1) strlen: For Getting the Length or Total Numbers of Characters in String.

2) strconcat: This is Used for Joining the two Strings or This function is used for
Concatenating the two Strings.
3) strrev: This Function is used for obtaining the Reverse of the String.

4) strcmp: This Function is used for Comparing the Two Strings and it gives us the
Result as follows after comparing the Two Strings.
1 it Returns us + value

2 if String1 is Greater than String2

3 it Returns us the - Value

4 if String1 is Less than String2

5 it Returns us the 0

if string1 is Equals to String2


6

Like The array elements of Integer Types The Character array also are the Single
Dimensional or The Two Dimensional Array.
Single Dimensional Array The Single Dimensional array are used for creating the
Number of characters like
1 char name[10]

in this we can use the 10 characters on the name variable Means we can give the
name as 10 characters long
Two Dimensional array :-When we talk about the Two Dimensional of the Character
array The first Subscript of the array if used for representing the Total Numbers of
Strings and the second Subscript is used for defining the length of the array Characters
in the String like This
1 char name[5][10]

It declares the 5 names and each having the characters up to 10 So the First Subscript
is used for defining the total number of the Strings and the Second is used for Length
of the Character.
Arrays as Class Members in C++
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.
Example: A program to demonstrate the concept of arrays as class members
The output of the program is
1 #include<iostream>

2 using namespace std;

const int size=5;


3
class student
4
{
5
int roll_no;
6
int marks[size];
7
public:
8
void getdata ();
9 void tot_marks ();

10 } ;

11 void student :: getdata ()

{
cout<<"\nEnter roll no: ";
12
cin>>roll_no;
13
for(int i=0; i<size; i++)
14
{
15
cout<<"Enter marks in subject"<<(i+1)<<": ";
16
cin>>marks[i] ;
17
}
18 void student :: tot_marks() //calculating total marks

19 {

20 int total=0;

21 for(int i=0; i<size; i++)

22 total+ = marks[i];

cout<<"\n\nTotal marks "<<total;


23
}
24
int main() {
25
student stu;
26
stu.getdata() ;
27
stu.tot_marks() ;
28 return 0;

29 }

Enter roll no: 101


Enter marks in subject 1: 67
Enter marks in subject 2 : 54
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
Enter marks in subject 5 : 82
Total marks = 343
In this example, an array marks is declared as a private member of the class student
for storing a student’s marks in five subjects. The member function tot_marks ()
calculates the total marks of all the subjects and displays the value.
Similar to other data members of a class, the memory space for an array is allocated
when an object of the class is declared. In addition, different objects of the class have
their own copy of the array. Note that the elements of the array occupy
contiguous memory locations along with other data members of the object. For
instance, when an object stu of the class student is declared, the memory space is
allocated for both rollno and marks

C++ Functions

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.

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
void myFunction()

{
// code to be executed

Example Explained
 myFunction() is the name of the function
 void means that the function does not have a return value. You will learn
more about return values later in the next chapter
 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:

Example
Inside main, call myFunction():

// create a function

void myFunction()

{
cout << "I just got executed!";

int main()

{
myFunction(); // call the function

return 0;
}

// Outputs "I just got executed!"

A function can be called multiple times:

Example
void myFunction()

{
cout << "I just got executed!\n";
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

// I just got executed!

// I just got executed!

// I just got executed!

Function Declaration and Definition

A C++ function consist of two parts:

 Declaration: the return type, the name of the function, and parameters (if
any)
 Definition: the body of the function (code to be executed)

void myFunction()
{ // declaration
// the body of the function (definition)
}

Note: If a user-defined function, such as myFunction() is declared after


the main() function, an error will occur:

Example

int main()

{
myFunction();
return 0;
}
void myFunction()

{
cout << "I just got executed!";

// Error

However, it is possible to separate the declaration and the definition of the function
- for code optimization.

You will often see C++ programs that have function declaration above main(), and
function definition below main(). This will make the code better organized and
easier to read:

Example
// Function declaration
void myFunction();

// The main method


int main()

{
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction()

{
cout << "I just got executed!";
}

You might also like