[go: up one dir, main page]

0% found this document useful (0 votes)
51 views138 pages

Computr Progaming CPP

The document is a comprehensive manual on computer programming, covering various programming languages, problem-solving techniques, and the C and C++ languages. It includes sections on software types, programming language generations, and structured programming concepts. The manual is compiled by Asst Prof. Anshu Ghimire from the Department of CSE, providing foundational knowledge for computer science students.

Uploaded by

Ishwor Neupane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views138 pages

Computr Progaming CPP

The document is a comprehensive manual on computer programming, covering various programming languages, problem-solving techniques, and the C and C++ languages. It includes sections on software types, programming language generations, and structured programming concepts. The manual is compiled by Asst Prof. Anshu Ghimire from the Department of CSE, providing foundational knowledge for computer science students.

Uploaded by

Ishwor Neupane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 138

COMPUTER PROGRAMMING

MANUAL

Compiled By: Asst Prof. Anshu Ghimire,Dept of CSE,nec


Changunarayan
Contents

Unit I Introduction to Programming Language ................................................. 3


1.1 Programming Language –Machine Level Language, Assembly Language and High Level Language ..... 3
1.2 Software and its type .............................................................................................................................. 5
1.3 Generation of Programming Language ................................................................................................... 6
1.4 Structured Programming Language ........................................................................................................ 8
Unit II Problem Solving Using Computer ....................................... 10
2.1 Problem Analysis (Understanding of the problem, feasibility and requirement analysis) ................... 10
2.2 Design (Algorithm and Flowchart) ........................................................................................................ 11
2.3 Coding (Compilation and Execution) .................................................................................................... 14
2.4 Testing and Debugging .......................................................................................................................... 14
2.5 Implementation, Evaluation and Maintenance of Computer Program ................................................ 17
2.6 Programming Documentation............................................................................................................. 17
Unit III The C Language and its Basic Constructs .................................................. 18
3.1 History of C Language ........................................................................................................................... 18
3.2 Features of C ......................................................................................................................................... 19
3.3 The C Character Set ............................................................................................................................... 20
3.4 Keywords and Identifier ........................................................................................................................ 21
3.5 Data Types............................................................................................................................................. 22
3.6 Constants, Variables and their declarations ......................................................................................... 24
3.7 Formatted Input / Output Functions .................................................................................................... 26
3.8 The C-Operators .................................................................................................................................... 33
3.9 Control Structures-branching statements (if, if-else and switch statements) looping statements (for,
while and do-while) .................................................................................................................................... 36
Unit IV Array and Structures in C ..................................................................... 46
4.1 Arrays (one dimensional and multi-dimensional arrays) ...................................................................... 46
4.2 Initializations of arrays and accessing the elements of arrays ............................................................. 48
4.3 Character Arrays (Strings) ..................................................................................................................... 54
4.4 Structure and Union .............................................................................................................................. 59
Unit V Functions and Pointers in C......................................................................... 68
5.1 Functions and their importance............................................................................................................ 68
5.2 Declaration of a function ...................................................................................................................... 68

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 1


5.3 Structure of function and return statement ......................................................................................... 69
5.4 Library and User-Defined functions ...................................................................................................... 70
5.5 Function Arguments and Return Types ................................................................................................ 74
5.6 Local and Global Variables .................................................................................................................... 77
5.7 Calling a function-Call by Value............................................................................................................. 79
5.8 Pointers, Pointer Operators and Pointer Arithmetic ............................................................................ 80
Unit VI Introduction to C++ .......................................................................... 86
6.1 Procedure –Oriented vs. Object Oriented Programming ..................................................................... 86
6.2 Concept of Object-Oriented Programming ........................................................................................... 89
6.3 Origin of C++ ......................................................................................................................................... 94
6.4 Features of C++ ..................................................................................................................................... 95
6.5 C++ Program Structure.......................................................................................................................... 97
6.6 Input/ Output Stream ........................................................................................................................... 98
6.7 Access Specifiers ................................................................................................................................. 101
6.8 Objects and accessing data members and member functions ........................................................... 105
6.9 Constructors (Default and Parameterized) and Destructors .............................................................. 108
Unit VII Object –Oriented Programming Concepts ............................................. 115
7.1. Inline function .................................................................................................................................... 115
7.2 Friend Function ................................................................................................................................... 116
7.3 Function overloading .......................................................................................................................... 120
7.4 Inheritance and its types (Single, Multiple, Multi-level) ..................................................................... 121
7.5 Function Overriding ............................................................................................................................ 127
7.6 Template Function .............................................................................................................................. 131
7.7 Exception Handling ............................................................................................................................. 134

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 2


Unit I Introduction to Programming Language

1.1 Programming Language –Machine Level Language, Assembly Language and High Level
Language
Programming Language is a standardized communication technique for describing instructions to a computer.
Each programming language has a set of syntactic and semantic rules used to define computer programs. The
different types of programming language are described below.

Low Level Languages are those languages which are closer to the hardware. They are specific to the hardware
so cannot run on different hardware. Knowledge of hardware is required to develop such programs using low
level languages. It can be divided into Machine language and Assembly language.

Machine Language:

Low-Level language is the only language which can be understood by the computer. Low-level language is also
known as Machine Language. The machine language contains only two symbols 1 & 0. All the instructions of
machine language are written in the form of binary numbers 1's & 0's. A computer can directly understand the
machine language

Advantages:

 It makes fast and efficient use of computers


 Translator is not required.

Disadvantages:

 Programmer should have hardware knowledge.


 All memory addresses and operation codes are needed to be remembered.
 Testing and Debugging are difficult to carry out.
 They are machine dependent.

Assembly Language:

Middle-level language is a computer language in which the instructions are created using symbols such as letters,
digits and special characters. Assembly language is an example of middle-level language. In assembly language,
we use predefined words called mnemonics. Binary code instructions in low-level language are replaced with
mnemonics and operands in middle-level language. But the computer cannot understand mnemonics, so we use
a translator called Assembler to translate mnemonics into machine language.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 3


Assembler is a translator which takes assembly code as input and produces machine code as output. That means,
the computer cannot understand middle-level language, so it needs to be translated into a low-level language to
make it understandable by the computer. Assembler is used to translate middle-level language into low-level
language.

Advantages:

 Easier to understand and use as compared to machine language.


 Programs are normally very fast and very compact.
 Timings can be calculated very precisely and program flow is easily controlled.

Disadvantages:

 Good Understanding of the hardware is required.


 Machine dependent

High Level language:

High-level language is a computer language which can be understood by the users. The high-level language is
very similar to human languages and has a set of grammar rules that are used to make instructions more easily.
Every high-level language has a set of predefined words known as Keywords and a set of rules known as Syntax
to create instructions. The high-level language is easier to understand for the users but the computer cannot
understand it. High-level language needs to be converted into the low-level language to make it understandable
by the computer. We use Compiler or interpreter to convert high-level language to low-level language.

Languages like FORTRAN,C, C++, JAVA, Python, etc., are examples of high-level languages. All these
programming languages use human-understandable language like English to write program instructions. These
instructions are converted to low-level language by the compiler or interpreter so that it can be understood by
the computer.

Compiler is a computer program that transforms code written in a high-level programming language into the
machine code. It is a program which translates the human-readable code to a language a computer processor
understands (binary 1 and 0 bits). The computer processes the machine code to perform the corresponding tasks.

Role of Compiler

Compliers reads the source code, outputs executable code. Translates software written in a higher-level language
into instructions that computer can understand. It converts the text that a programmer writes into a format the
CPU can understand. The process of compilation is relatively complicated. It spends a lot of time analyzing and
processing the program. The executable result is some form of machine-specific binary code

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 4


Interpreter is a computer program, which converts each high-level program statement into the machine code.
This includes source code, pre-compiled code, and scripts. Both compiler and interpreters do the same job which
is converting higher level programming language to machine code. However, a compiler will convert the code
into machine code (create an exe) before program run. Interpreters convert code into machine code when the
program is run.

Role of Interpreter

 The interpreter converts the source code line-by-line during RUN Time.
 Interpret completely translates a program written in a high-level language into machine level language.
 Interpreter allows evaluation and modification of the program while it is executing.
 Relatively less time spent for analyzing and processing the program

Program execution is relatively slow compared to compiler

Figure: Compiler vs. Interpreter

1.2 Software and its type

Software is a collection of machine readable instructions that directs a computer to perform some specific tasks.
It is an ordered sequence of instructions given for changing the state of the computer hardware in a certain
predefined sequence. Generally software can be categorized as system software and application software. The
detail descriptions of system software and application software along with their sub-categories are given below:

1) System software: It is a type of computer software designed to operate the computer hardware, to provide
basic functionality and to provide a platform for running application software. System software include device
drivers, operation systems etc. It is responsible for controlling, integrating and managing the individual hardware
components of a computer system so that they can work together harmoniously. Its purpose is to hide the
complex details of the hardware.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 5


 Operating system is the main system software which controls all parts of the computer system. The major
function of OS are to handle all the hardware connected to the system, coordinate and manage use of other
resources and provide common services for computer programs. Application programs usually require an
operating system to function.

 Device driver is a computer program that operates or controls a particular type of device that is attached to a
computer. A device driver simplifies programming by acting as translator between a hardware device and the
applications that use it.

2) Application software: It is a type of computer software that causes a computer to perform useful tasks that a
user wishes to perform. It utilizes capacities of a computer directly to a dedicated task. Application software
includes word processing software, database software, multimedia software, graphics software etc. It can be
categorized as:

 Tailored (custom) software is software that is specially designed for some specific organizations or other user.
It is developed for a single user that accommodates the particular preferences and expectations of the user.

 Packaged (off the shelf) software is software which performs some specific function or calculation which is
useful for more than one computer user and is sufficiently well documented to be used without modifications on
a defined configuration of some computer system.

1.3 Generation of Programming Language

Programming languages have been developed over the year in a phased manner. Each phase of developed has
made the programming language more user-friendly, easier to use and more powerful. Each phase of improved
made in the development of the programming languages can be referred to as a generation. The programming
language in terms of their performance reliability and robustness can be grouped into five different generations,

1. First Generation Language (Machine language)

The first generation programming language is also called low-level programming language because they were
used to program the computer system at a very low level of abstraction. i.e. at the machine level. The machine

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 6


language also referred to as the native language of the computer system is the first generation programming
language. In the machine language, a programmer only deals with a binary number.

Advantages of first generation language

 They are translation free and can be directly executed by the computers.
 The programs written in these languages are executed very speedily and efficiently by the CPU of the
computer system.
 The programs written in these languages utilize the memory in an efficient manner because it is possible
to keep track of each bit of data.

2. Second Generation language (Assembly Language)

The second generation programming language also belongs to the category of low-level- programming language.
The second generation language comprises assembly languages that use the concept of mnemonics for the
writing program. In the assembly language, symbolic names are used to represent the opcode and the operand
part of the instruction.

Advantages of second generation language

 It is easy to develop understand and modify the program developed in these languages are compared to
those developed in the first generation programming language.
 The programs written in these languages are less prone to errors and therefore can be maintained with
a great case.

3. Third Generation languages (High-Level Languages)

The third generation programming languages were designed to overcome the various limitations of the first and
second generation programming languages. The languages of the third and later generation are considered as a
high-level language because they enable the programmer to concentrate only on the logic of the programs
without considering the internal architecture of the computer system.

Advantages of third generation programming language

It is easy to develop, learn and understand the program. As the program written in these languages are less prone
to errors they are easy to maintain. The program written in these languages can be developed in very less time
as compared to the first and second generation language.

Examples: FORTRAN, ALGOL, COBOL, C++, C

4. Fourth generation language (Very High-level Languages)

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 7


The languages of this generation were considered as very high-level programming languages required a lot of
time and effort that affected the productivity of a programmer. The fourth generation programming languages
were designed and developed to reduce the time, cost and effort needed to develop different types of software
applications.

Advantages of fourth generation languages

 These programming languages allow the efficient use of data by implementing the various database.
 They require less time, cost and effort to develop different types of software applications.
 The program developed in these languages are highly portable as compared to the programs developed
in the languages of other generation. Examples: SOL, CSS, coldfusion

5. Fifth generation language (Artificial Intelligence Language)

The programming languages of this generation mainly focus on constraint programming. The major fields in
which the fifth generation programming language are employed are Artificial Intelligence and Artificial Neural
Networks.

Advantages of fifth generation languages

 These languages can be used to query the database in a fast and efficient manner.
 In this generation of language, the user can communicate with the computer system in a simple and an
easy manner.Examples: mercury, prolog, OPS5

1.4 Structured Programming Language

Structured programming (sometimes known as modular programming) is a programming paradigm that


facilitates the creation of programs with readable code and reusable components. All modern programming
languages support structured programming, but the mechanisms of support, like the syntax of the programming
languages, varies.

Where modules or elements of code can be reused from a library, it may also be possible to build structured code
using modules written in different languages, as long as they can obey a common module interface or application
program interface (API) specification. However, when modules are reused, it's possible to compromise data
security and governance, so it's important to define and enforce a privacy policy controlling the use of modules
that bring with them implicit data access rights.

Structured programming encourages dividing an application program into a hierarchy of modules or autonomous
elements, which may, in turn, contain other such elements. Within each element, code may be further structured
using blocks of related logic designed to improve readability and maintainability. These may include case, which

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 8


tests a variable against a set of values; Repeat, while and for, which construct loops that continue until a condition
is met. In all structured programming languages, an unconditional transfer of control, or goto statement, is
deprecated and sometimes not even available.

In other words, Structured programming language - In this type


of language, large programs are divided into smaller programs
called functions. The main focus is on functions and processes
that work on data. Data runs freely around the system from one
function to another. The program structure follows the "top-
down approach

Advantages of Structured Programming Language


 Structured programming is user-friendly and easy to understand.
 In this programming, programs are easier to read and learn.
 It avoids the increased possibility of data corruption.
 The main advantage of structured programming is reduced complexity.
 Application programs are less likely to contain logic errors, increase the productivity of application
program development, Errors are more easily found, it is easier to maintain.
 It is independent of the machine on which it is used, i.e. programs developed in high-level languages
can be run on any computer.

Disadvantages of Structured Programming Language


 Same code repetition, the code that is written may appear in different parts of the program. It can be
vulnerable to various problems because of its location. Programs have variables, which means that
they can take on different values at different parts of the program.
 Lack of encapsulation, Lack of information hiding
 Its lack of availability in structured programming means that programs will be longer.
 Information hiding involves isolating design decisions in a computer program that has the greatest
chance to change. This protects other parts of the program from modifications if the design decision
is changed.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 9


Unit II Problem Solving Using Computer

Problem Solving is the sequential process of analyzing information related to a given situation and generating
appropriate response options. Solving problems is the core of computer science. Programmers must first
understand how a human solves a problem, then understand how to translate this "algorithm" into something a
computer can do, and finally how to "write" the specific syntax (required by a computer) to get the job done. It
is sometimes the case that a machine will solve a problem in a completely different way than a human. Problem
solving should clearly specify its objectives, output requirements, input requirements, processing requirements,
and evaluating feasibility.

Problem Solving Using Computer


In computer science and in the part of artificial intelligence that deals with algorithms, problem solving includes
techniques of algorithms, heuristics (trial and error or rules loosely defined) and root cause analysis. The amount
of resources (e.g. time, memory, energy) required to solve problems is described by computational complexity
theory. In more general terms, problem solving is part of a larger process that encompasses problem
determination, de-duplication, analysis, diagnosis, repair, and other steps.
The following are six steps that must be followed to solve a problem using computer

1. Problem Analysis 2. Program Design - Algorithm, Flowchart and Pseudo code 3. Coding 4. Compilation and
Execution 5. Debugging and Testing 6. Program Documentation

