Computr Progaming CPP
Computr Progaming CPP
MANUAL
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:
Disadvantages:
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.
Advantages:
Disadvantages:
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
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
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.
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.
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,
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
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.
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.
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.
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.
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.
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
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.
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
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
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.
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: 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
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.
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
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.
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: 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.
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.
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.
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:
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
DebugWatch Add watchSpecify variables and expressions to watch the value its valueOK
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
DebugAddBreakpointsProvide 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.
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.
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
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
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) BCPL1967 3) B1970 4) C1972 5)K&R C 1978 6) ANSI C1989 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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;
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
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
Example:
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.
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
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
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
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 .
(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.
#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;
}
(ii) scanf()
The scanf() function is used for inputs formatted from standard inputs and provides numerous conversion options
for the printf() function.
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
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.
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.
Output
Enter a character : y
Entered character : y
// C program to implement
// getch() function
#include <conio.h>
#include <stdio.h>
int main()
{
printf("Enter any character: ");
Output:
Enter any character:
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.
Output
Note:
The getch() function will not echo a character. The putch() function displays the input you pressed
String IO Functions
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.
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.
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 –
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and
variable B holds 20 then −
!= 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
&& 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 −
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 −
& 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
<< 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 −
= 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
Besides the operators discussed above, there are a few other important operators including sizeof and ?
: supported by the C Language.
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.
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:
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.
Flow Chart:
Output:
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:
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.
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
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.
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:
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:
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
Advantages of Array
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.
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:
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.
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.
One Dimensional
data_type array_name[array_size];
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;
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;}
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
90 22 55 26 56
marks[0] marks[1] marks[2] marks[3] marks[4] element
Example
#include <stdio.h>
int main()
{ Output:
#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
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'
The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to the
previous example −
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
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];
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";
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'.
char string[]="Nepal";
int len;
len=strlen(string);
printf("length of %s is %d\t", string, len);
}
Output::length of Nepal is 5.
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);
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";
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>
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>
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.
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;
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.
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.
STUDENTS DETAILS:
Roll number: 1
Name: Venkat
Total Marks:98.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.
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.
#include <stdio.h>
#include <conio.h>
#include <stdio.h>
#include <conio.h>
void main()
{
struct dob
{
int day;
int month;
int year;
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
{
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.
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.
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 −
int result;
result = num1;
else
result = num2;
return result;
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
double large;
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
if (a > b)
return a;
else return b;
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.
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 function body consists of the set of instructions enclosed between { and } .
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:
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.
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
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.
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.
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;
}
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
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 main()
int m,n;
swap(m,n);
}
void swap(int a, int b)
int temp;
temp=a;
a=b;
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.
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.
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
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.
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.
type *name;
example
Pointer Operators
c = *a;
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.
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]
#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
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.
The ability of a programming language to create new data types is called Extensibility. Extensibility
6. Access There are no access modifiers in The access modifiers in OOP are
modifiers procedural programming. named as private, public, and
protected.
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.
13. Data hiding There is not any proper way for data There is a possibility of data hiding.
hiding.
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.
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)
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.
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
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
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.
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.
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.
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.
#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.
Opening Brace
This is called the Opening Brace {. Whatever we will write inside the main function, we will write it after the
Opening Brace.
Closing Brace
This is called the Closing Brace}. We use the Closing Brace at the end of the program.
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.
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(<<).
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:
The extraction operator extracts the data from the object cout << "Enter your 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
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
double compute_area()
{
return 3.14*radius*radius;
}
};
// main function
int main()
{
Circle obj;
Output:
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:
};
// main function
int main()
{
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;
// 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:
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.
id_protected = id;
void displayId()
{
cout << "id_protected is: " << id_protected << endl;
}
};
// main function
int main() {
Child obj1;
obj1.setId(81);
obj1.displayId();
return 0;
}
Output:
id_protected is: 81
Syntax:
ClassName ObjectName;
Let’s declare an object student1 of the class Student defined above.
Student student1;
We can access data members and member functions using dot (‘.’) operator.
Syntax:
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;
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:
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;
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.
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:
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( );
};
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:
{ // 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 encounteredThe 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
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.
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.
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.
class class_name
{
friend data_type function_name(argument/s); // syntax of friend function
};
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
#include<iostream>
#include<conio.h>
class B;
class A{
int dataa;
void showdata(){
cout<<"Value1="<<dataa<<endl; }
class B{
int datab;
datab=a; }
void showdata(){
cout<<"Value2="<<datab<<endl; }
};
int temp;
temp=x.dataa;
x.dataa=y.datab;
y.datab=temp; }
int main(){
A a;
B b;
a.getdata(20);
b.getdata(50);
a.showdata();
b.showdata();
a.showdata();
b.showdata();
getch();
return 0; }
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:
add(int a, int b)
add(double a, double b)
add(int a, int b)
add(int a, double b)
add(double a, int b)
Example
#include <iostream>
void print(int i) {
void print(double f) {
int main() {
print(10);
print(10.10);
print("ten");
return 0;
Output
Here is int 10
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
{ //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;
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
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;
}
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
Syntax
{…….};
{……..};
{….. } ;
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()
Enter value of x= 2
Enter value of y= 3
Enter value of z= 3
Product= 18
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";
} };
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>
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(){
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:
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:
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.
ret_type func_name(parameter_list)
{ // body of function. }
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
We can use more than one generic type in the template function by using the comma to separate the list.
We can overload the generic function means that the overloaded template functions can differ in the
parameter list.
#include <iostream>
template<class X>
void fun(X a)
void fun(X b ,Y c)
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
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,
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.
if( b == 0 ) {
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 ) {
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;
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 −
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
soprotection.com