0% found this document useful (0 votes)
6 views

OOPC Part1

OOPs in Cpp

Uploaded by

aadityamdubey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

OOPC Part1

OOPs in Cpp

Uploaded by

aadityamdubey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Object Oriented Programming in C++

Number System

There are four types of number systems.


(1) Decimal Number System
(2) Binary Number System
(3) Octal Number System
(4) Hexadecimal Number System

Binary Number System [BNS] :- Bi means 2 so BNS consist of 2 digits 0 –1. A binary number
system is any combination of digits 0 and 1.
Example: 01, 00, 11, 100010001, 11001100, 11110000

Decimal Numbe r System [ DNS] :- Deci means 10 so DNS consist of ten digits 0 – 9. A
decimal number system is any combination of digits 0 to 9.
Example: 178, 234, 908, -99876

Octal Number System [ ONS] :- Octal means 8 so ONS consist of 8 digits 0 -7. An octal
number system is any combination of digits 0 to 7.
Example: 76, 75, 11, 123

Hexadecimal Numbe r System [HNS]:- Hexa means 6 and deci means 10 so HNS consist of 16
characters. 0 –9 and A-F
A=10, B=11, C=12, D=13, E=14, F=15
Eg. 76, 11, 01, 2A, 2FBC, AB12C

Conve rsion of Numbe r System


Conversion of DNS to BNS :-
Example: Convert 81 decimal to binary.
Arrange the numbers according to 8-4-2-1 representation as given below. Put the digit 1 below
the number 81 or less than 81. 64 is the number less than 81 so put 1 below 64 and subtract 64
from 81 we get 17. Put the digit 1 below the number 17 or less than 17. 16 is the number less
than 17 so put 1 below 16 and subtract 16 from 17 we get 1. Now put the 1 below 1 and subtract
1 from 1 we get 0. Put zeros below other numbers. Now stop the process we get
(0 1 0 1 0 0 0 1) which is the binary equivalent of
81.

128 64 32 16 8 4 2 1
0 1 0 1 0 0 0 1

Conversion of BNS to DNS:-


Example: Convert 1 0 0 1 1 0 1 1 to decimal.
Arrange the numbers according to 8-4-2-1 representation as given below. Put the digits 1 and 0
below the number according to the positions of the digits. Add all 1’s bit we get 155.

Amar Nayak
Object Oriented Programming in C++

128 64 32 16 8 4 2 1
1 0 0 1 1 0 1 1

1 0 0 1 1 0 1 1 binary is 155
decimal.

Memory units
Bits: Binary digits, 0 or 1
Nibble: Group of 4 bits
Byte: Group of eight bits.
Word: Group of 16/ 32 or 64 bits.
b represents Bit and B represents Byte.
Kilo bits (Kb): 1024 bits (1kb)
Kilo Byte (KB): 1024 byte (1KB)
Mega bits(Mb): 1kb * 1kb= 1024 * 1024 bits= 1mb
Mega byte(MB): 1KB * 1KB= 1024 * 1024 byte= 1MB
Giga bits (Gb) = 1024 * 1024 * 1024 bits = 1kb * 1kb * 1kb= 1mb*1kb
Giga byte (GB) = 1024 * 1024 * 1024 byte = 1KB * 1KB * 1KB= 1MB*1KB
Tera bits (Tb) = 1024 * 1024 * 1024 * 1024 bits = 1Kb*1Kb*1Kb*1Kb=1Mb*1Mb=1Gb
Tera Byte (TB) = 1024 * 1024 * 1024 * 1024 byte = 1KB*1KB*1KB*1KB=1MB*1MB=1GB

Decimal number Binary equivalent


0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
10 1010
11 1011
12 1100
13 1101
14 1110
15 1111

Amar Nayak
Object Oriented Programming in C++

Programming Languages

Generations of Programming Languages


There are five generations of programming languages available to program a computer.

(1) First generation: Machine Language, Low Level Language, Binary Language :- [ LLL ]
(2) Second generation: Assembly Language:- [AL]
(3) Third generation: High Level Language: - [ HLL ]: C/C++/Java/PHP/Python
(4) Fourth generation language (4GL): [ HLL]: HTML, XML, SQL
(5) Fifth generation language (5GL) [HLL]: Artificial Intelligence: Prolog, LISP

(1) Machine Language : Machine Language is the language written by using 0’s and 1’s. The
computer only understands machine language.
Advantages of machine language:-
(1) It directly communicated with the internal circuitry.
(2) It is fast.