2.1 Problem Analysis (Understanding of the problem, feasibility and requirement analysis)

Problem Analysis investigates a situation/problem in order to allow the programmer to understand more fully
the problem, in order to recommend practical solutions for solving it. Thus, the problem analysis would report
that the lighting was not the cause of the problem, saving the company time and money. The following are steps
involves in problem analysis.

a. Understand the problem b. Break the problem c. Define problem goals


d. Decide how to measure progress towards goals.

a. Understand the Problem: We must understand the issue, problem or symptom we are experiencing before
we can realistically try to figure out what to do about it. As a first step towards self – help, take steps to understand
jthe nature of our problem.

b. Break the Problem down into Small Parts: Even when we understand what is our problem is, it may be too
big and too well established for us to figure out how to fix all at once. Instead of trying to tackle the entire

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 10


problem all at once, break it down into manageable parts. Then, make a plan for how we will fix or address each
part separately.

c. Define Problem Goals: For each of our small manageable problem parts, figure out what our goals are; where
we want to end up at the end of the self-help process for each part of our problem. If we don't know what we are
working towards, we will never know when we've arrived there.

d Decide How to Measure Progress towards Goals: Find ways to measure progress our make towards
accomplishing each of our problem goals, so that we will always know:
a. What our problem starting point looked like
b. How far we've come towards meeting our goals at any given moment, and
c. How we'll know when we’ve met our goals and are done.

2.2 Design (Algorithm and Flowchart)

Algorithm:
 Step-by-step method to solve the particular problem is called algorithm, in other words, an algorithm is
a procedure for solving problems. Algorithm can be defined as: “A sequence of activities to be processed
for getting desired output from a given input”.
 To be an algorithm, a set of rules must be unambiguous and have a clear stopping point. There may be
more than one way to solve a problem, so there may be more than one algorithm for a problem.
 Algorithms are written in simple English language.

Examples of Algorithm
Problem 1: Find the area of a Circle of radius r
Step1: Read\input the Radius r of the Circle
Step2: Area ←PI*r*r // calculation of area
Step3: Print Area

Problem 2: Find the largest value of any three numbers.


Step1: Start
Step2: Read/input A, B and C
Step3: If (A>=B) and (A>=C) then Max=A
Step4: If (B>=A) and (B>=C) then Max=B
Step5: If (C>=A) and (C>=B) then Max=C
Step6: Print Max

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 11


Problem 3: An algorithm to calculate even numbers between 0 and 99
1. Start
2. I ← 0
3. Write I in standard output
4. I ← I+2
5. If (I <=98) then go to line 3
6. End

Properties of algorithm
a) Finiteness: An algorithm must always terminate after a finite number of steps
b) Definiteness: Each step of an algorithm must be precisely defined without ambiguity
c) Input: Any operation you perform need some beginning value/quantities associated with different activities
in the operation. So the value/quantities are given to the algorithm before it begin or during runtime
d) Output: Each algorithm must produce one or more output.
e) Effectiveness: It should always provide effective result among various alternatives of solving problem.

Flowchart:
A flowchart can also be defined as a diagrammatic representation of an algorithm, a step-by-step approach to
solving a task. It is a type of diagram that represents a workflow or process .A flowchart, will describe the
operations (and in what sequence) are required to solve a given problem. You can see a flow chart as a blueprint
of a design you have made for solving a problem.
Flowchart Symbols
There are 6 basic symbols commonly used in flowchart: Terminal, Process, input/output, Decision, Connector
and Predefined Process. This is not a complete list of all the possible flowcharting symbols, it is the ones used
most often in the designing the flowchart.
Advantages of Using Flowcharts:
The benefits of flowcharts are as follows:
 Communication: Flowcharts are better way of communicating the logic of a system to all concerned.
 Effective analysis: With the help of flowchart, problem can be analyzed in more effective way.
 Proper documentation: Program flowcharts serve as a good program documentation, which is needed
for various purposes.
 Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program
development phase.
 Proper Debugging: The flowchart helps in debugging process.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 12


 Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of
flowchart. It helps the programmer to put efforts more efficiently on that part.

Limitations of Using Flowcharts:


Although a flowchart is a very useful tool, there are a few limitations in using flowcharts which are listed below:
 Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes
complex and clumsy.
 Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 13


Problem 1: Find the area of a circle of radius r Problem 2: To find the greater number
between two numbers

2.3 Coding (Compilation and Execution)

Coding: Coding is the real job of programmer. The algorithm to solve a problem which is described by pseudo-
code or flow chart is converted into actual programming language code. The code written by programmer by
using any programming language like C is called the source code or source program.

Compilation and Execution:

Compilation and execution: The source code written in any programming language is not directly executed by
the computer. It should be translated into to the machine readable format i.e. actual machine language. The
process of translation of source code into the target code is called the compilation. Each programming language
has its own compiler program that translates the source code into its target code. The converted program in actual
machine language is then executed by the computer which is known as program execution.

2.4 Testing and Debugging

Program testing and debugging refer to the tasks of detecting and removing errors in a program, so that the
program produces the desired results on all occasions.

Types of Errors

1) Syntax errors: Any violation of rules of the language results in syntax errors.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 14


2) Run time errors

Errors such as a mismatch of data types or referencing an out of range array element go undetected by the
compiler. A program with these mistakes will run, but produce erroneous results

3) Logical errors

These errors are primarily due to a poor understanding of the problem, incorrect translation of the algorithm into
the program and a lack of clarity of hierarchy of operators.

4) Latent errors

It is a ‘hidden’ error that shows up only when a particular set of data is used. For example, consider the following
statement: ratio = (x+y)/(p-q);n error occurs only when p and q are equal. An error of this kind can be detected
only by using all possible combinations of test data.

Testing

Testing is the process of reviewing and executing a program with the intent of detecting errors. It involves any
activity aimed at evaluating attribute or capability of a program or system and determining that it meets its
required result.

Testing process may include the following two stages:


a) Human testing. b) Computer-based testing.

a) Human testing is an effective error detection process and is done before the computer based testing begins.
Human testing methods include code inspection by the programmer, code inspection by a test group, and a
review by a peer group. The test is carried out statement by statement and is analyzed with respect to a checklist
of common programming errors. In addition to finding the errors, the programming style and choice of algorithm
are also reviewed.

b) Computer based testing involves two stages, namely compiler testing and run time testing. Computer based
testing involves two stages, namely compiler testing and run time testing. Different type of debugging techniques
are used to find the syntax error, If there is no syntax error, we need to find logical and runtime errors.

Debugging: Debugging is a methodical process of finding and reducing the number of bugs (or defects) in a
computer program, thus making it behave as originally expected. There are two main types of errors that need
debugging:

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 15


I .Compile-time: These occur due to misuse of language constructs, such as syntax errors. Normally fairly easy
to find by using compiler tools and warnings to fix reported problems.
II .Run-time: These are much harder to figure out, as they cause the program to generate incorrect output (or
“crash”) during execution.
Types of debugging techniques are as follows.

Isolating Errors: Error isolations is used for locating an errors resulting in a diagnostic message. Temporary
error detection can be accomplished by surrounding the instructions with comment markers(/* */).We can put
different printf statements in different blocks to check whether that part of program is executing or not.
Tracing
In this technique printf statement is used to print the values of some important variables. By observing these
values we can check program is running correctly or not. From this way also we can trace the errors
Watch values
A valid expression result value or a value which is assigned to a variable in the watch window is called watch
value. Thus we can see changes in watch values as they occur ,in response to program logic,by determining these
values we can detect where the program begin to generate an incorrect or unexpected value.In Turbo C++ IDE
to define the watch values go through following steps
DebugWatch Add watchSpecify variables and expressions to watch the value its valueOK
Breakpoints
A point in the processing of a program that the programmer wants to observe more closely by stopping the
program and examining the contents of variables, buffers and memory. Part of the debugging function, lines of
code are marked as breakpoints. When those instructions are about to be executed, the program stops, and control
is passed to the programmer. After inspection, the programmer can step through the program one line at a time
or cause the program to continue running either to the end, to the next breakpoint or until it crashes, whichever
comes first.In Turbo C++ we can set breakpoints by following steps
DebugAddBreakpointsProvide the requested information in dialogue box Or Select Particular line within
program  Press function key F5 .To disable the breakpoints again press function key F5.
Stepping
Program animation or stepping refers to the debugging method of executing code one instruction or line at a
time. The programmer may examine the state of the program, machine, and related data before and after
execution of a particular line of code. This allows the programmer to evaluate the effects of each statement or
instruction in isolation, and thereby gain insight into the behavior (or misbehavior) of the executing program.
Nearly all modern IDEs and debuggers support this mode of execution.In Turbo C++ Stepping can be done by
pressing function key F7.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 16


2.5 Implementation, Evaluation and Maintenance of Computer Program

Implementation is a process of ensuring that the computer programs are operational whereas maintenance means
restoring something to its original conditions of program. And evaluation is a systematic method for collecting,
analyzing, and using data to examine the effectiveness and efficiency of programs and, as importantly, to
contribute to continuous program improvement. This step is precisely more important for continuous
improvement of computer programs.

2.6 Programming Documentation

From the start of the problem solving to the end of the implementation of the program, all the tasks should be
documented i.e. kept for future reference. It is also the important part of the problem solving or program
development. Documentation may be of two types

 Technical Documentation known as programmer's documentations which includes the problem


analysis to implementation details for that program. It is needed for future reference for any
modification, update of the program.

 User manual is the documentation prepared for the end-user of the program that guides the user how
to operate the program.

Program documentation may also refer to the detail that describes a program. Some details may be built may be
built-in as an integral part of the program. These are known as internal documentation. Two important aspect of
internal documentation are: selection of meaningful variable names and the use of comments. Selection of
meaning names is crucial for understanding the problem. For Example: Area=Breadth*Length; is more
meaningful than A=B*L and comments are used to describe actions part and identification in a program

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 17


Unit III The C Language and its Basic Constructs

3.1 History of C Language

The base or father of programming languages is ‘ALGOL.’ ‘ALGOL’ introduced the concept of structured
programming to the developer community. In 1967, a new computer programming language was announced
called as BCPL was designed and developed by Martin Richards, especially for writing system software.. Just
after three years, in 1970 a new programming language called ‘B’ was introduced by Ken Thompson that
contained multiple features of ‘BCPL.’

In 1972, a great computer scientist Dennis Ritchie created a new programming language called ‘C’ at the Bell
Laboratories. It was created from ‘ALGOL’, ‘BCPL’ and ‘B’ programming languages. ‘C’ programming
language contains all the features of these languages and many more additional concepts that make it unique
from other languages.

‘C’ is a powerful programming language which is strongly associated with the UNIX operating system. Even
most of the UNIX operating system is coded in ‘C’. Initially ‘C’ programming was limited to the UNIX operating
system, but as it started spreading around the world, it became commercial, and many compilers were released
for cross-platform systems.

Today ‘C’ runs under a variety of operating systems and hardware platforms. As it started evolving many
different versions of the language were released To assure that ‘C’ language will remain standard, American
National Standards Institute (ANSI) defined a commercial standard for ‘C’ language in 1989. Later, it was
approved by the International Standards Organization (ISO) in 1990. ‘C’ programming language is also called
as ‘ANSI C’.

1) ALGO 1960 2) BCPL1967 3) B1970 4) C1972 5)K&R C 1978 6) ANSI C1989 7)ANSI/ISO
C 1990

Languages such as C++/Java are developed from ‘C’. These languages are widely used in various technologies.
Thus, ‘C’ forms a base for many other languages that are currently in use.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 18


3.2 Features of C

1. Simple
C language is simple and easy to learn. The syntax of C is simple and gives flexibility to the programmer with
its wide variety of in-built functions and data types.

2. Portable
C is a machine independent language, which means a C program written one machine can run on another
machine without requiring a code change.

3. Fast
C is a compiler based language. C is power packed with several features but it is not bloated like some other
programming languages, it supports only useful features which makes the compilation of C file fast.

4. Extensible
C program supports code modifications and addition of new code to the already existing programs, this makes
C language extensible. It becomes easier to add new functionalities to the existing C programs.

5. Rich libraries:
C libraries are full of useful in-built functions. These functions can be used frequently to perform some
repeated tasks. As a C programmer, you won’t need to write same code again and again for some trivial
repeated tasks, rather you can use in-built functions to perform the task.

6. Dynamic memory allocation


Dynamic memory allocation means, optimizing and allocating the memory during runtime. C language
supports dynamic memory allocation, which supports function like free() to free the un-utilized memory space
and other memory management functions such as malloc(), calloc() etc.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 19


7. Reusability
Function is a block of code that is used to perform a specific task. Along with the in-built predefined functions,
C language allows you to create you own functions that you can create for a reoccurring tasks. This improves
the reusability of the code and avoids the unnecessary writing of the same code again and again.

8. Mid-Level programming language


C language provides the benefits of high level and low-level languages both. C allows manipulation of
hardware just like low level language and allows high user end functionalities like high-level languages.

9. Supports pointers
C language supports pointers. The pointer in C allows you to directly interact with the memory.

10. Recursion
C supports recursion. Recursion means a function calls itself. Recursion provides the features of code
reusability and backtracking.

3.3 The C Character Set


A character set in C Programming Language is set of all valid character which is used to form a words, numbers
and expression’s in source program. The character set is fundamental raw material of any language and they are
used to represent information like natural language, computer language will also have well defined Character set
that is useful to build the programs.

Type of C Character Set


There are four type of character set in C programming.
a) Alphabets
b) Digit
c) Special Character
d) White space

a) Alphabets: It has a two case. Upper case A-Z Lower case a-z.
b) Digit: C programming support 10 digit which are used to construct numerical value. Digit 0-9
c) Special character C programming supports set of special symbols that include symbols to perform
mathematical operation, check condition and other special symbol.
d) Special character %,&,*,etc. are special characters few are listed below with their ASCII Code.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 20


Special ASCII Special ASCII
Character Code Character Code
~ 126 – 45
! 33 _ 95
@ 64 + 43
# 35 = 61
$ 36 { 123
% 37 } 125
& 38 | 124
* 42 \ 92
( 40 ; 58
) 41 : 59
‘ 39 / 47
“ 34 ? 63
< 60 > 62

e) White space
In computer programming, white space is a character that represent vertical space in typography. White
space \b,\v,\? and so on. Below table signifies white space along with their meaning.

White Space Meaning White Space Meaning

\b blank space \\ back slash

\t horizontal tab \’ single quote

\v vertical tab \” double quote

\r carriage return \? Question mark

\f form feed \0 Null

\n new line \a alarm (bell)

3.4 Keywords and Identifier

Keywords:
Every programming language has some reserved words that are used internally and have some meaning for the
language, such words are called Reserved Keywords or just Keywords.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 21


The meaning of C language keywords has already been described in the C compiler, which means the C compiler
knows what these words mean and what it has to do with them. These meanings cannot be changed. Hence,
keywords cannot be used as a variable name or a function name (in short as an Identifier) because that would try
to change the existing meaning of the keyword, which is not allowed. There are a total of 32 keywords in the C
language.

auto double int struct


break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned

Note:
 A keyword cannot be used as an Identifier .Keywords must be written in lower case.
 Keywords hold special meaning for the C compiler, so respect that, otherwise you will get a compile-
time error
Identifier
Identifier refers to name given to entities such as variables, functions, structures etc. Identifiers must be
unique. They are created to give a unique name to an entity to identify it during the execution of the
program. For example:
int money; double accountBalance;
Here, money and accountBalance are identifiers.

Rules for defining an Identifier:


1) A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
2) The first letter of an identifier should be either a letter or an underscore.
3) You cannot use keywords like int, while etc. as identifiers.
4) There is no rule on how long an identifier can be. However, you may run into problems in some compilers if
the identifier is longer than 31 characters.
You can choose any name as an identifier if you follow the above rule, however, give meaningful names to
identifiers that make sense.

3.5 Data Types

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 22


Data types in c refer to an extensive system used for declaring variables or functions of different types. The
type of a variable determines how much space it occupies in storage and how the bit pattern stored is
interpreted.
The types in C can be classified as follows
S..No. Types & Description
1 Basic Types
They are arithmetic types and are further classified into: (a) integer types and (b) floating-point and double types. (c)
Character Type
2 Enumerated types
They are again arithmetic types and they are used to define variables that can only assign certain discrete integer
values throughout the program.
3 The type void
The type specifier void indicates that no value is available.
4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types

From the different types of data types here we will be focusing on only basic /fundamental data types.
Integer Types
The following table provides the details of standard integer types with their storage sizes and value ranges.

Type Storage size Value range


Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
Int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
Long 8 bytes or (4bytes for 32 bit OS) -9223372036854775808 to 9223372036854775807

unsigned long 8 bytes 0 to 18446744073709551615

To get the exact size of a type or a variable on a particular platform, we can use the sizeof operator. The
expressions sizeof(type) yields the storage size of the object or type in byte.

Floating-Point Types & Double Type

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 23


The float data type is 4 bytes or 32 bits in size. It is a single-precision data type that is used to hold decimal
values. It is used for storing large values.The double data type is 8 bytes or 64 bits in size. It can store values
that are double the size of what a float data type can store, hence it is called double. The following table provide
the details of standard floating-point and double types with storage sizes and value ranges and their precision −

Type Storage size Value range


Float 4 byte 1.2E-38 to 3.4E+38
Double 8 byte 2.3E-308 to 1.7E+308
long double 10 byte 3.4E-4932 to 1.1E+4932

Character type The char data type is 1 byte in size or 8 bits. This is mostly the same and is not affected by the
processor or the compiler used.

Type Storage Size Value Range


Char 1 byte -127 to 127
unsigned char 1 byte 0 to 255
signed char 1 byte -127 to 127

3.6 Constants, Variables and their declarations

Variables

 A meaningful name given to a data storage location in the computer memory is known as a Variable.
 When a variable is used it actually refers to a address of the memory where the data is stored.
 A variable name can comprise of letters, digits and underscore characters.
 The first character has to be an alphabet.
 There should be no commas or blank spaces between the variable names.

Variable declaration

All the variables that we wish to use in the program need to be declared.
Syntax:
data-type variable-name;
In the above syntax a data-type is declared along with a variable name.
Meaningful names should be given to the variables.
Example: A simple variable declaration.
int emp_id;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 24


float salary;
Variables can be declared anywhere in the program according to their needs.
Multiple variables can also be declared in one statement but the data-type has to be the same.

Example: Multiple variable declaration


float salary, bonus;

Generally variables are declared in three places as follows:


1. Local variable is declared inside the function.
2. Formal parameters are declared in the definition of the function parameters.
3. Global variables are declared outside all the functions.

Constants

The identifiers whose value does not/ cannot change are known as Constants. Variables can change their
values but constants will never change their value.

Types of constants

There are three types of constants:


1. Integer constants: An integer quantity which contains a sequence of digits is known as an Integer
constant. There are no decimal points. They can be either positive or negative. Blanks and commas are not
allowed. Its value must lie within the range of its values.

Example: A decimal integer which consists of any combinations of the digits from 0 to 9.
0 5250 9990

Example: An octal integer constant which is a combination of digits from 0 through 7. Its first digit should
always be a 0.
0 03 0567

Example: Hexadecimal integer begin with 0x or 0X followed by the combination of the digits from 0 through 9
and a through f.
0x 0x4 0xcdf

Certain suffixes are given to the constants.

The suffixes are given for the following types.


Long – I or L
Unsigned long – ul or UL.

Example:

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 25


6000U unsigned (decimal)
0x3000U unsigned (hexadecimal)
3421ul unsigned long(decimal)
0325U unsigned (octal)

2. Floating point constants

These type of constants contain a decimal point or an exponent. They can be either negative or positive.
Commas or blanks are not allowed within a real constant.

Example: Floating point constants


+3.2f-4 -0.3e-3 325.0 -33.75

Unlike the integer constants they too have a suffix for the following type:

Float – f or F
Long double – I or L

3. Character constant

They consist of a single character which are enclosed in single quotes.


Example: Character constant
'b' '@' '5'
The characters are stored by using the machines character set using the ASCII code.

Constants declaration
A constant can be declared by using the const keyword and assigning it a value.
Example: Simple constant
const float pi = 3.14;
The const keyword tells us that the value of pi can never be changed.
Other way of declaring the constant is by using the pre-processor command define. #define can be placed
anywhere in the program

Example: declaring a constant by using a pre-processor


#define pi 3.14159

3.7 Formatted Input / Output Functions

Input means to provide the program with some data to be used in it and Output means to display data on the
screen or write the data to a printer or a file. The C programming language provides standard library functions
to read any given input and display output on the console. The C language is accompanied by a collection of
library functions which includes a number of input/output functions. These functions are used to permit the
transfer of information between the computer and the standard input/output device. Input /Output functions are

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 26


also included in the user program by using the header file <stdio.h> which stands for standard input-output
header.
(1) Formatted I/O functions

These functions are called formatted I/O functions because we can use format specifiers in these functions and
hence, we can format these functions according to our needs. Few of format specifiers are listed below. Though
we have different formatted i/o available in c programming here we will be using only two functions (i) printf()
(ii) scanf() as formatted i/o .

S NO. Format Type Description


Specifier
1 %d int/signed int used for I/O signed integer value
2 %c char Used for I/O character value
3 %f float Used for I/O decimal floating-p
4 %s string Used for I/O string/group of
characters
5 %ld long int Used for I/O long signed integer value
6 %u unsigned int Used for I/O unsigned integer value
7 %i unsigned int used for the I/O integer value
8 %lf double Used for I/O fractional or floating data
9 %n prints prints nothing

(i) printf():-

The printf() function is used for output formatted as the standard output according to a format specification. The
format specification string and the output data are the parameters of the printf() function.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 27


Syntax 1: Syntax 2:

printf(format_specifiers, data1, data2,…..... ); To display any string or a message

C program to implement printf function printf(“String to display”);

#include <stdio.h>
#include <stdio.h>
int main() int main()
{
{ // Displays the string written
// Declaring an int type variable
int a; // inside the double quotes
// Assigning a value in a variable
printf("Welcome to C-Programming\n");
a = 20;
// Printing the value of a variable return 0; }
printf("%d", a);
return 0;
}

Output: 20 Output: Welcome to C-Programming

(ii) scanf()

The scanf() function is used for inputs formatted from standard inputs and provides numerous conversion options
for the printf() function.

scanf(format_specifiers, &data1, &data2,……); // & is address operator

The scanf() function reads and converts the characters from the standard input according to the format
specification string and stores the input in the memory slots represented by the other arguments.
#include <stdio.h>
int main()
{
int num1;
// Printing a message on the output screen
printf("Enter a integer number: ");
// Taking an integer value

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 28


// from keyboard
scanf("%d", &num1);
// Displaying the entered value
printf("You have entered %d", num1);
return 0;
}

(2) Unformatted I/O Functions

Unformatted input and output functions are only work with character data type. Unformatted input and output
functions do not require any format specifiers. Because they only work with character data type.

Character I/O Functions

(i) getchar() Function

The getchar() function reads character type data form the input. The getchar() function reads one character at a
time till the user presses the enter key.

#include <stdio.h> //header file section


#include <conio.h>
int main()
{
char c;
printf("Enter a character : ");
c = getchar();
printf("\nEntered character : %c ", c);
return 0;
}
Note: Here, getchar() reads the input from the user and display back to the user.

Output

Enter a character : y
Entered character : y

(ii) getch() Function

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 29


The getch() function reads the alphanumeric character input from the user. But, that the entered character will
not be displayed. This function is declared in conio.h(header file). getch() is also used for hold the screen.

// C program to implement
// getch() function
#include <conio.h>
#include <stdio.h>
int main()
{
printf("Enter any character: ");

// Reads a character but


// not displays
getch();
return 0;
}

Output:
Enter any character:

(iii) getche() Function

The getche() function reads the alphanumeric character from the user input. Here, character you entered will
be echoed to the user until he/she presses any key.

#include <stdio.h> //header file section


#include <conio.h>
int main()
{
printf("\nHello, press any alphanumeric character or symbol to exit \n ");
getche();
return 0;
}

Output

Hello, press any alphanumeric character or symbol to exit

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 30


K

(iv) putchar() Function


putchar() function prints only one character at a time.
#include <stdio.h> //header file section
#include <conio.h>
int main()
{
char c = 'K';
putchar(c);
return 0;
}
Output:K

(v) putch() Function

The putch() function prints any alphanumeric character


#include <stdio.h> //header file section
#include <conio.h>
int main()
{
char c;

printf("Press any key to continue\n ");


c = getch();
printf("input : ");
putch(c);
return 0;
}
Output: Press any key to continue
input: d

Note:

The getch() function will not echo a character. The putch() function displays the input you pressed

String IO Functions

(i) gets() Function

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 31


The gets() function can read a full string even blank spaces presents in a string. But, the scanf() function leave
a string after blank space space is detected. The gets() function is used to get any string from the user.

#include <stdio.h> //header file section


#include <conio.h>
int main()
{
char c[25];
printf("Enter a string : ");
gets(c);
printf("\n%s and hi\m ",c);
return 0;
}

Enter a string :Hello and hi

Note:

The gets() function reads a string from through keyboard and stores it in character array c[25]. The printf()
function displays a string on the console.

(ii) puts() Function

The puts() function prints the character array or string on the console. The puts() function is similar to printf()
function, but we cannot print other than characters using puts() function.

#include <stdio.h> //header file section


#include <conio.h>
int main()
{
char c[25];
printf("Enter your Name : ");
gets(c);
puts(c);
return 0;
}

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 32


Enter your Name: Ram
Ram

3.8 The C-Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language
is rich in built-in operators and provides the following types of operators –

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc. Operators

Arithmetic Operators

The following table shows all the arithmetic operators supported by the C language. Assume variable A holds
10 and variable B holds 20 then –

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer division. B%A=0

++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9

Relational Operators

The following table shows all the relational operators supported by C. Assume variable A holds 10 and
variable B holds 20 then −

Operator Description Example

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 33


== Checks if the values of two operands are equal or not. If yes, then the condition becomes (A == B) is not
true. true.

!= Checks if the values of two operands are equal or not. If the values are not equal, then the (A != B) is true.
condition becomes true.

> Checks if the value of left operand is greater than the value of right operand. If yes, then the (A > B) is not
condition becomes true. true.

< Checks if the value of left operand is less than the value of right operand. If yes, then the (A < B) is true.
condition becomes true.

>= Checks if the value of left operand is greater than or equal to the value of right operand. If (A >= B) is not
yes, then the condition becomes true. true.

<= Checks if the value of left operand is less than or equal to the value of right operand. If yes, (A <= B) is true.
then the condition becomes true.

Logical Operators

Following table shows all the logical operators supported by C language. Assume variable A holds 1 and
variable B holds 0, then

Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, then the (A && B) is false.
condition becomes true.

|| Called Logical OR Operator. If any of the two operands is non-zero, then the (A || B) is true.
condition becomes true.

! Called Logical NOT Operator. It is used to reverse the logical state of its operand. !(A && B) is true.
If a condition is true, then Logical NOT operator will make it false.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows −

Assume A = 60 and B = 13 in binary format, they will be as follows −


A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 34


P q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and variable 'B' holds 13, then −

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) = 12, i.e., 0000
1100

| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e., 0011
1101

^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) = 49, i.e., 0011
0001

~ (~A ) = ~(60), i.e,. -


Binary One's Complement Operator is unary and has the effect of 'flipping' bits.
0111101

<< Binary Left Shift Operator. The left operands value is moved left by the number of A << 2 = 240 i.e., 1111
bits specified by the right operand. 0000

>> Binary Right Shift Operator. The left operands value is moved right by the number of A >> 2 = 15 i.e., 0000
bits specified by the right operand. 1111

Assignment Operators
The following table lists the assignment operators supported by the C language −

Operator Description Example

= Simple assignment operator. Assigns values from right side operands to left C = A + B will assign the value
side operand of A + B to C

+= Add AND assignment operator. It adds the right operand to the left operand C += A is equivalent to C = C +
and assign the result to the left operand. A

-= Subtract AND assignment operator. It subtracts the right operand from the left C -= A is equivalent to C = C –
operand and assigns the result to the left operand. A

*= Multiply AND assignment operator. It multiplies the right operand with the C *= A is equivalent to C = C *
left operand and assigns the result to the left operand. A

/= Divide AND assignment operator. It divides the left operand with the right
C /= A is equivalent to C = C /
operand and assigns the result to the left operand.
A

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 35


%= Modulus AND assignment operator. It takes modulus using two operands and C %= A is equivalent to C = C
assigns the result to the left operand. %A

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Misc Operators ↦ sizeof & ternary

Besides the operators discussed above, there are a few other important operators including sizeof and ?
: supported by the C Language.

Operator Description Example

sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.

& Returns the address of a variable. &a; returns the actual address of the variable.

* Pointer to a variable. *a;

?: Conditional Expression. If Condition is true ? then value X : otherwise value Y

3.9 Control Structures-branching statements (if, if-else and switch statements) looping statements
(for, while and do-while)

In simple words, Control statements in C help the computer execute a certain logical statement and decide
whether to enable the control of the flow through a certain set of statements or not. Also, it is used to direct the
execution of statements under certain conditions.
Types of Control Statements in C
 Decision-making control statements.
 Conditional statements
 Goto statements in C
 Loop control statements in C
Decision-Making Control Statements Are:

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 36


 Simple if statement
 if-else statements
 Nested if-else statements
 else-if ladder

Simple if Statement
Simple if statements are carried out to perform some operation when the condition is only true. If the
condition of the if statement is true then the statements under the if block is executed else the control is
transferred to the statements outside the if block.

Syntax of the if statement is as given below:

Flow Chart:

Output:

if- else statements

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 37


In some situations, you may have to execute statements based on true or false under certain conditions,
therefore; you use if-else statements. If the condition is true, then if block will be executed otherwise
the else block is executed.

Nested if-else Statements

The nested if-else statements consist of another if or else. Therefore; if the condition of “if” is true (i.e., an outer
if) then outer if’s if block is executed which contains another if (that is inner if) and if the condition of if block
is true, statements under if block will be executed else the statements of inner if’s “else” block will be executed.
If the outer “if” condition is not true then the outer if’s “else” block is executed which consists of another if. The
outer else’s inner if the condition is true then the statement under outer else’s inner if is executed else the outer
else’s else block is executed. Syntax of the nested if-else statement is as given below:

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 38


Flowchart:

else-if Ladder Statements

The else-if ladder statements contain multiple else-if, when either of the condition is true the statements under
that particular “if” will be executed otherwise the statements under the else block will be executed.

Syntax of the else-if ladder statement is as given below:

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 39


Conditional Control Statements in C

Switch

As per the value of the switch expression, the switch statement will allow multi-way branching. Depending on
the expression, the control is transferred to that particular case label and executed the statements under it. If none

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 40


of the cases are matched with the switch expression, then the default statement is executed. The syntax of the
switch statement is as given below:

The syntax of the switch statement is as given below:

goto Statements in C

The goto statements are used to transfer the flow of control in a program, goto statement is also known as a jump
control statement because it is used to jump to the specified part of the program. The label in goto statement is
a name used to direct the branch to a specified point in the program.

Syntax of the goto statement is as given below:

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 41