Disadvantages of machine language:-


(1) The binary code is very difficult to learn and find out errors.
(2) It id machine dependent.
Example: 10001011
10011111

(2) Assembly Language :- In assembly language program are written in the form of English
abbreviations (Short form) is called mnemonics. The assembly language is machine dependent.
Advantages of AL
It is easy as compared to machine language.

Disadvantages
Machine dependent
It requires assembler to convert program written in AL to LLL which may
be costly.

Example. MOV a,b


SUB A,B
ADD A,B
MUL A,C
Example:
MVI A,10H
MVI B,20H
ADD B
OUT B
HLT

Amar Nayak
Object Oriented Programming in C++

(3) High Level Language :- HLL is the language written using human understandable language
like English. HLL languages are easier to learn and use. It is machine independent language.
HLL can be run on many different computers with very little or no alternation.
A program written in HLL is called source program.
Example:
COBOL [COmmon Business Oriented Language]
FORTRAN [FORmula TRANslation]
C, C++, Java, C#, VB.NET, VB, Pascal, Scala, Julia, Kotlin, PHP, Go, Swift

Advantage of HLL
Simple
Portable

Limitation
It requires compiler or interpreter which may be costly.

(4) 4GL: In 4GL we have to only specify What to do? We don’t have to specify how to do?
HTML: Hypertext markup language
XML: Extensible markup language
SQL: Structured Query Language

Example in SQL:
Select * from students;
Delete from students where eno=10;
Example in HTML:
<html>
<head><title></title></head>
<body>
<h1>Welcome</h1>
<hr>
<img src=”myphote.jpg”></img>
</body>
</html>

(5) 5GL: 5GL are used specially for developing Artificial Intelligence program.
Example: LISP: LISt Processing
Prolog

Instruction: - Instruction tells the computer to do some action.


Program: - A group of statements (instructions) are called program.
Software: - A group of program is called software.
Types of software’s
Application software: used by users. Notepad, MS Word, Excel, Calculator
System software: Operating systems (Windows, Linux, Unix, Android, Mac OS)
Device drivers: Keyboard, Printer, Scanner

Amar Nayak
Object Oriented Programming in C++

Compiler: -

HLL Compiler Machine Language

A compiler is a system software program, which converts HLL program into machine language.
It converts entire program into machine language. It is fast.

Functions of compiler:-
(1) It translates the source program into machine language.
(2) During the translation process it looks for syntax error.
(3) The compiler reserve space for variables, arrays etc.

Inte rpreter:-

HLL Inte rpreter Machine Language

An interpreter is a system software program, which converts HLL program into machine
language.
It translates one by one statement written in HLL into machine language. It is slow.
The functions of interpreter are
(1) It translates the source program into machine language.
(2) During the translation process it looks for syntax error.
(3) The compiler reserve space for variables, arrays etc.

Assembler:-
AL Assembler Machine Language

An Assembler is a system software program, which converts Assembly program into


machine language.

Linker: -Linker is a system program which takes object code of a source program as input and
produces an executable code. The linker combines the code you wrote with the object code
already found in the standard library. This process is called linking.

Amar Nayak
Object Oriented Programming in C++

Introduction to C
C is a (middle level) high level programming language developed by Dennis Ritchie in
1972 at AT & T Bell labs at USA. C is also called middle level language because it
combines the features of high level language and machine language. As a HLL language
it gives the better programming efficiency i.e. faster program development. As a LLL it
gives better machine efficiency i.e. faster program execution.

Feature of c:- (1) Simple


(2) Secure
(3) Portable
(4) Modular.

Uses of c:-
(1) System programming:- For developing system program.
Example. For developing Operating System Example Unix, Linux, Win 95/98/NT/2000,
Sun solaris
For developing compiler, editors, interpreter
For developing device drivers for hardware’s.
(2) Database programming:- For developing databases.
Example. Oracle, SQLServer, MySQL, Informix, Sybase.
(3) Application Programming:- For developing application software.
Example Mathematical equations, Customer bill, banking
History of c:- Before the development of c each language is used for specific purpose. For
Example COBOL (Common Business Oriented Language) for co mmercial applications and
FORTRAN (Formula Translation) for Engineering and scientific applications. At this stage
people started thinking that instead of learning and using so many languages, each for a different
purpose why not use only one language, which can perform all possible applications. So they
developed c.
C is a general-purpose language. C is a structured language. The feature of a
structure language is compartmentalization of functions and data.
C offers better interaction with hardware.

Language history

Year Language Developed by


1960 ALGOL International Committee
1963 CPL Cambridge University
1967 BCPL Martin Richards at C
Cambridge University
1970 B Ken Thomson at AT & T
1972 C Dennis Ritchie at AT & T
1979 C++ Bjarne Strustrup

Amar Nayak
Object Oriented Programming in C++

1990 Python Guido Van Rossum


1991 Java James Gosling
1984 MATLAB Cleve Moler
1978 SQL Donald Chamberlin,
Boyce
1985 Eiffel Bertrand Meyer
1987 Perl Larry Wall
1991 Visual Basic Alan Cooper (Microsoft)
1993 R Ross Ihaka
1995 Ruby Yukihiro Matssumoto
1995 JavaScript Brendan Eich
1995 PHP Rasmus Ledorf
2001 C# Anders Hejlsberg
2003 Scala Martin Odersky
2009 Go Ken Thompson
2010 Rust Graydon Hoare
2011 Dart Lars Bak and Kasper Lund
2011 Kotlin JetBrains
2012 Julia Jeff Bezanson
2014 Swift Chris Lattner

ALGOL -> Algorithmic Language


CPL -> Combined Programming Language
BCPL -> Basic Combined Programming Language

Introduction to C++
C++ is an object oriented, high level programming language. C++ is a cross-platform
language that can be used to create high-performance applications. C++ was
developed by Bjarne Stroustrup, as an extension to the C language. C++ gives
programmers a high level of control over system resources and memory.
The language was updated 3 major times in 2011, 2014, and 2017 to C++11, C++14,
and C++17.
C++ is a general-purpose programming language that was developed as an
enhancement of the C language to include object-oriented paradigm. It is an
imperative and a compiled language.
C++ is a middle- level language rendering it the advantage of programming low- level
(drivers, kernels) and even higher-level applications (games, GUI, desktop apps etc.).
The basic syntax and code structure of both C and C++ are the same.

Some of the features & key-points to note about the programming language are as
follows:
Simple: It is a simple language in the sense that programs can be broken down into
logical units and parts, has a rich libray support and a variety of data-types.

Amar Nayak
Object Oriented Programming in C++

Machine Independent but Platform Dependent: A C++ executable is not platform-


independent (compiled programs on Linux won’t run on Windows), however they
are machine independent.
Mid-level language: It is a mid- level language as we can do both systems-
programming (drivers, kernels, networking etc.) and build large-scale user
applications (Media Players, Photoshop, Game Engines etc.)
Rich library support: Has a rich library support (Both standard ~ built- in data
structures, algorithms etc.) as well 3rd party libraries (e.g. Boost libraries) for fas t
and rapid development.
Speed of execution: C++ programs excel in execution speed. Since, it is a compiled
language, and also hugely procedural. Newer languages have extra in-built default
features such as grabage-collection, dynamic typing etc. which slow the execution of
the program overall. Since there is no additional processing overhead like this in
C++, it is blazing fast.
Pointer and direct Memory-Access: C++ provides pointer support which aids users
to directly manipulate storage address. This helps in doing low- level programming
(where one might need to have explicit control on the storage of variables).
Object-Oriented: One of the strongest points of the language which sets it apart from
C. Object-Oriented support helps C++ to make maintainable and extensible
programs. i.e. Large-scale applications can be built. Procedural code becomes
difficult to maintain as code-size grows.
Compiled Language: C++ is a compiled language, contributing to its speed.

Applications of C++:
C++ finds varied usage in applications such as:
Operating Systems & Systems Programming. e.g. Linux-based OS (Ubuntu etc.)
Browsers (Chrome & Firefox)
Graphics & Game engines (Photoshop, Blender, Unreal- Engine)
Database Engines (MySQL, MongoDB, Redis etc.)
Cloud/Distributed Systems
Some interesting facts about C++:
Here are some awesome facts about C++ that may interest you:

The name of C++ signifies the evolutionary nature of the changes from C. “++” is
the C increment operator.
C++ is one of the predominant languages for the development of all kind of technical
and commercial software.
C++ introduces Object-Oriented Programming, not present in C. Like other things,
C++ supports the four primary features of OOP: encapsulation, polymorphism,
abstraction, and inheritance.
C++ got the OOP features from Simula67 Programming language.
A function is a minimum requirement for a C++ program to run.(at least main()
function)

Amar Nayak
Object Oriented Programming in C++

Why Use C++


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