#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do { When the above code is compiled and executed, it
produces the following result −
if( a == 15) {
/* skip the iteration */ value of a: 10
a = a + 1; value of a: 11
goto LOOP; value of a: 12
} value of a: 13
printf("value of a: %d\n", a); value of a: 14
value of a: 16
a++;
value of a: 17
}while( a < 20 ); value of a: 18
return 0; value of a: 19
}

Loop Control Statements in C


While Loop
A while loop is also known as an entry loop because in a while loop the condition is tested first then the
statements underbody of the while loop will be executed. If the while loop condition is false for the first time
itself then the statements under the while loop will not be executed even once.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 42


The syntax of the while loop is as given below:

Output:

do - while Loop
The do-while is also known as an exit loop because in the do-while loop, the statements will be executed first
and then the condition is checked. If the condition of the while loop is true then the body of the loop will be
executed again and again until the condition is false. Once the condition is false, the control will transfer outside
the do-while loop and execute statements followed soon after the do-while loop. The syntax of the do-while loop
is as given below:

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 43


Output:

for Loop
The for loop is also known as a pre-test loop. From the following syntax, expression1 is an initialization,
expression2 is the conditional expression and expression3 is an updation. The variables can be initialized in for
the statement itself.
The syntax of the do-while loop is as given below:

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 44


In the for loop, expression1 is used to initialize the variable, expression2 is evaluated and if the condition is true,
then the body of for loop will be executed and then the statements under expression3 will be executed. This
process is repeated as long as the for loop condition is true, once the condition is false control will return to the
statements following the for loop and execute those statements

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 45


Unit IV Array and Structures in C

4.1 Arrays (one dimensional and multi-dimensional arrays)

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

The array contains the following properties.


 Each element of an array is of same data type and carries the same size.
 Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest
memory location.
 Elements of the array can be randomly accessed since we can calculate the address of each element of the array
with the given base address and the size of the data element.

Advantages of Array

1) Code Optimization: Less code to the access the data.

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

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

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

Disadvantages of Array

1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit.

In C, there are three types of array namely, One Dimension Array, Two Dimensional Array and Multi-
Dimensional Array.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 46


1. One- Dimensional Array

A one-dimensional array has one subscript. One Dimensional (1D) array is an array which is represented either
in one row or in one column. .In other words, it can be represented as in a single dimension-width or height as
shown in the below figure:

2. Two Dimensional Array

Two Dimensional (2D) array is a fixed-length, homogeneous data type, row and column-based data structure
which is used to store similar data type element in a row and column-based structure. A two-dimensional array
is referred to as a matrix or a table. A matrix has two subscripts, one denotes the row and another denotes the
column. In other words, a two-dimensional array is an array of a one-dimensional array.

The general syntax for declaration of a 2D array is given below:

data_type array_name[row] [column];


where data_type specifies the data type of the array. array_name specifies the name of the array, row specifies
the number of rows in the array and column specifies the number of columns in the array.The total number of
elements that can be stored in a two array can be calculated by multiplying the size of all the dimensions.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 47


3. Multi-Dimensional Array
An array having more than one dimension is called multidimensional array in C language. A two-
dimensional array is the simplest form of a multidimensional array. By placing n number Of brackets [ ]
we can declare n-dimensional array where n is dimension number.

In general, an n-dimensional array declaration is as shown below:


<data_type> array_name[d1][d2]…..[dn]
For example,
int a[5][5][5] Three Dimensional Array.
int a[2][5][4][4] Four-Dimensional Array.

A total number of elements that can be stored in a multidimensional array can be calculated by multiplying
the size of all the dimensions.The three-dimensional array is an array or collection of 2D arrays. Below
figure shows visualization of a 3D array having 3 tables and each table having 4rows and 2 columns.

4.2 Initializations of arrays and accessing the elements of arrays

One Dimensional

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 48


Declaration of Array

We can declare an array in the c language in the following way.

data_type array_name[array_size];

Now, let us see the example to declare the array.

int marks[5]; Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Initialization of Array

The simplest way to initialize an array is by using the index of each element. We can initialize each element
of the array by using the index. Consider the following example. marks[0]=80;//initialization of array
marks[1]=60; marks[2]=70; marks[3]=85; marks[4]=75;

Syntax: Data-type array-name [size] = {value1, value2, value3,…….value n}

Example
#include<stdio.h> Output
int main(){
80
int i=0;
60
int marks[5];//declaration of array
70
marks[0]=80;//initialization of array
85
marks[1]=60;
75
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}return 0;}

Accessing Array Elements

Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of array
minus 1.We can access the elements of array by giving the name and proper subscript inside the bracket [].

Eg.float marks[5]={90,22,55,26,56},where

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 49


1000 1004 1008 1012 1016  address

90 22 55 26 56
marks[0] marks[1] marks[2] marks[3] marks[4] element

marks[0] is 90 which is stored in address 1000 respectively.

Example

#include <stdio.h>
int main()
{ Output:

int arr[5]; 5 -10 2 5


arr[0] = 5;
arr[1] = -10;
arr[2] = 2;
arr[3] = arr[0];
printf("%d %d %d %d", arr[0], arr[1], arr[2], arr[3]);
return 0;
}
Programs for sorting an array
#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp; } } }
printf("Printing Sorted Element List ...\n");

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 50


for(i = 0; i<10; i++){
printf("%d\n",a[i]);
}}

Program to find the average of n numbers using arrays

#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
// adding integers entered by the user to the sum variable
sum += marks[i];
}
average = sum/n;
printf("Average = %d", average);
return 0;
}
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39

Two-dimensional Arrays

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 51


The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is, in
essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size [x][y], we would
write something as follows −

type arrayName [ x ][ y ];

Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional array
can be considered as a table which will have x number of rows and y number of columns. A two-dimensional
array a, which contains three rows and four columns can be shown as follows −

Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where 'a' is the name
of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'

Initializing Two-Dimensional Arrays


Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array
with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3}, / * initializers for row indexed by 0 */
{4, 5, 6, 7}, / * initializers for row indexed by 1 */
{8, 9, 10, 11} / * initializers for row indexed by 2 */
};

The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to the
previous example −

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements


An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column index of
the array. For example −

int val = a[2][3];

The above statement will take the 4th element from the 3rd row of the array. You can verify it in the above
figure. Let us check the following program where we have used a nested loop to handle a two-dimensional array

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 52


#include <stdio.h>
int main () {
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
} }
return 0; }

When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

As explained above, we can have arrays with any number of dimensions, although it is likely that most of the
arrays we create will be of one or two dimensions
C program to create two matrixes. Add the values of the two matrixes and store it in another
matrix. Display the new matrix
#include <stdio.h>
#include <conio.h>
void main()
{
int a[2][3],b[2][3],c[2][3],i,j;
printf("\nENTER VALUES FOR MATRIX A:\n");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\nENTER VALUES FOR MATRIX B:\n");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<2;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 53


printf("\nTHE VALUES OF MATRIX C ARE:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf("%5d",c[i][j]);
printf("\n");
}
getch();
}
Output

4.3 Character Arrays (Strings)

String is a sequence of characters that are treated as a single data item and terminated by a null
character '\0'. C language does not support strings as a data type. A string is actually a one-dimensional
array of characters in C language. These are often used to create meaningful and readable programs.

The following declaration and initialization create a string consisting of the word "Hello". To hold the null
character at the end of the array, the size of the character array containing the string is one more than the
number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization then you can write the above statement as follows −
char greeting[] = "Hello";

Following is the memory presentation of the above defined string in C/C++ −

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 54


How to take Input as string and print Output that string?
way 2:
way 1:
void main()
void main()
{
{
char name[30];
char name[30];
printf("Enter your name");
printf("Enter your name");
gets(name); //in-built function
scanf("%s", name); //format specifier
puts(name);
printf("%s", name);
} }

Difference between both ways is that 1st way use's format specifier and second way uses in-built
function.

In 1st way if you enter something like john karter it will take only john as string and anything after (space)
will be discarded. In second way if you enter any space it will be accepted. Output of second way would be
john karter. Similarity between both way is that you don't have to add '\0' character. scanf(%s ) converts
32(space) or '\n' character into '\0' and gets() converts newline character '\n' into '\0'.

List of (most frequently used) string library functions in c.

String functions examples


1) int strlen(char array):This function accepts string as parameter and return integer i.e
the length of String passed to it.
Example
#include <stdio.h>
#include <string.h>
void main(void)

char string[]="Nepal";
int len;
len=strlen(string);
printf("length of %s is %d\t", string, len);
}
Output::length of Nepal is 5.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 55


strlen() does not include '\n' in string length or else length would be 6.

2) strcpy (Destination string,Source string): This function accepts 2 strings as parameter,1st one is
destination string and 2nd is source string. This function copies source string to destination string.
Example
#include <stdio.h>
#include <string.h>
void main(void)
{
char src[]="nepal ",dest[15];
strcpy(dest,src);
printf("%s is copied to dest string\t",dest);
}
Output: nepal is copied to dest string.

3) strcat (Destination string,source string): This function accepts two strings source string is appended
to the destination string.
Example
#include <stdio.h>
#include <string.h>
void main(void)
{
char src[]="nepal",dest[]="programming";

strcat(dest,src);

printf("concatenated string is %s",dest);

Output: concatenated string is programmingnepal

4) strrev (string):This function accepts single string as parameter and reverse that string.

Example

#include <stdio.h>
#include <string.h>
void main(void)
{
char string[]="nepal";

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 56


strrev(string);
printf("reverse string is %s",string);
}
Output: reverse string is lapen.

5) int strcmp (string 1, string2):This function compares two strings passed as parameters and returns
either
+ve number,0,-ve number.
+ve value indicates string1 > string2.
0 indicates string1 and string2 are equal
-ve value indicates string1 < string2.
Example
#include <stdio.h>
#include <string.h>
void main(void)
{
char string1[]="spark",string2[]="programming";
int cmp;
cmp=strcmp(string1,string2);
if(cmp>0)
printf("%s > %s",string1,string2);
else
{
if(cmp<0)
printf("%s < %s",string1,string2);
else
printf("%s = %s",string1,string2);
}}

6) strcmpi (string 1, string2):This function is similar to strcmp().The only difference is that it ignores the
case.example SparK and spark both are same.

Example
#include <stdio.h>
#include <string.h>

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 57


void main(void)
{
char string1[]="spark",string2[]="SPArk";
int cmp;
cmp=strcmpi(string1,string2);
if(cmp>0)
printf("%s > %s",string1,string2);
else
{
if(cmp<0)
printf("%s < %s",string1,string2);
else
printf("%s = %s",string1,string2);
}
}
Output: spark = SPArk.
7) strlwr (string)::This function accepts single string that can be in any case(lower or upper).Itconverts the
string in lower case.

Example
#include <stdio.h>
#include <string.h>
void main(void)
{
char string1[]="SPArk";
strlwr(string1);
printf("%s is in lower case",string1);
}
Output: spark is in lower case.

8) strupr (string)::This function accepts single string that can be in any case(lower or upper).It converts
the string in upper case.

Example
#include <stdio.h>

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 58


#include <string.h>
void main(void)
{
char string1[]="SPArk";
strupr(string1);
printf("%s is in upper case",string1);
}
Output: SPARK is in upper case

4.4 Structure and Union

Structure

A structure is a user defined data type. We know that arrays can be used to represent a group of data items that
belong to the same type, such as int or float. However we cannot use an array if we want to represent a collection
of data items of different types using a single name. A structure is a convenient tool for handling a group of
logically related data items.

Structure is a user defined data type used to represent a group of data items of different types using a single
name. The syntax of structure declaration is

struct structure_name

type element 1;

type element 2;

……………..

type element n;

};

In structure declaration the keyword struct appears first, this followed by structure name. The member of
structure should be enclosed between a pair of braces and it defines one by one each ending with a semicolon. It
can also be array of structure. There is an enclosing brace at the end of declaration and it end with a semicolon.

We can declare structure variables as follows

struct structure_name var1,var2,…..,var n;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 59


Example:

To store the names, roll number and total mark of a student you can declare 3 variables. To store this data for
more than one student 3 separate arrays may be declared. Another choice is to make a structure. No memory is
allocated when a structure is declared. It just defines the “form” of the structure. When a variable is made then
memory is allocated. This is equivalent to saying that there's no memory for “int”, but when we declare an integer
that is int var; only then memory is allocated. The structure for the abovementioned case will look like

struct student
{
int rollno;
char name[25];
float totalmark;
};

We can now declare structure variables stud1, stud2 as follows struct student stud1, stud2; Thus, the stud1 and
stud2 are structure variables of type student. The above structure can hold information of 2 students.
It is possible to combine the declaration of structure combination with that of the structure variables, as shown
below.

struct structure_name
{
type element 1;
type element 2;
……………..
type element n;
} var1,var2,…,varn;

The following single declaration is equivalent to the two declaration presented in the previous example.

struct student

int rollno;

char name[25];

float totalmark;

} stud1, stud2;

Accessing structure Variable

The different variable types stored in a structure are called its members. The structure member can be accessed
by using a dot (.) operator, so the dot operator is known as structure member operator.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 60


Example:

In the above example stud1 is a structure variable of type student. To access the member name, we would write
stud1.name. Similarly, stud1’s rollno and stud1’s totalmark can be accessed by writing stud1.rollno and
stud1.totalmark respectively.

Initializing Structure Members


Structure members can be initialized at declaration. This much the same manner as the element of an array; the
initial value must appear in the order in which they will be assigned to their corresponding structure members,
enclosed in braces and separated by commas.

The general form is

struct structure_name var={val1,val2,val3…..};


Example:
#include <stdio.h>
#include<conio.h>
void main()
{
struct student
{
char *name;
int rollno;
float totalmark;
};
struct student stud1={"Venkat",1,98};
struct student stud3= {"Shweta",3,97};
struct student stud2={"Arpita",2,99};
clrscr();
printf(“STUDENTS DETAILS:\n”);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, stud1.rollno, stud1.name,
stud1.totalmark);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, stud2.rollno, stud2.name,
stud2.totalmark);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, stud3.rollno, stud3.name,
stud3.totalmark);
getch();
}
Output

STUDENTS DETAILS:
Roll number: 1
Name: Venkat
Total Marks:98.000000

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 61


Roll number: 2
Name: Arpita
Total Marks:99.000000
Roll number: 2
Name:Shweta
Total Marks:99.000000

Array of structures:
It is possible to store a structure has an array element. i.e., an array in which each element is a structure. Just as
arrays of any basic type of variable are allowed, so are arrays of a given type of structure. Although a structure
contains many different types, the compiler never gets to know this information because it is hidden away inside
a sealed structure capsule, so it can believe that all the elements in the array have the same type, even though
that type is itself made up of lots of different types.

The declaration statement is given below


struct struct_name
{
type element 1;
type element 2;
……………..
type element n;
}array name[size];

Example:
struct student
{
int rollno;
char name[25];
float totalmark;
} stud[100];

In this declaration stud is a 100-element array of structures. Hence, each element of stud is a separate structure
of type student. An array of structure can be assigned initial values just as any other array. So the above
structure can hold information of 100 students.

Program to demonstrate use of array of structure

#include <stdio.h>
#include <conio.h>

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 62


void main()
{
struct student
{
int rollno;
char name[25];
int totalmark;
}stud[100];
int n,i;
clrscr();
printf("Enter total number of students\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter details of %d-th student\n",i+1);
printf("Name:\n");
scanf("%s",&stud[i].name);
printf("Roll number:\n");
scanf("%d",&stud[i].rollno);
printf("Total mark:\n");
scanf("%d",&stud[i].totalmark);
}
printf("STUDENTS DETAILS:\n");
for(i=0;i<n;i++)
{
printf("\nRoll number:%d\n",stud[i].rollno);
printf("Name:%s\n",stud[i].name);
printf("Total mark:%d\n",stud[i].totalmark);
}
getch();
}
OUTPUT
Enter total number of students:
3
Enter details of 1-th student

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 63


Name:SUBAHAS
Roll number:11
Total mark:589
Enter details of 2-th student
Name:RUKSANA
Roll number:12
Total mark:594
Enter details of 3-th student
Name:SANA
Roll number:13
Total mark:595
STUDENTS DETAILS:
Roll number:11
Name: SUBAHAS
Total mark:589
Roll number:12
Name: RUKSANA
Total mark:594
Roll number:13
Name: SANA
Total mark:595

Structure as structure member (Embedded structure):


A structure inside another structure is called an embedded structure. A structure can have one or more of its
member as another structure, but a structure cannot be member to itself when a structure is used as structure
member. In such situation, the declaration of the embedded structure must appear before the declaration of the
outer structure. For example

#include <stdio.h>
#include <conio.h>
void main()
{
struct dob
{
int day;
int month;
int year;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 64


};
struct student
{
struct dob d;
int rollno;
char name[25];
int totalmark;
}stud[25];
int n,i;
clrscr();
printf("Enter total number of students");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\nEnter details of %d student",i+1);
printf("\nName:");
scanf("%s",&stud[i].name);
printf("\nRoll number:");
scanf("%d",&stud[i].rollno);
printf("\nTotal mark:");
scanf("%d",&stud[i].totalmark);
printf("\nDate of birth (Format:01 06 2010):");
scanf("%d%d%d",&stud[i].d.day,&stud[i].d.month,&stud[i].d.year);
}
printf("\nSTUDENTS DETAILS:\n");
for(i=0;i<n;i++)
{
printf("\nRoll number:%d\n",stud[i].rollno);
printf("Name:%s\n",stud[i].name);
printf("Total mark:%d\n",stud[i].totalmark);
printf("Date of birth : %d / %d / %d \n\n",
stud[i].d.day,stud[i].d.month,stud[i].d.year);
}
getch();
}
OUTPUT
Enter total number of students 2
Enter details of 1 student
Name: karthik
Roll number:12
Total mark:588
Date of birth (Format:01 06 2010):11 12 1997
Enter details of 2 student
Name: sarita
Roll number:18
Total mark:598
Date of birth (Format:01 06 2010):1 2 1997
STUDENTS DETAILS:
Roll number:12

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 65


Name: karthik
Total mark: 588
Date of birth : 11 / 12 / 1997
Roll number:18
Name: sarita
Total mark:598
Date of birth : 1 / 2 / 1997

Union: Union is a user created data type similar to structure but in this case all the members share a common
memory location. The size of the union corresponds to the length of the largest member. Since the member share
a common location they have the same starting address. The real purpose of unions is to prevent memory
fragmentation by arranging for a standard size for data in the memory. By having a standard data size we can
guarantee that any hole left when dynamically allocated memory is freed will always be reusable by another
instance of the same type of union. This is a natural strategy in system
Programming where many instances of different kinds of variables with a related purpose and stored
dynamically.
A union is declared in the same way as a structure. The syntax of union declaration is
union union_name
{
type element 1;
type element 2;
……………..
type element n;
};
This declares a type template. Variables are then declared as:
union union_name x,y,z;
For example, the following code declares a union data type called Student and a
union variable called stud:
union student
{
int rollno;
float totalmark;
};
union student stud;
It is possible to combine the declaration of union combination with that of the union
variables, as shown below.
union union_name
{

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 66


type element 1;
type element 2;
……………..
type element n;
}var1,var2,…,varn;
The following single declaration is equivalent to the two declaration presented in the
previous example.
union student
{
int rollno;
float totalmark;
}x,y,z;
The difference between structure and union is

Structure Union
We use the struct statement to define a structure. We use the union keyword to define a union.

Every member is assigned a unique memory All the data members share a memory location.
location.
Change in the value of one data member does not Change in the value of one data member affects the
affect other data members in the structure. value of other data members.
You can initialize multiple members at a time. You can initialize only the first member at once.
A structure can store multiple values of the A union stores one value at a time for all of its members
different members.
A structure’s total size is the sum of the size of A union’s total size is the size of the largest data member.
every data member.
Users can access or retrieve any member at a time. You can access or retrieve only one member at a time.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 67


Unit V Functions and Pointers in C

5.1 Functions and their importance

A function is a self-contained program segment or sub-program that performs some well-defined task. The C
program consists of one or more functions. The execution of each function begins as a sequence of function call
appears in the main () function. If a program contains only one function then it is known as the main () function.

C function contains set of instructions enclosed by “{ }” which performs specific operation in a C program.
Actually, Collection of these functions creates a C program.

Importance/ Key Benefits

 Enables reusability and reduces redundancy


 Makes a code modular
 Provides abstraction functionality
 The program becomes easy to understand and manage
 Breaks an extensive program into smaller and simpler pieces

5.2 Declaration of a function

A function declaration in C provides information to the compiler on the name and method of calling a function.
The function’s actual body can be specified independently. A function declaration has the following parts −

return_type function_name( parameter list );

For the below-defined function max(), the function declaration is as follows –

int max(int num1, int num2);

/* function returning the max between two numbers */

int max(int num1, int num2) {

/* local variable declaration */

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 68


}
Only their type is necessary when defining a function; hence, the following declaration is likewise acceptable:
int max(int, int);

5.3 Structure of function and return statement

Here is the syntax that we use to create a function in the C programming language:
return_type name_of_function(data_type parameter…){
// executable code in c
}
The return -type specifies the type of data that the function returns. A function may return any type (default: int)
of data except an array .The parameter (formal arguments) list is a comma-separated list of variable names and
their associated types. The parameters receive the values of the arguments when the function is called. A function
can be without parameters: An empty parameter list can be explicitly specified as such by placing the keyword
void inside the parentheses

return statement

The return statement is used to terminate the execution of a function and transfer program control back to the
calling function. In addition, it can specify a value to be returned by the function. The general format of the
return statement is given below.
return expr ;

where, expr is the expression whose value is returned by the function. The execution of the return statement
causes the expression expr to be to be evaluated and its value to be returned to the point from which this function
is called. The expression expr in the return statement is optional and if omitted, program control is transferred
back to the calling function without returning any value. ·
If a function does not return any value, the return statement may be omitted, in which case all the statements
within the function body are always executed before control is transferred back to the calling program. However,
we can include one or more return statements (without expr) to transfer control back to the calling function

Function returning a value


The function given below accepts two numbers of type double and returns the larger of them which is also a
value of type double.

double large(double a, double b) {

double large;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 69


if (a > b)

large = a;

else large = b;

return large;

As a function can contain several return statements, we can simplify this function by eliminating the variable
large and returning the values from both the if and else clauses as shown below

double large(double a, double b) {

if (a > b)

return a;

else return b;

5.4 Library and User-Defined functions

(a)Library functions /pre-defined functions /standard functions/Built in Functions


These functions are defined in the library of C compiler which are used frequently in the C program.

 These functions are written by designers of c compiler.


 C supports many built in functions like
 Mathematical functions
 String manipulation functions
 Input and output functions
 Memory management functions
 Error handling functions

EXAMPLE:

 pow(x,y)-computes xy
 sqrt(x)-computes square root of x
 printf()- used to print the data on the screen
 scanf()-used to read the data from keyboard.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 70


(b) User Defined Functions
 The functions written by the programmer /user to do the specific tasks are called user defined function
(UDF’s).The user can construct their own functions to perform some specific task. This type of functions
created by the user is termed as User defined functions.
Elements of User Defined Function
The Three Elements of User Defined function structure consists of:
1. Function Definition
2. Function Declaration
3. Function call
1. Function Definition:
 A program Module written to achieve a specific task is called as function definition.
 Each function definition consists of two parts:
i. Function header
ii. Function body
General syntax of function definition

i. Function header
Syntax:
datatype functionname(parameters)
It consists of three parts
a) Datatype:
The data type can be int,float,char,double,void.
This is the data type of the value that the function is expected to return to calling function

b) function name:

 The name of the function.


It should be a valid identifier.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 71


c) parameters
The parameters are list of variables enclosed within parenthesis.
The list of variables should be separated by comma.
Ex: void add( int a, int b)
 In the above example the return type of the function is void
the name of the function is add and
The parameters are 'a' and 'b' of type integer.

ii. Function body

 The function body consists of the set of instructions enclosed between { and } .

The function body consists of following three elements:


a) declaration part: variables used in function body.
b) executable part: set of Statements or instructions to do specific activity.
c) return : It is a keyword,it is used to return control back to calling function.
If a function is not returning value then statement is:
return;
If a function is returning value then statement is:
return value;

2. Function Declaration

 The process of declaring the function before they are used is called as function declaration or function
prototype.
 Function declaration Consists of the data type of function, name of the function and parameter list
ending with semicolon.

3. Function Call:

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 72


 The method of calling a function to achieve a specific task is called as function call.
 A function call is defined as function name followed by semicolon.
 A function call is nothing but invoking a function at the required place in the program to achieve a
specific task.

Ex:

void main()

{
add( ); // function call without parameter
}
Function Prototype
A function prototype is simply the declaration of a function that specifies function's name, parameters
and return type. It doesn't contain function body. A function prototype gives information to the compiler
that the function may later be used in the program.
Syntax of function prototype
returnType functionName(type1 argument1, type2 argument2, ...);

In the above example, int addNumbers(int a, int b); is the function prototype which provides the
following information to the compiler:

name of the function is addNumbers(),return type of the function is int, two arguments of type int are
passed to the function. The function prototype is not needed if the user-defined function is defined
before the main() function.

Formal Parameters and Actual Parameters


Formal Parameters:
The variables defined in the function header of function definition are called formal parameters. All the
variables should be separately declared and each declaration must be separated by commas. The formal
parameters receive the data from actual parameters
Actual Parameters:
The variables that are used when a function is invoked)in function call) are called actual parameters.
Using actual parameters, the data can be transferred from calling function.to the called function. The
corresponding formal parameters in the function definition receive them. The actual parameters and
formal parameters must match in number and type of data

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 73


Differences between Actual and Formal Parameters

5.5 Function Arguments and Return Types

1. Function with no parameters and no return values


2. Function with no parameters and return values.
3. Function with parameters and no return values
4. Function with parameters and return values

1. Function with no parameters and no return values


Function with no parameters and no return values
(void function without parameter)

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 74


In this category no data is transferred from calling function to called function, hence called function cannot
receive any values. In the above example, no arguments are passed to user defined function add( ).Hence no
parameter are defined in function header. When the control is transferred from calling function to called function
a, and b values are read, they are added, the result is printed on monitor. When return statement is executed,
control is transferred from called function/add to calling function/main.

2. Function with parameters and no return values (void function with parameter)

In this category, there is data transfer from the calling function to the called function using parameters. But there
is no data transfer from called function to the calling function. The values of actual parameters m and n are

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 75


copied into formal parameters a and b. The value of a and b are added and result stored in sum is displayed on
the screen in called function itself.

3. Function with no parameters and with return values

In this category there is no data transfer from the calling function to the called function. But, there is data
transfer from called function to the calling function. No arguments are passed to the function add( ). So, no
parameters are defined in the function header .When the function returns a value, the calling function receives
one value from the called function and assigns to variable result. The result value is printed in calling function.

4. Function with parameters and with return values

In this category, there is data transfer between the calling function and called function. When Actual parameters
values are passed, the formal parameters in called function can receive the values from the calling function.
When the add function returns a value, the calling function receives a value from the called function. The values
of actual parameters m and n are copied into formal parameters a and b. Sum is computed and returned back to
calling function which is assigned to variable result.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 76


5.6 Local and Global Variables
Local Variables

Variables that are declared inside a function or block are called local variables. They can be used only by
statements that are inside that function or block of code. Local variables are not known to functions outside their
own. The following example shows how local variables are used. Here all the variables a, b, and c are local to
main() function.

#include <stdio.h>
int main () {
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 77


Global Variables
Global variables are defined outside a function, usually on top of the program. Global variables hold their values
throughout the lifetime of your program and they can be accessed inside any of the functions defined for the
program. A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. The following program show how global variables are used
in a program.
#include <stdio.h>
/* global variable declaration */
int g;
int main () {
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
Parameter Local Global
Scope It is declared inside a function. It is declared outside the function.
Value If it is not initialized, a garbage value is If it is not initialized zero is stored as
stored default.

Lifetime It is created when the function starts It is created before the program’s global
execution and lost when the functions execution starts and lost when the
terminate. program terminates.
Data sharing Data sharing is not possible as data of the Data sharing is possible as multiple
local variable can be accessed by only functions can access the same global
one function. variable.
Parameters Parameters passing is required for local Parameters passing is not necessary for a
variables to access the value in other global variable as it is visible throughout
function the program

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 78


Modification of When the value of the local variable is When the value of the global variable is
variable value modified in one function, the changes modified in one function changes are
are not visible in another function. visible in the rest of the program.
Accessed by When the value of the global variable is You can access global variables by any
modified in one function changes are statement in the program.
visible in the rest of the program.

5.7 Calling a function-Call by Value

Call by value:

 In call by value, the values of actual parameters are copied into formal parameters.
 The formal parameters contain only a copy of the actual parameters.
 So, even if the values of the formal parameters changes in the called function, the values of the actual
parameters are not changed.
 The concept of call by value can be explained by considering the following program.

Example:

#include<stdio.h>

void swap(int a,int b);

void main()

int m,n;

printf("enter values for a and b:");


scanf("%d %d",&m,&n);

printf("the values before swapping are m=%d n=%d \n",m,n);

swap(m,n);

printf("the values after swapping are m=%d n=%d \n",m,n);

}
void swap(int a, int b)

int temp;

temp=a;

a=b;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 79


b=temp;

 Execution starts from function main( ) and we will read the values for variables m and n, assume we are
reading 10 and 20 respectively. We will print the values before swapping it will print 10 and 20.The function
swap( ) is called with actual parameters m=10 and n=20. In the function header of function swap( ), the formal
parameters a and b receive the values 10 and 20. In the function swap( ), the values of a and b are exchanged.
But, the values of actual parameters m and n in function main( ) have not been exchanged. The change is not
reflected back to calling function.

5.8 Pointers, Pointer Operators and Pointer Arithmetic

A Pointer in C language is a variable that holds a memory address. This memory address is the address of another
variable (mostly) of same data type. In simple words, if one variable stores the address of second variable then
the first variable can be said to point towards the second variable.

What is Memory Address in C?

Whenever a variable is defined in C language, a memory location is assigned for it, in which it's value gets
stored. We can check this memory address, using the & symbol. If var is the name of the variable, then &var
will give it's address. Let's write a small program to see memory address of any variable that we define in our
program.

#include<stdio.h>
void main()
{
int var = 7;
printf("Value of the variable var is: %d\n", var);
printf("Memory address of the variable var is: %x\n", &var);
}
Output

Value of the variable var is: 7


Memory address of the variable var is: bcc7a00

Also while using the scanf() function, we mention &var to take user input for any variable var.
scanf("%d", &var); This is used to store the user input value to the memory address of the variable
var.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 80


Let us assume that system has allocated memory location 80F for a variable a. int a = 10;

We can access the value 10 either by using the variable name a or by using its address 80F.

The question is how we can access a variable using it's address? Since the memory addresses are also just
numbers, they can also be assigned to some other variable. The variables which are used to hold memory
addresses are called Pointer variables. A pointer variable is therefore nothing but a variable which holds an
address of some other variable. And the value of a pointer variable gets stored in another memory location.

Following is the syntax for declaring a variable as a pointer:

type *name;
example

int *ptr; //pointer to int

float *ptr; //pointer to float

char *ptr; //pointer to char


Here, type is the data type of the pointer, and the name is the name of the pointer variable. And the * operator
with the name, informs the compiler that the variable is a pointer. The data type of the pointer variable should
be the same as of the variable to which the pointer is pointing.

Pointer Operators

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 81


There are two pointer operators in C, they are:
(a)* operator
(b) & operator
The & operator returns the memory address of its operand. For example,
a = &b;
In the variable a the memory address of the variable b will get stored.
The * operators is the complement of &. This operator returns the value located at the given address. For
example, if a contains the memory address of the variable b, then the code,

c = *a;

will store the value of the variable b into c.

Pointers in C Example

Let's see a basic code example where we will create a pointer and assign it a value.For example, if a contains
the memory address of the variable b, then the code.c = *a; will store the value of the variable b into c.

#include<stdio.h>
int main()
{
int x = 99;
// declare a pointer
int *ptr;
// assign value to pointer
ptr = &x;
printf("Value at ptr is: %d \n", *ptr);
printf("Address pointed by ptr is: %p \n", ptr);
return 0;
}
Value at ptr is: 99
Address pointed by ptr is: 000000000062FE14
Pointer Arithmetic
There are only a few operations that are allowed to perform on Pointers in C language. The operations are slightly
different from the ones that we generally use for mathematical calculations. The operations are:
(a)Increment/Decrement of a Pointer
(b)Addition and subtraction of integer to a pointer
(c)Comparison of pointers of the same type.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 82


(a)Increment/Decrement of a Pointer

Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually increments
by the number equal to the size of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of an int) and the
new address it will points to 1004. While if a float type pointer is incremented then it will increment by 4(size
of a float) and the new address will be 1004.
Like increment, we can Decrement a pointer variable. If we decrement a pointer, it will start pointing to the
previous location.
Example
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1; //p=p-1 for decrement
printf("After increment: Address of p variable is %u \n",p);
// in our case, p will get incremented by 4 bytes.
return 0;
}
Output for Increment
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304
In above example we have seen p variable has been incremented by 4
Output for Decrement
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296
[Note: Either in decrement or increment for 32 bit int variable it will increment/decrement by 2 bytes for 64 bit
it will increment/decrement by 4 bytes]