C++ Fundamentals
Communicating with a computer involved speaking the language the computer understands.
Steps in learning C++ language:-

C++ character set Constants, Identifiers,


(Alphabets, digits, Variables, Keywords
special Symbols) Expressions Instruction Program

First we have to know what alphabets, numbers and special symbols are used in C++. Then using
these alphabets numbers and symbols how to construct instructions. And using these group of
instructions how to create a program.

The C++ character set :C++ uses


Uppercase letter A to Z
Lowercase letter a to z
Digits 0 to 9
Special symbols *,#,(,$,&,},},,
C++ uses ASCII character sets.
ASCII: American Standard Code for Information Interchange
In ASCII every character is encoded with integer value.
A: 65, B: 66,…….. Z:90
a: 97, b: 98,………z:122
0: 48, 1,49,……..9:57
$: 36
These character set is used to form basic program elements.
Example: Constant, Variables, Keywords, Operator, Expressions.

Identifiers:- Identifiers are the name given to various program elements such as variables,
functions, classes, objects and arrays. Identifiers consist of letters and digits in any order except
that first character must be a letter. Both uppercase and lowercase are permitted. The underscore
(_) character can also be included. The keywords cannot be used for identifiers. We cannot use
special symbol as identifiers.
Valid identifiers:- a, a12,qm_1,_am_as,ATM,area,simple
Invalid Identifier:- 1a,*am, _a+c, a#,int, float.

Amar Nayak
Object Oriented Programming in C++

Keywords:- There are certain reserved words called keywords that are standard predefined
meaning in C++. There
Example: int, float, char, long, double, if, else, do, while, for, class, struct, virtual, etc.

Data:- Data is a collection of facts and figures which can be processed to produce information.
Raw information is called data.
Data is simple value or set of values.
Information: - When data is meaningful it is called information.

12 + 5 = 17
where 12 and 7 are data and 17 is information.
Data types: - A data type defines a set of values that a variable can store along with a set of

operations that can be performed on that variable.

C has five basic types of data. Integer, floating point, character, double, void

Constant:- A constant is a quantity that doesn’t changes. This quantity can be stored at locations
in the memory of the computer.
C++ has four basic types of constants, integer constant, floating point co nstant, character
constant, string constants and Boolean constants.

C constants

Bool
(true/false) Numeric Character

Single String
Integer Float Character

Decimal Octal Hexa


Fractional Exponential

Integer Constant:- is an integer value number. It consists of sequence of digits. Integer constant
can be written in 3 different ways.
(1) Decimal
(2) Octal
(3) Hexadecimal

(1) Decimal:- A decimal integer Consists of any combination of digits from 0 to 9.

Amar Nayak
Object Oriented Programming in C++

(2) Octal:- An octal integer Consists of any combination of digits from 0 to 7.


The first digit must be 0 to identify the constant as octal.
(3)Hexadecimal:-A hexadecimal integer consists of any combination of digits from 0 to 9
and A to F. Hexadecimal constant began with 0x or 0X.

Rules of creating integer constant


(a) Must have at least one digit.
(a) Must not have any decimal point.
(b) Positive or negative. Default sign is positive.
(c) Range is –32768 to +32767.
(d) No commas or blank spaces are allowed.

Example 10 65 -976 9134 -9865 (in decimal)


012 06754 06312 (in octal)
0xA120x1001 0x897A (in hexadecimal)

Floating Point Constant (Real constant):- can be written in two forms.


(1) Fractional: Normal floating point calculations are using fractional notations.
(2) Exponential: When value is too short or too long then exponential form is used.

Rules for constructing floating point constant in fractional form.


(a) Must have at least one digit.
(b) Must have a decimal point.
(c) Positive or negative. Default sign is positive.
(d) No commas or blank spaces are allowed.

Example. 10.3 -78.9 3.14 -0.0009

The Exponential form of representation of real constant is usually used if value of the
constant is either too small or too large.
In exponential form of representation the real constant is represented in two parts. The
part appearing before E is called mantissa whereas the part following E is called exponent.

Rules for constructing floating point constant in Exponential form.


(a) The mantissa part and exponential part should be separated by letter E.
(b) The mantissa part may have a positive or negative sign.
(c) The exponent must have at least one digit which may be positive or negative.
(d) Range is –3.4E38 to 3.4E38.

Amar Nayak
Object Oriented Programming in C++

Example. +3.2E-5 -0.2E+3


4.1E38 -3.2E-5

Character constant:- A character constant is either a single alphabet, a single digit