(b) Addition and Subtraction of integer to a pointer

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 83


When a pointer is added with a value, the value is first multiplied by the size of data type and then added to the
pointer. The formula of adding value to pointer is given below:
new_address= current_address + (number * size_of(data type))
Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from a pointer
will give an address. The formula of subtracting value from the pointer variable is given below:
new_address= current_address - (number * size_of(data type))
Example
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable //Likewise p=p-3 for substraction
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}
Output for Addition
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
As we can see, the address of p is 3214864300. But after adding 3 with p variable, it is 3214864312, i.e., 4*3=12
increment. Since we are using 64-bit architecture, it increments 12. But if we were using 32-bit architecture, it
was incrementing to 6 only, i.e., 2*3=6. As integer value occupies 2-byte memory in 32-bit OS.
Output for Substraction
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288
we can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the previous address value

(c)Comparison of pointers of the same type


We can compare pointers if they are pointing to the same array. Relational pointers can be used to compare two
pointers. Pointers can’t be multiplied or divided.
#include <stdio.h>
int main() {
int *p2;
int *p1;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 84


p2 = (int *)300;
p1 = (int *)200;
if(p1 > p2) {
printf("P1 is greater than p2");
} else {
printf("P2 is greater than p1");
}
returb(0);
}
Output
P2 is greater than p1

5.9 Returning multiple values from functions using pointers


We can return more than one values from a function by using the method called “call by address”, or “call by
reference”. In the invoker function, we will use two variables to store the results, and the function will take
pointer type data. So we have to pass the address of the data. In this example, we will see how to define a function
that can return quotient and remainder after dividing two numbers from one single function.

#include<stdio.h>
void div(int a, int b, int *quotient, int *remainder) {
*quotient = a / b;
*remainder = a % b;
}
main() {
int a = 76, b = 10;
int q, r;
div(a, b, &q, &r);
printf("Quotient is: %d\nRemainder is: %d\n", q, r);
}
Output
Quotient is: 7
Remainder is: 6

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 85


Unit VI Introduction to C++

6.1 Procedure –Oriented vs. Object Oriented Programming

6.1.1 Procedure Oriented Programming (POP)

POP is a conventional way of programming. Procedural programming is where the primary focus is on getting
the task done in sequential order. Flowchart organizes the flow of control of the program. If the program is
extensive, it is structured in some small units called functions, which shares global data. Here, the concern of
data security arises, as there is an unintentional change in the program by functions.

POP characteristics
 While designing a program, POP follows a top-down programming approach.
 Majority of the functions allows global data to be shared.
 It also divides larger programs into smaller parts called as functions.
 It allows a free data movement around the system from functions to functions.
 Data is transformed by the functions from one form to another.
 It gives importance to the concept of the functions.

POP Limitations

1) Data is undervalued

Procedural programming gives importance on doing things. Data is given less importance, any function can
access and change data.

2) Adding new data element needs modification to functions

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 86


As functions access global data, data cannot be changed without modifying functions that access data.

3) Difficult to create new data types

The ability of a programming language to create new data types is called Extensibility. Extensibility

helps to reduce program complexity. Procedural languages are not extensible.

6.1.2 Object-Oriented Programming (OOP)


The major motivating factor in the invention of object-oriented approach is to remove some of the flaws
encountered in the procedural approach. OOP treats data as a critical element in the program development and
does not allow it to flow freely around the system. It ties data more closely to the function that operate on it, and
protects it from accidental modification from outside function.
OOP allows decomposition of a problem into a number of entities called objects and then builds data and function
around these objects. The organization of data and function in object-oriented programs is shown in fig below.
The data of an object can be accessed only by the function associated with that object. However, function of one
object can access the function of other objects. Organization of data and function in OOP

Features of object oriented programming are:

• Emphasis is on data rather than procedure.


• Programs are divided into what are known as objects.
• Data structures are designed such that they characterize the objects.
• Functions that operate on the data of an object are ties together in the data structure.
• Data is hidden and cannot be accessed by external function.
• Objects may communicate with each other through function.
• New data and functions can be easily added whenever necessary.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 87


• Follows bottom up approach in program design.
Object-oriented programming is the most recent concept among programming paradigms and still means
different things to different people.

Procedure –Oriented Vs. Object-Oriented Programming

S.no. On the Procedural Programming Object-oriented programming


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 task around data or objects rather than
into a set of variables and routines via functions and logic.
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.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 88


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


procedural programming. function 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++.

6.2 Concept of Object-Oriented Programming

6.2.1 Class and Object


 A class is a collection of objects. Each class represents a collection of objects with common attributes
and a set of operations.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 89


 When we define a class, we define a blueprint for a data type. This doesn't actually define any data, but
it does define what the class name means, that is, what an object of the class will consist of and what
operations can be performed on such an object.
 A class definition starts with the keyword class followed by the class name; and the class body, enclosed
by a pair of curly braces. A class definition must be followed either by a semicolon or a list of
declarations For example, we defined the Box data type using the keyword class as follows:
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
Following statements declare two objects of class Box:
Both of the objects Box1 and Box2 will have their own copy of data members.
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box

Objects:
 A class provides the blueprints for objects, so basically an object is created from a class. We declare
objects of a class with exactly the same sort of declaration that we declare variables of basic types.
 Objects are the basic run-time entities in an object-oriented system. They may represent a person, a
place, a bank account, a table of data or any item that the program must handle.
 The fundamental idea behind object oriented approach is to combine both data and function into a
single unit and these units are called objects.
 The term objects means a combination of data and program that represent some real world entity. For
example: consider an example named Amit; Amit is 25 years old and his salary is 2500. The Amit may
be represented in a computer program as an object. The data part of the object would be (name: Amit,
age: 25, salary: 2500)
 The program part of the object may be collection of programs (retrieve of data, change age, change of
salary). In general even any user –defined type-such as employee may be used. In the Amit object the
name, age and salary are called attributes of the object.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 90


6.2.2 Abstraction
 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.
 Classes uses the concept of abstraction and are defined as a list of abstract data and functions to operate
on these datas.
 Classes encapsulate all the essential properties of the objects that are to be created. Since the classes use
the concept of data abstraction, they are known as Abstract Data Types (ADT).
 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.
6.2.3 Encapsulations
 Encapsulation is an Object Oriented Programming concept that binds together the data and functions
that manipulate the data, and that keeps both safe from outside interference and misuse. Data
encapsulation led to the important OOP concept of data hiding.
 Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section, etc. Now, the finance section handles all the financial
transactions and keeps records of all the data related to finance. Similarly, the sales section handles all
the sales-related activities and keeps records of all the sales. Now there may arise a situation when for
some reason an official from the finance section needs all the data about sales in a particular month. In
this case, he is not allowed to directly access the data of the sales section. He will first have to contact
some other officer in the sales section and then request him to give the particular data.
 This is what Encapsulation is. Here the data of the sales section and the employees that can manipulate
them are wrapped under a single name “sales section”

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 91


6.2.4 Inheritance
Inheritance is one of the most useful and essential characteristics of object-oriented programming. The
existing classes are the main components of inheritance. The new classes are created from existing ones.
The properties of the existing classes are simply extended to the new classes.

The new classes created by using such a method are known as derived classes, and the existing classes
are known as base classes, as shown in the figure. The programmer can define new member variables and
functions in the derived class. The base class remains unchanged. The object of the derived class can
access members of the base as well as derived classes. On the other hand, the object of the base class
cannot access members of the derived classes. The base class does not know about their subclasses.

The base class is also called super class, parent, or ancestor, and the derived class is called subclass, child,
or descendent. It is also possible to derive a class from a previously derived class. A class can be derived
from more than one class.

Reusability: Reusability means the reuse of properties of the base class in the derived classes.
Reusability is achieved using inheritance. Inheritance and reusability are not different from each other.
The outcome of inheritance is reusability.

Inheritance Definition: The procedure of creating a new class from one or more existing classes is
termed inheritance.
Syntax: A new class can be defined as per the syntax given below. The derived class is indicated by
associating with the base class. A new class also has its own set of member variables and
functions. The syntax given below creates the derived class.
class name_of_the_derived_class: access specifiers name_of_the_base_class
{
// member variables of new class (derived class)

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 92


}
Example
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
// sub class derived from base class
class Car: public Vehicle{
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0; }
Output:
Here, Class Car has been inherited from of base class Vehicle

6.2.5 Polymorphism
Polymorphism means having many forms. It can be defined as the technique by which an object can take
many forms depending on the situation. In programming terms, we can say that an object can behave
differently in different conditions. Typically, polymorphism occurs when there is a hierarchy of classes
and they are related by inheritance C++ polymorphism means that a call to a member function will cause
a different function to be executed depending on the type of object that invokes the function.
Example:
Consider this example:
The “ +” operator in c++ can perform two specific functions at two different scenarios i.e. when the “+”
operator is used in numbers, it performs addition.

int a = 6; int b = 6; int sum = a + b; // sum =12


And the same “+” operator is used in the string, it performs concatenation.
string firstName = "Great ";
string lastName = "Learning";

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 93


// name = "Great Learning "
string name = firstName + lastName;

Example:

The draw() function is present in the base class SHAPE to draw any shape in the above figure. As the
technique for drawing different shapes is unique, so we have redefined the draw() function in each of the
derived classes. With polymorphism, whenever a user wants to draw a particular shape (say circle), it
merely sends the request to the base class SHAPE by invoking its function draw(), which in reality be
calling a function draw() of the appropriate derived class to display the requested shape.
In C++ polymorphism is basically two types
(a) Compiled time Polymorphism
(b) Run-time Polymorphism

Polymorphism is divided into compile-time polymorphism and runtime polymorphism.


Compile time polymorphism is further divided into operator overloading and function overloading..
Compile time polymorphism is also known as early binding or static polymorphism. In this type of
polymorphism, object’s method is invoked at the compile time.
Runtime polymorphism, the object’s method is invoked at run time. Runtime polymorphism is also known
as dynamic or late binding or dynamic polymorphism. Runtime polymorphism is further implemented using
virtual functions

6.3 Origin of C++

C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell
Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s. Stroustrup, an admirer of Simula67 and a
strong supporter of C, wanted to combine the best of both the languages and create a more powerful language

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 94


that could support object-oriented programming features and still retain the power and elegance of C. The result
was C++.
Therefore, C++ is an extension of C with a major addition of the class construct feature of Simula67. Since the
class was a major addition to the original C language, Stroustrup initially called the new language ‘C with
classes’. However, later in 1983, the name was changed to C++. The idea of C++ comes from the C increment
operator ++, thereby suggesting that C++ is an augmented version of C. C+ + is a superset of C. Almost all c
programs are also C++ programs. However, there are a few minor differences that will prevent a c program to
run under C++ compiler.. The most important facilities that C++ adds on to C care classes, inheritance, function
overloading and operator overloading. These features enable creating of abstract data types, inherit properties
from existing data types and support polymorphism, thereby making C++ a truly object-oriented language.

6.4 Features of C++

1. Simple

C++ is one of the most-simple languages when it comes to programming. It is also easy to understand and learn
as it originated from the C programming language. C++ follows the bottom-up approach for any kind of project
development that helps in breaking down big tasks into a chunk of tasks.

2. Object-Oriented Programming

One of the most important features because of which C++ got famous. Everything is treated as objects in C++
that’s why it is called object-oriented programming. Objects are used for performing all kinds of functionalities.
It has various features like Polymorphism and Inheritance which aims to bind function and data together in a
single unit to make applications secured and efficient.

3. Portability

C++ is not platform independent but we can say it is portable enough to run on different machines by adding
some or no changes at all. On different operating systems you can run the same code. Write code for one time
and use it for every time you need that particular functionality.

4. Mid-Level Programming Language

C++ programming language is a collection of special features of low-level languages and high-level languages.
It can be used to develop applications based on the required level of programing language that is low or high.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 95


5. Rich Library

C++ library is full of in-built functions that save a huge amount of time in the software development process. As
it contains almost all kinds of functionality a programmer can need in the development process. Hence saving
time and increasing development speed.

6. Case Sensitive

As C++ is originated from C, it is also purely CASE sensitive that means lowercase and uppercase characters
written in code will have completely different meaning and will be treated differently.

7. Compiler-Based

As no interpretation is done in C++ code it is considered to be a compiler-based language that makes it faster
than other programming languages like Java, etc. Without compilation, you can’t execute any C++ code.

8. Dynamic Memory Allocation

Due to pointer support in the C++ language. Memory allocation can be easily done dynamically rather than
static. Can free memory anytime by using the free() function.

9. Recursion

Due to code reusability features, we can call any function within a function saving memory space by not writing
the same code again and again. Code reusability is there for every function.

10. Fast

As compared to other programming languages. Execution time and Compilation time of a code written in C++
language are faster than any other programming language.

11. Pointers

As we all know pointers hold the address of another variable and we can access the address of any variable using
concept or pointers which increases performance. C++ also provides the use of pointers in the software
development process.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 96


6.5 C++ Program Structure

#include<iostream.h>
#include<conio.h>
Using namespace std;
int main(){
return 0;
}

Preprocessor Directive
The Preprocessor Directive begins with the character #. It is used to include the necessary header file in a C++
program before compilation. Here we use #include<iostream.h> which stands for standard input-output stream.
This header file contains definitions to objects like cin, cout, cerr etc.

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.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 97


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.

6.6 Input/ Output Stream

C++ comes with libraries which provides us with many ways for performing input and output. In C++ input and
output is performed in the form of a sequence of bytes or more commonly known as streams.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 98


 Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the
main memory then this process is called input.

 Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device(
display screen ) then this process is called output

C++ comes with libraries which provides us with many ways for performing input and output. In C++ input and
output is performed in the form of a sequence of bytes or more commonly known as streams.

Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory
then this process is called input.
Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device (display screen )
then this process is called output.