or a special symbol enclosed within single inverted commas. Both inverted commas should
point to left.
Maximum length is 8 bit [1 byte].
Example. ’A’, ’a’, ’1’, ’*’

String Constant:- is a set of characters enclosed in double quotes.


Example “This is a string”

Bool constant: used to represents Boolean values true/ false.

How to identify data type


2 -: integer constant (decimal)
2.0 -: float constant
‘2’ -: char constant
02 -: integer constant (octal)
0X2 -: integer constant (hexadecimal)
“2” -: string

Data types: - A data type defines a set of values that a variable can store along with a set of

operations that can be performed on that variable.

Data Types
Data Type Description Size in Bytes Range

(1) char Single character 1 Byte -128 to +127


unsigned char Single character 1 Byte 0-255
signed char Single character 1 Byte -128 to +127
(2) int integer quantity 2 Byte -32768 to +32767
unsigned int integer quantity 2 Byte 0 to 65535
signed int integer quantity 2 Byte -32768 to +32767
short int integer quantity 2 Byte -32768 to +32767
unsigned short int integer quantity 2 Byte 0 to 65535
signed short int integer quantity 2 Byte -32768 to +32767
long int integer quantity 4 Byte -2147483648 to +2147483647
unsigned long int integer quantity 4 Byte 0-4294967295
signed long int integer quantity 4 Byte -2147483648 to +2147483647

(3) float floating point number 4 Byte 3.4E-38 to 3.4E38


(4) double double precision 8 byte 1.7E-308 to 1.7E 308

Amar Nayak
Object Oriented Programming in C++

(5) long double ten digits of precision 10 Byte 1.7E-4932 to 1.1E4932


(6) bool Boolean values true/ false

Separators

In C++ there are few characters that are used as separators. The most commonly used separator
in C++ is the semicolon (;). The other separators are
Symbol Name Purpose
() Parenthesis Used to contain lists of parameters in function
definition
and invocation. Also used for defining precedence
in expressions, containing expressions in control
statements, surrounding the casts.
{} Curly braces Used to contain the values of automatically
initialized
arrays. Also used to define a
block of statements, structure, functions and local
scopes.
[] Brackets Used to declare array types. Also used when
accessing an
array.
; Semicolon Terminates statements.
, Comma Separate identifiers in a variable declaration. Also
used to
chain statements together inside a for statement.
. Period Used to separate structure variable and structure
member.

Variables
A variable is a quantity, which may changes during the program execution. Variables names are
names given to the location in the memory of the computer where different constants are stored.
These locations may contain integer, real or character constant. All variables must be declared
before they can be used. Variable is a container for constants.

Types of variables
(1) int
(2) float
(3) char

Declaration-: All variables must be declared before they can be used. The general form of a
declaration is
datatype variable_list ;
Type must be a valid data type and variable list may consist of one or more identifier names
separated by commas.
Example

Amar Nayak
Object Oriented Programming in C++

int a,a1,axz;
Explanation:- a, a1, axz are the variables which stores integer type
of data.

float x,y,z;
Explanation:- x, y, z are the variables which stores float type of
data.

char p,q,r;
Explanation:- p, q, r are the variables which stores character type
of data.

By default a variable contain garbage value. If we have to give initial value to the variable then
we must initialize it.

Initialization of variables:- Initial values can be assigned to variables with a type declaration. We
can give variables a value as we declare them by placing an equal sign and a value after the
variable name.
The general form of initialization is
Data_type variable_name = value ;
(1) Initialization of integer variable:-
int a=10,b=20; a and b are integer variables which hold 10, 20 values.
(2) Initialization of float variable:-
float x=3.14 ,y=-12.8 ; x and y are float variables which hold 3.14 , -12.8 values.
(3) Initialization of character variable:-
char p=’*’ ,q=’2’ , r=’A’; p , q and r are character variables which hold * , 2 , A
values.

IDE (Integrated Development Environment) :-


Provides all necessary tools for developing a program.

Editor

Compile
r
IDE
Debugger

Preprocessor
Linker

Amar Nayak
Object Oriented Programming in C++

Flowchart
Before solving a problem with the help of a computer it is necessary to plan the solution
in a step-by-step manner. Such a planning is represented symbolically with the help of flowchart.
A flowchart is a symbolic representation of the step-by-step solution of a given problem.
Flowchart indicates the flow of entire process, the sequence of data input, operations,
computations, decisions, and results. A flowchart is useful to understanding of the logical
structure of a problem and in documenting the method used.
Two types of flowchart:
(1) System flowcharts: are used by System Analysts to describe the data flow and
operations for a data processing. A system flowchart defines the processing in the organization.
(2) Program flowcharts: are used by programmers to describe the sequence of operations
and decisions for a particular problem.