The two keywords cout in C++ and cin in C++ are used very often for printing outputs and taking inputs
respectively. These two are the most basic methods of taking input and printing output in C++. To use cin and
cout in C++ one must include the header file iostream in the program.This lesson mainly discusses the objects
defined in the header file <iostream> like cin and cout.

cin and cout are NOT reserved words, they are actually variables, instances of classes, that have been declared
in <iostream>. cout is a variable of type ostream. cin is a variable of type istream.

Standard output stream (cout): Usually the standard output device is the display screen. The C++ cout
statement is the instance of the ostream class. It is used to produce output on the standard output device which
is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output
stream (cout) using the insertion operator(<<).

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 99


#include <iostream>
using namespace std;
int main()
{
char sample[] = "NepalEngineeringCollege";
cout << sample << " - A college for Engineers";
return 0;
}

In the above program the insertion operator(<<) inserts the value of the string variable sample followed by the
string “A computer science portal for geeks” in the standard output stream cout which is then displayed on
screen. Notice that you have to insert spaces in the second string. The output of the above program would be:

NepalEngineeringCollege - A college for Engineers

Standard input stream (cin): #include <iostream>


Usually the input device in a computer is the keyboard.
using namespace std;
C++ cin statement is the instance of the class istream
int main()
and is used to read input from the standard input device
{
which is usually a keyboard. The extraction operator (>>)
is used along with the object cin for reading inputs. int age;

The extraction operator extracts the data from the object cout << "Enter your age:";

cin which is entered using the keyboard. cin >> age;

cout << "\nYour age is: " << age;

return 0;

The above program asks the user to input the age. The object cin is connected to the input device. The age entered
by the user is extracted from cin using the extraction operator(>>) and the extracted data is then stored in the
variable age present on the right side of the extraction operator.
Input:
18
Output:
Enter your age:
Your age is: 18

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 100


6.7 Access Specifiers

One of the main features of object-oriented programming languages such as C++ is data hiding. Data hiding
refers to restricting access to data members of a class. This is to prevent other functions and classes from
tampering with the class data. However, it is also important to make some member functions and member data
accessible so that the hidden data can be manipulated indirectly.
The access modifiers of C++ allows us to determine which class members are accessible to other classes and
functions, and which are not.
There are 3 types of access modifiers available in C++:
1) Public
2) Private
3) Protected

Let us now look at each one of these access modifiers in detail:


1. Public: All the class members declared under the public specifiers will be available to everyone. The data
members and member functions declared as public can be accessed by other classes and functions too. The public
members of a class can be accessed from anywhere in the program using the direct member access operator (.)
with the object of that class.
Example:
// access modifier
#include<iostream>
using namespace std;
// class definition
class Circle
{
public:
double radius;

double compute_area()
{
return 3.14*radius*radius;
}
};

// main function
int main()
{
Circle obj;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 101


// accessing public datamember outside class
obj.radius = 5.5;
cout << "Radius is: " << obj.radius << "\n";
cout << "Area is: " << obj.compute_area();
return 0;
}

Output:

Radius is: 5.5


Area is: 94.985

In the above program, the data member radius is declared as public so it could be accessed outside the class and
thus was allowed access from inside main().

2. Private: The class members declared as private can be accessed only by the member functions inside the
class. They are not allowed to be accessed directly by any object or function outside the class. Only the member
functions or the friend functions are allowed to access the private data members of the class.

Example:

// C++ program to demonstrate private


// access modifier
#include<iostream>
using namespace std;
class Circle
{
// private data member
private:
double radius;

// public member function


public:
double compute_area()
{ // member function can access private
// data member radius
return 3.14*radius*radius;
}

};

// main function
int main()
{

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 102


// creating object of the class
Circle obj;

// trying to access private data member


// directly outside the class
obj.radius = 1.5;

cout << "Area is:" << obj.compute_area();


return 0;
}
Output:

In function 'int main()':


11:16: error: 'double Circle::radius' is private
double radius;
^
31:9: error: within this context
obj.radius = 1.5;
^

The output of the above program is a compile time error because we are not allowed to access the private data
members of a class directly from outside the class. Yet an access to obj.radius is attempted, but radius being a
private data member, we obtained the above compilation error. However, we can access the private data members
of a class indirectly using the public member functions of the class.

Example:

#include<iostream>
using namespace std;

class Circle
{
// private data member
private:
double radius;

// public member function


public:
void compute_area(double r)
{ // member function can access private
// data member radius
radius = r;
double area = 3.14*radius*radius;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 103


cout << "Radius is: " << radius << endl;
cout << "Area is: " << area;
} };

// main function
int main()
{
// creating object of the class
Circle obj;
// trying to access private data member
// directly outside the class
obj.compute_area(1.5);
return 0;
}

Output:

Radius is: 1.5


Area is: 7.065

3. Protected: The protected access modifier is similar to the private access modifier in the sense that it can’t be
accessed outside of its class unless with the help of a friend class. The difference is that the class members
declared as Protected can be accessed by any subclass (derived class) of that class as well.

using namespace std;


// base class
class Parent
{
// protected data members
protected:
int id_protected;
};
// sub class or derived class from public base class
class Child : public Parent
{
public:
void setId(int id)
{

// Child class is able to access the inherited


// protected data members of base class

id_protected = id;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 104


}

void displayId()
{
cout << "id_protected is: " << id_protected << endl;
}
};

// main function
int main() {

Child obj1;

// member function of the derived class can


// access the protected data members of the base class

obj1.setId(81);
obj1.displayId();
return 0;
}
Output:

id_protected is: 81

6.8 Objects and accessing data members and member functions

Creating Objects in C++

Syntax:

ClassName ObjectName;
Let’s declare an object student1 of the class Student defined above.

Student student1;

Accessing class members in C++

We can access data members and member functions using dot (‘.’) operator.
Syntax:

ObjectName.VariableName; //Accessing data member


ObjectName.FunctionName(); //Accessing member function

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 105


For example, to access member function getDetails() of class Student defined above for object student1,
we write

student1.getDetails();

Example to show how to create multiple objects of a class and how to access class members

#include <iostream>
using namespace std;
//Class
class Rectangle {
public: //Access specifier
double length, breadth; //Data members
double area() { //Defining Member function
return length*breadth;
}
};
int main() {
//Declaring an object
Rectangle obj1;
//Accessing data members by object 1
obj1.length=12;
obj1.breadth=8.5;

//Declaring another object


Rectangle obj2;
//Accessing data members by object 2
obj2.length=20;
obj2.breadth=14;
//Accessing member functions
cout<<"Area of first rectangle = "<<obj1.area()<<endl;
cout<<"Area of second rectangle = "<<obj2.area();
return 0;
}
Methods
C++ class methods are user-defined functions that can be used within an instance of the class. A dot notation
is used before method names to distinguish them from regular functions.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 106


Class Methods
A class method can be defined in two ways:
(a) Inside the class definition
(b) Outside the class definition
a) Inside the Class
class Person {
string name;
public:
// Defines the method
void get_name() {
return name;
}
};
int main() {
Person ram;
// Calls the method
ram.get_name();
return 0;
}
b) Outside the Class
class Person {
string name;
public:
void get_name();
};

// Defines the method


void Person::get_name() {
return name;
}
int main() {
Person ram;
// Calls the method
ram.get_name();

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 107


return 0; }

6.9 Constructors (Default and Parameterized) and Destructors

 It is sometimes convenient if an object can initialize itself when it is first created, without the need to
make a separate call to member functions.
 Automatic initialization is carried out using special member functions called constructors.

Constructors: A Constructor is a special member function that is called automatically when an object is created.
The purpose of a constructor is to mainly initialize the member variables of a class.

Example: Program to demonstrate how constructor is automatically executed at the time of object creation.
#include<iostream.h>
#include<conio.h>
class Student
{
public:
Student( ) //Here Student is Constructor
{
cout<<”Constructor called automatically”;
cout<<”at the time of object creation”<<endl;
}
};
void main( )
{
Student S1;
Student S2;
Student S3;
}
OUTPUT:
Constructor called automatically at the time of object creation
Constructor called automatically at the time of object creation
Constructor called automatically at the time of object creation

Characteristics of Constructor:

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 108


 The name of the constructor is the same as the name of the class.
Example: In the above class, name of the class is Student and the function name is Student.
 A Constructor, even though it is a function, has no return type, i.e. it is neither a value-returning function
nor a void function. Example: Student ( ) function has no return type and not even void.
 The constructor should be declared in the public section. Constructors are executed automatically i.e.
they are never invoked. They are executed when a class object is created.
 A class can have more than one constructor. However all constructor of a class should have the same
name.
 It is not possible to refer to the address of the constructors. The constructors make implicit calls to the
operator new and delete when memory allocation is required.

Example: Program to demonstrate how a constructor is use to initialize data member of an object.
#include<iostream.h>
#include<conio.h>
class Number
{
private:
int a;
public:
Number ( )
{
cout<<”I am in the Constructor”;
a = 100;
}
void display( )
{
cout<<”Value of a is =”<<a; }

};
void main( )
{
Number N;
N.display();
}
Example: A Program to find the sum of N natural numbers using a class constructor.
#include<iostream.h>
#include<conio.h>
class Sum
{
private:
int n, s;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 109


public:
Sum ( )
{
s = 0;
}
void readdata( )
{
cout<<”Enter the input limit”<<endl;
cin>>n;
}
void display( )
{
for(int i =1; i<=n; i++)
s = s + i;
cout<<”Sum of Natural numbers =”<<s;
}
};
void main( )
{
Sum S1;
S1.readdata( );
S1.display( );
}
OUTPUT:
Enter the input limit
10
Sum of Natural numbers = 55

Types of constructor:
Constructors are normally classified as follows:
(a)Default Constructors.
(b) Parameterized Constructors

(a)Default Constructors:
 A default constructor is a special member function which is invoked by the C++ compiler
without any argument for initializing the object of a class.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 110


 It is also called as zero argument constructors.

Some of the features of the default constructors are:


 A default constructor function initializes the data member with no argument.
 It can be explicitly written in the public section of the class.
 In case, default constructor is not defined in a program, the C++ compiler automatically
generates it in a program.
 The purpose of the default constructor is to construct a default object of the class type.
 The general format of default constructor is as follows:

Example: A program to display N natural numbers using a class default constructor.


#include<iostream.h>
#include<conio.h>
class Number
{
private:
int n;
public:
Number ( ) //Default Constructor with no arguments
{
n = 0;
}
void readdata( )
{
cout<<”Enter the input limit”<<endl;
cin>>n;
}
void display( )
{
for( i =1; i<=n; i++)
cout<<”Natural numbers =”<< i<<”\t”;
}
};
void main( )
{

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 111


Sum S1;
S1.readdata( );
S1.display( );
}

OUTPUT:
Enter the input limit
10
Natural numbers = 1 2 3 4 5 6 7 8 9 10
Parameterized Constructors:
 A constructor that takes one or more arguments is called parameterized constructor.
 Using this constructor, it is possible to initialize different objects with different values.
Parameterized constructors are also invoked automatically, whenever objects with arguments are
created. The parameters are used to initialize the objects.

#include<iostream.h>
#include<conio.h>
class num
{
private:
int a, b;
public:
num ( int m, int n) //Parameterized Constructor
{
a = m;
b = n;
}
void display( )
{
cout<<” a = “ << a <<” b = “ << b;
}
};
void main( )
{
num obj1(10, 20); //Implicit Call
num obj2(40, 50); //Implicit Call
obj1.display( );
obj2.display( );
}
OUTPUT:

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 112


a = 10 b = 20
a = 40 b = 50

Destructors:
 A destructor is special member function that is executed when an object of that class is
destroyed. Destroying an object means, de-allocating all the resources such as memory that was
allocated for the object by the constructor. It will have like constructor, the name same as that of
the class but preceded by a tilde (~).
 The general format of destructor is as follows:

class Class_Name
{
public:
Class_Name( );
~ Class_Name( );
};

Some of the characteristics of destructor are:


 The destructor name must have the same name as the class preceded by a tilde (~).
 The destructor cannot take arguments therefore cannot be overloaded.
 The destructor has no return type.
 There can be only one destructor in each class.
 In should have public access in the class declaration.
 The destructor cannot be inherited

Example: Program to illustrate the use of destructors in C++. #include<iostream.h>


#include<conio.h>
class num
{
private:
int x;
public:
num( ); //Default constructor
void display( );
~ num( );

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 113


};
num : : num( )
{
cout<<In Constructor: \n”;
x = 100;
}
num : : ~ num( )
{
cout<<”In Destructor”;
}
void num : : display( )
{
cout <<”Value of X ” << x <<endl;
}
void main( )
{
num a;
a.display( );
}
OUTPUT:
In Constructor:
Value of X = 100
In Destructor

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 114


Unit VII Object –Oriented Programming Concepts

7.1. Inline function

 C++ provides inline functions to reduce the function call overhead. An inline function is a function
that is expanded in line when it is called.
 When the inline function is called whole code of the inline function gets inserted or substituted at the
point of the inline function call.
 This substitution is performed by the C++ compiler at compile time. An inline function may increase
efficiency if it is small.

Syntax:

inline return-type function-name(parameters)