The oval shaped symbol indicates the terminal points, i.e. the beginning or end of a flowchart.
The parallelogram symbol is used for input/output of data or information from/to any device, i.e.
it indicates the operation of reading and writing.
A diamond shaped symbol is used to indicate decisions (questions). The answer is yes/no.
The next step is depends upon answer of the question.

Escape Sequence:-
Certain non printing characters as well as the double quote ( “ ) , and backslash ( \ ) can be
expressed in terms of escape sequences. An escape sequence always begins with a back slash and
followed by one or more special characters.
The commonly used escape sequences are
Escape Sequence Meaning
\a Bell
\b Backspace
\t Horizontal Tab
\v Vertical tab
\n new line
\” Quotation mark
\\ Backslash
\0 Null

ASCII: - American Standard Code for Information Interchange. Most computers make use of
ASCII character set in which each individual character is numerically e ncoded with its own
unique ASCII value. There are 256 characters from 0-255.
Characters ASCII value.
A-Z 65-90
a-z 97-122
0-9 48-57
NULL 0
$ 36

Amar Nayak
Object Oriented Programming in C++

* 42

Comments:- Comments are explanatory remarks. Comments help to understand what the
complete program is about. Comments don’t affect the program execution and they can be
placed anywhere within a program. Comments are helpful in identifying the program principle
feature or in explaining logic of various program features. Comments are non-executable part.
Two types of comments in C++
// single line comment
/* Multiline
Comment
*/
Example.
/* This is a comment */

Expressions:- An expression represents a single data item such as a number or a character. The
expression may consist of a single entity such as a constant, a variable, an array element. It may
also consist of some combination of such entities interconnected by one or more operators.
Expression can also represent logical condition that are either true or false.
Example a+b, x=y, c=a+b, a<=y , x==y , ++j

Statements:- A statement tells the computer to carry out some action. The types of statements in
c are
(1) Expression (2) Compound (3) Control

(a)Expression statement: - An expression statement consists of an expression followed


by a semicolon.
Example a=3; c=a+b; ++j; printf(“Area=%f”,area);

(b)Compound statement: - Consist of several individual statements enclosed within a


pair of braces. { }
Example {
Pi=3.14;
Cir=2*3.14*r;
Area=pi*r*r;
}
(c)Control statement: - are used to create special program feature such as logical tests,
loops.
Example while(cnt<=n)
{
printf(“x”);
scanf(“%f”,%x);
sum=sum+x;
++cnt;
}

Amar Nayak
Object Oriented Programming in C++

Ope rators
An operator is a symbol that causes mathematical or relational or logical operations to be
performed. The data items that operators act upon are called operands. Some operators require
two operands they are called binary operators. Some operators require one operand they are
called unary operators.

a+b
a and b are operands and + is an operator.

The operators available in C are


(1) Arithmetic Operators
(2) Relational Operators
(3) Logical Operators
(4) Bitwise Operators
(5) Assignment Operators
(6) Increment and Decrement Operators
(7) Equality Operators
(8) Conditional Operators
(9) sizeof()

(1) Arithmetic Operators: are used for arithmetic operations. There are 5 arithmetic
operators in C++.

Operator Meaning
+ For addition
- For Subtraction
* For multiplication
/ For division
% Modulus or Remainder Operator (It
gives the remainder of its operand)
Modulus or remainder operator: (%) It returns remainder of integer division. The operands acted
upon by arithmetic operators must represent numeric values. Thus the operands can be
integer quantity, floating point quantity or characters. The remainder operator (%)
requires that both operands be integers and second operand be nonzero. Similarly, the
division operator (/) requires that the second operator be nonzero though the operands
need not be integers.
Division of one integer quantity by another is referred to as integer division. This
operation always results in a truncated quotient. On the other hand if a division operation
is carried out with two floating-point numbers, or with one floating-point number, the
result will be a floating-point quotient.

Amar Nayak
Object Oriented Programming in C++

(2) Relational Operator: are used to test or compare the value between two operands. The
relational operators produce an integer result to express the condition of the comparison.
If the condition is false then false keyword is used and if the condition is true then the
true keyword isused. There are six relational operators in C++

Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal

The relational and logical operators are used to form logical expressions representing
conditions that are either true or false.

(4)Assignment Operator:
Assign the value of the expression on its right side to the variable on the variable
on its left side.
= Assignment operator
int a=5,b;
b=a;
This statement assign the value of a=5 to b. So b becomes 5.
If the two operands in an assignment expression are of different data types, then
the value of the expression on the right will automatically be converting to the type of the
identifier on the left.
Rules for assigning value
(1) A floating point value may be truncated if assigned to an integer variable (identifier).
(2) A double precision value may be rounded is assign to a floating point identifier.
(3) An integer quantity may be altered if assigned to shorter integer identifier, or to a
character variable.

Ex
int i;
float a=2.3,b=3.9,c=-3.9;
Expression value
i=a; 2
i=b; 3
i=c; -3

Other assignment operators


+=
-=
*=
/=
%=

Amar Nayak
Object Oriented Programming in C++

a=a+5 is equivalent to a+=5


a=a-5 is equivalent to a-=5
a=a*5 is equivalent to a*=5
a=a/5 is equivalent to a/=5
a=a%5 is equivalent to a%=5

Note: The assignment (=) or equality operator (==) is different.


The assignment (=) operator is used to assign a value to an identifier (variable).
The equality operator (==) is used to determine (check) it two expression have the same
value.

(5)Logical operators: are used to combine two or more relations. The logical operators
act upon operands that are themselves logical expressions. The result of logical operators
is either true or false.

Operator Meaning

&& Logical AND


|| Logical OR
! Logical NOT

Logical AND (&&): The result of a logical AND operation will be true if both operands
are true.
Logical OR (||): The result of a logical OR operation will be true if either operand is true
or if both operands are true.
Logical NOT (!): Logical NOT negates the value o f logical expression. If the value of
expression is true than ! operator convert it to false and vice versa.
true -> flase
flase -> true
Output
input 1 input2 AND (&&) OR(||)

true false false false


false true false true
true false false true
true true true true

int i=7, j=4;

Expression Output
(i>=6) && (j>=2) true
(i>=6) && (j>=6) false
(i<10) && (j>2) true
(i<=7) && (j>=4) true

Amar Nayak
Object Oriented Programming in C++

(i>=6) || (j>=2) true


(i>=6) || (j>=6) true
(i<10) || (j>2) true
(i<=7) || (j>=4) true
!(i<5) true
!(i<=3) true
!(i<(j+1)) true

(6) Increment and decrement operator: The increment operators increment its operand
by one (1) where as decrement operator decreases the value of its operand by one (1).
++ Increment operator
-- Decrement operator

i=5;
i=i+1 is equivalent to i++ =6
i=5;
i=i-1 is equivalent to i-- =4

Increment and decrement operators can be used in two ways.


(1) Preincrement (3)Predecrement
(2) Postincreament (4)Postdecrement

Preincrement: If the increment operator precedes the operator (ex ++i) then it is
preincrement. In preincrement the operand will be altered in the value before it is used
within the program.
Postincrement: If the increment operator follows the operator (ex i++) then it is
postincrement. In postincrement the operand will be altered in the value after it is used
within the program

Predecrement: If the decrement operator precedes the operator (ex --i) then it is
predecrement. In predecrement the operand will be altered in the value before it is used
within the program.
Postdecrement: If the decrement operator follows the operator (ex i--) then it is
postdecrement. In postdecrement the operand will be altered in the value after it is used
within the program.

(7) Conditional Operator or ternary operator:- ? :


Syntax
expression1 ? expression2 : expression3

expression1 is evaluated first. It is usually a conditional expression that use relational or


logical operators. If expression1 is true then expression2 will be evaluated and this
becomes the value of the condition expression.
If expression1 is false then expression3 is evaluated and this becomes the value of
conditional expression.

Amar Nayak
Object Oriented Programming in C++

This operator is replacement for if- else statement


Example

(a>5) ? cout<<“\na is greater than 5 “ : cout<<“\na is less than 5”;

(8) Bitwise Operator

Some applications required the manipulation of individual bits. Bitwise operator operates on bits.
Bitwise operator operates only on int and char type data.

Bitwies operator Meaning


& Bitwise AND
| Bitwise OR
~ Bitwise Compliment
^ Bitwise XOR
>> Bitwise Right Shift
<< Bitwise Left Shift
All operators except ~ (Bitwise Compliment) are binary operator