{ // function code

The inline functions are a C++ enhancement feature to increase the execution time of a program.

 Functions can be instructed to compiler to make them inline so that compiler can replace those function
definition wherever those are being called. Compiler replaces the definition of inline functions at
compile time instead of referring function definition at run time. To make any function as inline, start
its definitions with the keyword “inline”.

Why to use?

In many places we create the functions for small work/functionality which contain simple and less number
of executable instruction. Imagine their calling overhead each time they are being called by callers.

NOTE- This is just a suggestion to compiler to make the function inline, if function is big (in term of
executable instruction etc) then, compiler can ignore the “inline” request and treat the function as normal
function.

When a normal function call instruction is encounteredThe program stores the memory address of the
instructions immediately following the function call statement, loads the function being called into the
memory, copies argument values, jumps to the memory location of the called function, executes the function
codes, stores the return value of the function, and then jumps back to the address of the instruction that

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 115


was saved just before executing the called function. Too much run time overhead. The C++ inline function
provides an alternative.

With inline keyword, the compiler replaces the function call statement with the function code itself (process
called expansion) and then compiles the entire code. Thus, with inline functions, the compiler does not have to
jump to another location to execute the function, and then jump back as the code of the called function is already
available to the calling program. Functions are made inline when they are small enough to be defined in 1 or 2
lines.

Example of Inline Function

Inline Advantages/Disadvantages

 Most of the advantage of inline functions comes from avoiding the overhead of calling an actual
function. Such overhead includes saving registers, setting up stack etc. But with large functions the
overhead becomes less important.
 The biggest drawback of inline function is prohibition of use of for, while and do-while statements in
inline function Inline expansion makes a program run faster because the overhead of a function call and
return is eliminated. However, it makes the program to take up more memory because the statements
that define the inline functions are reproduced at each point where the function is called.

7.2 Friend Function


 In C++, a class encapsulates data and functions that operate on that data. Data members are usually
made private so that they cannot be accessed from the class’s non-member functions. However, in

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 116


certain situations, there is a need to access the private data members of a class by a function that is not
the class member. It can be achieved by making the non-member function as a: friend function.
 However, there could be a situation where we would like two classes to share a particular function. Ex:
Consider a case where two classes, manager and scientist, would like to use a common function
income_tax() to operate on the objects of both the classes. C++ allows the common function to be made
friendly with both the classes, there by allowing the function to have access to the private data of these
classes. Such a function need not be a member of any of these classes

Characteristics of a Friend function:

 The function is not in the scope of the class to which it has been declared as a friend.
 It cannot be called using the object as it is not in the scope of that class.
 It can be invoked like a normal function without using the object.
 It cannot access the member names directly and has to use an object name and dot membership operator
with the member name.
 It can be declared either in the private or the public part.

Syntax for the declaration of a friend function.

class class_name
{
friend data_type function_name(argument/s); // syntax of friend function
};

The body of function is written outside the class


Return_type function-name (arguments)
{
}

In the above declaration, the friend function is preceded by the keyword friend. The function can be
defined anywhere in the program like a normal C++ function. The function definition does not use either
the keyword friend or scope resolution operator.
Example 1
#include<iostream>
#include<conio.h>
using namespace std;
class sample

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 117


{ int a,b;
public:
void getdata(){
a=5,b=6;
}
friend float mean(sample s);
};
float mean(sample s){
float temp;
temp=(s.a+s.b)/2.0;//Here we have used both private datas
return temp;
}
int main(){
sample x;
float r;
x.getdata();
r=mean(x);
cout<<"Mean Value="<<r<<endl;
getch();
return 0;
}
Output
Mean Value=5.5

Example 2: Swapping private data of classes

#include<iostream>

#include<conio.h>

using namespace std;

class B;

class A{

int dataa;

public: void getdata(int a){

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 118


dataa=a; }

void showdata(){

cout<<"Value1="<<dataa<<endl; }

friend void swap(A &x,B &y); };

class B{

int datab;

public: void getdata(int a){

datab=a; }

void showdata(){

cout<<"Value2="<<datab<<endl; }

friend void swap(A &x,B &y);

};

void swap(A &x,B &y){

int temp;

temp=x.dataa;

x.dataa=y.datab;

y.datab=temp; }

int main(){

A a;

B b;

a.getdata(20);

b.getdata(50);

cout<<"Values before Swap\n"<<endl;

a.showdata();

b.showdata();

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 119


swap(a,b);

cout<<"Values After Swap\n";

a.showdata();

b.showdata();

getch();

return 0; }

7.3 Function overloading

Function overloading is a feature of object-oriented programming where two or more functions can have the
same name but different parameters. When a function name is overloaded with different jobs it is called Function
Overloading. In Function Overloading “Function” name should be the same and the arguments should be
different. Function overloading can be considered as an example of a polymorphism feature in C++.The
parameters should follow any one or more than one of the following conditions for Function overloading:

(a) Parameters should have a different type

add(int a, int b)

add(double a, double b)

(b) Parameters should have a different number

add(int a, int b)

add(int a, int b, int c)

(c) Parameters should have a different sequence of parameters

add(int a, double b)

add(double a, int b)

Example

#include <iostream>

using namespace std;

void print(int i) {

cout << " Here is int " << i << endl;

void print(double f) {

cout << " Here is float " << f << endl;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 120


}

void print(char *c) {

cout << " Here is char* " << c << endl;

int main() {

print(10);

print(10.10);

print("ten");

return 0;

Output
Here is int 10

Here is float 10.1

Here is char* ten

How does Function Overloading work?

 Exact match:- (Function name and Parameter)


 If a not exact match is found:
 Char, Unsigned char, and short are promoted to an int.
 Float is promoted to double
 If no match is found C++ tries to find a match through the standard conversion.
 Else error

7.4 Inheritance and its types (Single, Multiple, Multi-level)

 In C++, inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically. In such way, you can reuse, extend or modify the attributes and
behaviors which are defined in other class.
 In C++, the class which inherits the members of another class is called derived class and the class
whose members are inherited is called base class. The derived class is the specialized class for the
base class.
 Code reusability: Now you can reuse the members of your parent class. So, there is no need to
define the member again. So less code is required in the class

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 121


Derived Classes
A Derived class is defined as the class derived from the base class. The Syntax of Derived class:

class <derived_class_name> : <access-specifier> <base_class_name>

{ //body }

Where,
o Class keyword to create a new class
o derived_class_name name of the new class, which will inherit the base class
o access-specifier either of private, public or protected. If neither is specified, PRIVATE is
taken as default
o base-class-name name of the base class

Single Inheritance:
 Single Inheritance is the process of creating a new class from existing class base class. The data members and
member function of the base class are data member and member function of the derived class. A derived class
with single inheritance is declared as follows:
Synatx
class Base_Class
{ ……….. };
class Derived_class : public Base_calss
{ ……….. };

As shown in the figure, in C++ single inheritance only one class can be derived from the base class.
Based on the visibility mode used or access specifiers used while deriving, the properties of the
base class are derived. Access specifiers can be private, protected or public.

Example
#include <iostream>
using namespace std;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 122


class base //single base class
{
public:
int x;
void getdata()
{
cout << "Enter the value of x = "; cin >> x;
}
};
class derive : public base //single derived class
{
private:
int y;
public:
void readdata()
{
cout << "Enter the value of y = "; cin >> y;
}
void product()
{
cout << "Product = " << x * y;
}
};
int main()
{
derive a; //object of derived class
a.getdata();
a.readdata();
a.product();
return 0;
} //end of program
Output

Enter the value of x = 3


Enter the value of y = 4
Product = 12

Explanation

In this program class derive is publicly derived from the base class base. So the class derive inherits all
the protected and public members of base class base i.e the protected and the public members of base
class are accessible from class derive. However private members can’t be accessed, although, we
haven’t used any private data members in the base class. With the object of the derived class, we can
call the functions of both derived and base class.

Multiple Inheritance

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 123


If a class is derived from two or more base classes then it is called multiple inheritance. In C++ multiple
inheritance a derived class has more than one base class.

As shown in above block diagram, class C is derived from two base classes A and B.As in other
inheritance, based on the visibility mode used or access specifier used while deriving, the properties of
the base class are derived. Access specifier can be private, protected or public

Syantax:

class A
{ .......... };
class B
{ ........... } ;
class C : acess_specifier A,access_specifier A // derived class from A and B
{ ........... } ;
Example

#include<iostream>
using namespace std;
class A
{
public:
int x;
void getx()
{
cout << "enter value of x: "; cin >> x;
}
};
class B
{
public:
int y;
void gety()
{
cout << "enter value of y: "; cin >> y;
}

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 124


};
class C : public A, public B //C is derived from class A and class B
{
public:
void sum()
{
cout << "Sum = " << x + y;
}
};

int main()
{
C obj1; //object of derived class C
obj1.getx();
obj1.gety();
obj1.sum();
return 0;
} //end of program
Output

enter value of x: 9
enter value of y: 1
Sum = 10

Multilevel Inheritance

If a class is derived from another derived class then it is called multilevel inheritance. So in C++
multilevel inheritance, a class has more than one parent class. For example, if we take animals as a base
class then mammals are the derived class which has features of animals and then humans are the also
derived class that is derived from sub-class mammals which inherit all the features of mammals.

As shown in above block diagram, class C has class B and class A as parent classes. Depending on the
relation the level of inheritance can be extended to any level. As in other inheritance, based on the

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 125


visibility mode used or access specifiers used while deriving, the properties of the base class are derived.
Access specifiers can be private, protected or public.

Syntax

class A // base class

{…….};

class B : acess_specifier A // derived class

{……..};

class C : access_specifier B // derived from derived class B

{….. } ;

Example

#include <iostream>
using namespace std;
class base //single base class
{
public:
int x;
void getdata()
{
cout << "Enter value of x= "; cin >> x;
} };
class derive1 : public base // derived class from base class
{ public:
int y;
void readdata()
{
cout << "\nEnter value of y= "; cin >> y;
}};
class derive2 : public derive1 // derived from class derive1
{
private:
int z;
public:
void indata()
{
cout << "\nEnter value of z= "; cin >> z;
}
void product()
{
cout << "\nProduct= " << x * y * z;
}
};
int main()

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 126


{
derive2 a; //object of derived class
a.getdata();
a.readdata();
a.indata();
a.product();
return 0;
}
Output

Enter value of x= 2
Enter value of y= 3
Enter value of z= 3
Product= 18

7.5 Function Overriding

Function overriding in C++ is a concept by which you can define a function of the same name and the
same function signature (parameters and their data types) in both the base class and derived class with
a different function definition. It redefines a function of the base class inside the derived class, which
overrides the base class function. Function overriding is an implementation of the run-time
polymorphism. So, it overrides the function at the run-time of the program.

In other words when the base class and derived class have member functions with exactly the same
name, same return-type, and same arguments list, then it is said to be function overriding.

#include<iostream>
#include<conio.h>
using namespace std;
class A{
public :void fun(){
cout<<"Hello C Programming\n";
}
};
class B:public A{
public :void fun(){
cout<<"Hello Oops Programming\n";
} };

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 127


int main() {
B obj;//class B is calling its own function
obj.fun();
getch();
}
Output
Hello Oops Programming

If we want to access A class function by using B class object how can we achieve it ?
 We can achieve function overriding in C++ by two ways
(a) Using Scope Resolution Operator
Example
#include<iostream>
#include<conio.h>
using namespace std;
class A{
public :void fun(){
cout<<"Hello C Programming\n";
}
};
class B:public A{
public :void fun(){
cout<<"Hello Oops Programming\n";
} };

int main() {
B obj;
obj.A::fun(); //using scope resolution operator to call outside function fun() of A is outside function
getch();
}

(b)Pointer:
In order to override the Base function instead of accessing it, we need to use virtual functions in the
Base class.
#include<iostream>

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 128


#include<conio.h>
using namespace std;
class A{
public :void fun(){
cout<<"Hello C Programming\n";
}
};
class B:public A{
public :void fun(){
cout<<"Hello Oops Programming\n";
} } ;

int main() {
A *ptr;
B obj;
ptr=&obj;
ptr->fun();//runtime call
getch();
}
Output:
Hello C Programming

Now if we want to call B class fun() function how can we achieve it from own object just by placing
keyword virtual in base class. Which will ignore fun() of base calss and will execute fun() of derived
class.
#include<iostream>
#include<conio.h>
using namespace std;
class A{
public :virtual void fun(){
cout<<"Hello C Programming\n";
}
};
class B:public A{
public :void fun(){

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 129


cout<<"Hello Oops Programming\n";
} };

int main() {
A *ptr;
B obj;
ptr=&obj;
ptr->fun();//runtime call
getch();
}
Output:
Hello Oops Programming
Advantages of Function Overriding

The concept of function overriding in C++ serves various advantages. Some of the major advantages
are as follows:

 Function overriding helps to improve the readability of the code.


 If both the child class and base class have the same function, it will not affect the independence
of the child class function.

Difference between function overloading and Function Overriding.

Function Overloading Function Overriding


Can occur with or without inheritance. Can only occur during the presence of inheritance.
Overloaded functions must have different function Overridden functions must have the same
signatures (number or data types of arguments should function signatures (number or data types of arguments
be different). should be identical).
Function Overloading allows the same function to Function Overriding occurs when the derived class and
exhibit different behavior depending on the the base class functions are expected to perform
arguments passed to the functions. differently.
Illustrates compile-time polymorphism. Illustrates run-time polymorphism.
Overloading takes place within the same class. Overriding occurs in a base class and its derived class.
Class can have any number of the overloaded Can have only one overridden function per derived class.
functions.
No special keyword is used to overload a function. The virtual keyword in the base class to override a
function.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 130


7.6 Template Function

C++ Templates

A C++ template is a powerful feature added to C++. It allows you to define the generic classes and
generic functions and thus provides support for generic programming. Generic programming is a
technique where generic types are used as parameters in algorithms so that they can work for a variety
of data types. Templates can be represented in two ways:

Templates can be represented in two ways:

 Function templates
 Class templates
In this chapter we will be covering only functions template.

Function Template

 Generic functions use the concept of a function template. Generic functions define a set of
operations that can be applied to the various types of data.
 The type of the data that the function will operate on depends on the type of the data passed as
a parameter.
 A Generic function is created by using the keyword template. The template defines what
function will do.
 For example, Quick sorting algorithm is implemented using a generic function, it can be
implemented to an array of integers or array of floats.

Syntax of Function Template

template < class Ttype>

ret_type func_name(parameter_list)

{ // body of function. }

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 131


 Where Ttype: It is a placeholder name for a data type used by the function. It is used within the
function definition. It is only a placeholder that the compiler will automatically replace this
placeholder with the actual data type.
 class : A class keyword is used to specify a generic type in a template declaration. Let's see a
simple example of a function template:

In the above example, we create the function template which can perform the addition operation on any
type either it can be integer, float or double.

Example
#include <iostream>
using namespace std;
template<class T>
T add(T &a,T &b)
{

T result = a+b;
return result;
}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<'\n';
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}
Output:

Addition of i and j is :5
Addition of m and n is :3.5

Function Templates with Multiple Parameters

We can use more than one generic type in the template function by using the comma to separate the list.

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 132


Syntax
template<class T1, class T2,.....>
return_type function_name (arguments of type T1, T2....)
{
// body of function.
}
#include <iostream>
using namespace std;
template<class X,class Y>
void fun(X a,Y b)
{
cout << "Value of a is : " <<a<<endl;
cout << "Value of b is : " <<b<<endl;
}
int main()
{
fun(15,12.3);
return 0;
}

Overloading a Function Template

We can overload the generic function means that the overloaded template functions can differ in the
parameter list.

#include <iostream>

using namespace std;

template<class X>

void fun(X a)

cout << "Value of a is : " <<a<<endl;

template<class X,class Y>

void fun(X b ,Y c)

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 133


cout << "Value of b is : " <<b<<endl;

cout << "Value of c is : " <<c<<endl;

int main()

fun(10);

fun(20,30.5);

return 0;

Output:
Addition of i and j is :5
Addition of m and n is :3.5

7.7 Exception Handling

 When a program runs into a runtime error, the program terminates abnormally. We want to
handle the runtime error so that the program can continue to run or terminate gracefully. An
exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
 Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.
throw − A program throws an exception when a problem shows up. This is done using a throw
keyword.
catch − A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The catch keyword indicates the catching of an
exception.
try − A try block identifies a block of code for which particular exceptions will be activated.
It's followed by one or more catch blocks

Examples of exception:

– Division by 0,
– Access to an array outside of its bounds,

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 134


– Exhaustion of the heap memory.
Assuming a block will raise an exception, a method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch as follows.

try − A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.

Assuming a block will raise an exception, a method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch as follows −

try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
We can list down multiple catch statements to catch different type of exceptions in case our try
block raises more than one exception in different situations.

Throwing Exceptions

Exceptions can be thrown anywhere within a code block using throw statement. The operand of the
throw statement determines a type for the exception and can be any expression and the type of the
result of the expression determines the type of exception thrown.

Following is an example of throwing an exception when dividing by zero condition occurs −

double division(int a, int b) {

if( b == 0 ) {

throw "Division by zero condition!";

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 135


return (a/b);

Catching Exceptions

The catch block following the try block catches any exception. We can specify what type of exception we want
to catch and this is determined by the exception declaration that appears in parentheses following the keyword
catch.

try {

// protected code

} catch( ExceptionName e ) {

// code to handle ExceptionName exception

Example

#include <iostream>
using namespace std;
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
int main () {
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 136


}

Because we are raising an exception of type const char*, so while catching this exception, we have to use const
char* in catch block. If we compile and run above code, this would produce the following result −

Division by zero condition!

Example

#include<iostream>
#include<conio.h>
using namespace std;
int main() {
int age;
cout<<"Enter age for voting(l8 to 120) ";
cin>>age;
try {
if(age>0 & age<18)
throw 0;
else if(age>120)
throw 'v';
else if (age<0)
throw 2.8;
cout<<"Eligible for voting";}
catch(int i) {
cout<<"Exception Valid age but not eligible for voting";
}
catch( ...)// To catch all unhandled exception
{
cout<<"Exception.: Invalid age for voting";}
getch(); }
Output
Enter age for voting(l8 to 120) 208
Exception.: Invalid age for voting

COMPILED BY:ASST.PROF.ANSHU GHIMIRE,DEPT OF CSE 137

soprotection.com

You might also like