&, |, ^ operators: Each of these operators requires two integer type operands. The operations are
carried out independently on each pair of corresponding bits within the operands The LSB within
the two operands will be compared, then next LSB and so on until all of the bits have been
compared.
(1) Bitwise AND (&) expression will return a 1 if both bits have a value 1 (i.e. both bits are
true.) otherwise it will return a value 0.
(2) Bitwise OR ( | ) expression will return a 1 if one or more of the bits have a value 1 (i.e.
one or both bits are true.) otherwise it will return a value 0.
(3) Bitwise XOR ( ^ ) expression will return a 1 if one of the bits have a value 1 and the
other has a value of 0(i.e. one bit is true and one bit is false.) otherwise it will return a
value 0.

If a and b represent the corresponding bits within the first and second operands, respectively

a b a&b a|b a^b


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Amar Nayak
Object Oriented Programming in C++

Right shift and Left shift:


The two bitwise operators are Right shift and left shift. Each operator requires two
operands. The first is an integer type operand that represents the bits to be shifted. The
second is an unsigned integer that indicates number of positions on left or right to be
shifted.
Right Shift ( >>): This operator shifts its operand to the right. The number of position to
be shifted to the right is given by second operand.
Ex.
a=21;
a>>2;
21 is represented in binary as
0 0 0 1 0 1 0 1

0 0 0 0 0 1 0 1
answer is 5

Left Shift ( <<): This operator shifts its operand to the left. The number of position to be
shifted to the left is given by second operand.
Ex.
a=21;
a<<2;
21 is represented in binary as
0 0 0 1 0 1 0 1

0 1 0 1 0 1 0 0
answer is 84

Bitwise Complement Operator or One's complement operator (~) : is a unary


operator that inverts (reversed) the bits so 1's becomes 0's and 0's becomes 1's. This
opearotor always precedes its operand. The operand must be integer type of quantity.
+0
-1

Steps of finding Bitwise compliment.


(1) First convert number into their binary equivalent.
(2) Inverts all the bits excepts first digit.
(3) Take one's compliment.
(4) Take 2's compliment.

If first digit is 1 then the number is negative.


If first digit is 0 then the number is positive.

Ex
Find Compliment of 4

Amar Nayak
Object Oriented Programming in C++

0 0 0 0 0 1 0 0

0 1 1 1 1 0 1 1

1 0 0 0 0 1 0 0
+ 1
------------------------------------------------------------
[1] 0 0 0 0 1 0 1

The answer is -5 .

Bitwise Assignment operator:


&=, |=, ^=, <<=, >>=

a=a&2; is equivalent to a&=2;


a=a|2; is equivalent to a|=2;
a=a^2; is equivalent to a^=2;
a=a<<2; is equivalent to a<<=2;
a=a>>2; is equivalent to a>>=2;

sizeof() operator: gives the size of its operand in bytes.


Syntax
Sizeof(operand);

Example:
Sizeof(int) 2 byte
Float b;
Sizeof(b); 4 bytes

Ope rator precedence

Ope rator Description Example Associability

() Function call pow(x,y)


[] Array element reference arr[10]
-> Pointer to structure e->name L-R
. Structure element reference e.name

- Unary minus -a
++ Increment a++
-- Decrement a--
! Not !(a>5)
~ One’s Compliment ~2 R-L

Amar Nayak
Object Oriented Programming in C++

* Value at address *ptr


& Address of &a
sizeof() Size in bytes sizeof(int)
(type) Type Convertion (float)total/n

* Multiplication a*b
/ Division a/b L-R
% Modulus a%b

+ Addition a+b L-R


- Subtraction a-b

>> Right Shift a>>3 L-R


<< Left Shift a<<2

> Greater than a>4


< Less than a<6
>= Greater than or equal to a>=4
<= Less than or equal to a<=6 L-R
== Equal to a==b
!= Not equal to a!=b

& Bitwise AND a&3 L-R


^ Bitwise XOR a^b

| Bitwise OR a |b
&& Logical AND a>b && a>c
|| Logical OR i>4||j<6 L-R
?: Conditional Operator a>b ? 10 : 20

= *= /= Assignment operator cnt += 3


%= += a*=5
-= &= R-L
^= |=
<<=
>>=

, Comma operator i=10,j=9 L-R

L-R means left to right


R-L means right to left

Amar Nayak
Object Oriented Programming in C++

Operators in the same box have the same precedence. Associativity determines order of
evaluation for operators with the same precedence For ex a=b=c;
Is evaluated right to left as a=(b=c);

Amar Nayak

You might also like