SlideShare a Scribd company logo
DATA TYPES
and
OPERATORS IN C++
IDENTIFIERS
• Identifiers are the names of things that appear
in the program. Such names are called as identifiers.
All identifiers must obey the following rules:
1. It is a sequence of characters that consists of
letters, digits and underscores.
2. It must start with a letter or underscore. It can
not start with a digit.
3. It cannot be a reserved word.
4. It can be of any length.
C++ is a case-sensitive so area, Area and AREA are
All different identifiers.
VARIABLES
• Variables are used to store values so that these
Values can be used later in the program.
• They are called variables because their values can
be changed.
• The values to variables can be reassigned also.
• Example: radius=1.0; //compute 1st area
area= radius*radius*3.14;
cout<<area;
radius=2.0; //compute 2nd area
area=radius*radius*3.14;
cout<<area;
VARIABLE DECLARATION
• To use a variable, you declare it by telling the
compiler its name and what type of data it represents.
This is called Variable Declaration.
datatype variable_name;
It tells the compiler to allocate the appropriate
memory space for the variable based on its data type.
int count;// declare count to be an integer variable
int count=1; OR //2 statements are equivalent to
int count=1;
DATATYPE
• Datatype means what are the various types of
data that a variable can hold.
• The compiler allocates memory space to store
each variable according to its datatype.
Imagine this Notebook as a variable
NoteBook name
C++
Initially book
Is empty means
You have not
defined the variable
Data Types
Data types are means to identify the type
of data and associated operation of
handling it .
C++ has three types of data types :-
• Built in data type.
• Derived data type.
• User defined data type.
Chapter 2.datatypes and operators
Chapter 2.datatypes and operators
Built in data type
Built in data types are those who are
not composed of other data types.
There are mainly 5 kinds of build in
data type :-
1.int type.
2.char type.
3.float type.
4.double type.
5.void type.
Void data type
The void data type specifies an
empty set of values .
It is used as the return type for
functions that do not return a
value.
Int data type
Integers are whole number such as 5,39,-
1917,0 etc.
they have no fractional part.
Integers can have positive as well as
negative value .
An identifiers declared as int cannot have
fractional part.
Each integer comes in two flavors:
1. Signed
2. Unsigned
• Half of the numbers represented by signed short
Are positive and other half are negative.
• All numbers represented by short are non-negative.
• If you know that value stored in a variable is
always negative, declare it as unsigned.
• The size of datatype may vary depending on the
compiler.
Char data type
characters can store any member of
the c++ implementation’s basic
character set .
An identifiers declared as char
becomes character variable .
char set is often said to be a integer
type .
Float data type
A number having a fractional part is
a floating-point number .
the decimal point shows that it is a
floating-point number not an integer.
for ex-31.0 is a floating-point
number not a integer but simply 31 is
a integer.
Double data type
It is used for handling floating-point
numbers.
It occupies twice as memory as float.
It is used when float is too small or
insufficiently precise.
Data type modifiers
The basic data type has modifiers
preceding them .we use modifier to alter
the meaning of the base type to fit various
situation more precisely.
There are 3 types of modifiers:-
1.Integer type modifiers.
2.Character type modifiers .
3.Float type modifiers .
Integer type modifiers
By using different number of bytes to
store values , c++ offers 3 types of
integers :short , int and long that can
represent upto three different integer
sizes.
A short integer is at least 2 bytes .
A int integer is at least as big as short .
A long integer is at least 4 bytes .
TYPE APPROXIMATE
SIZE(IN BYTES)
MINIMAL RANGE
short 2 -32768 to 32767
Unsigned short 2 0 to 65,535
Signed short 2 same as short
Int 2 -32768 to 32767
Unsigned int 2 0 to 65,535
Signed int 2 same as int
Long 4 -2,147,483,648 to
2,147,483,647
Unsigned long 4 0 to 4,294,967,295
character type modifiers
The char type can also be signed or
unsigned .
The unsigned char represent the range 0
to 255.
The signed char represent the range -128
to 127.
Type Approximate
size(in bytes)
Minimal
range
Char 1 -128 to 127
Unsigned char 1 0 to 255
Signed char 1 same as char
Floating-point type modifiers
C++ has three floating-point types : float
, double and long double.
float type occupies 4 byte.
Double occupies 8 byte .
Long double occupies 10 byte.
TYPE approximate
size(in bytes)
Digit of
precision
Float 4 7
Double 8 15
Long double 10 19
Derived Data Types
From the built in data types other types
can be derived called derived data types.
There are 5 types of derived data
types :-
1.Arrays.
2.Functions.
3.Pointers.
4.References.
5.Constant.
ARRAYS
Values of similar type stored in continuous
memory locations.
int a[10]; char string[3]=“xyz”;
Array can be one dimensional , two
dimensional , multi dimensional.
For ex-float a[3]; //declares array of three
floats :a[0],a[1],a[2].
Int b[2][4]; //declares a 2 dimension array
of integer:b[0][0], b[0][1], b[0][2], b[0][3],
b[1][0], b[1][1], b[1][2], b[1][3].
Functions
Set of statements to perform specific
tasks.
A piece of code that perform specific
task.
Introduces modularity in the code.
Reduces the size of program.
C++ has added many new features
to the functions to make them more
reliable and flexible.
It can be overloaded.
 Function declaration
◦ return-type function-name (argument-list);
◦ void show();
◦ float volume(int x,float y,float z);
 Function definition
return-type function-name(argument-list)
{
statement1;
statement2;
}
 Function call
◦ function-name(argument-list);
◦ volume(a,b,c);
Pointers
Pointers can be declared and initialized as in
C.
int * ip; // int pointer
ip = &x; // address of x assigned to ip
*ip = 10; // 10 assigned to x through
indirection
References
A reference is an alternative name of
an object.
Constant
A constant is a data item whose data value
can never change during the program run.
Classes and Objects
 Class is a way to bind the data and
procedures that operates on data.
 Class declaration:
class class_name
{
private:
variable declarations;//class
function declarations;//members
public:
variable declarations;//class
function declarations;//members
};//Terminates with a semicolon
Classes and Objects
 Class members that have been declared as
private can be accessed only from within
the class.
 Public class members can be accessed
from outside the class also.
 Supports data-hiding and data
encapsulation features of OOP.
Classes and Objects
 Objects are run time instance of a class.
 Class is a representation of the object, and
Object is the actual run time entity which
holds data and function that has been
defined in the class.
 Object declaration:
class_name obj1;
class_name obj2,obj3;
class class_name
{……}obj1,obj2,obj3;
Structures
 Structures Revisited
◦ Makes convenient to handle a group of logically
related data items.
struct student //declaration
{
char name[20];
int roll_number;
float total_marks;
};
struct student A;// C declaration
student A; //C++ declaration
A.roll_number=999;
A.total_marks=595.5;
Final_Total=A.total_marks + 5;
Structures in C++
 Can hold variables and functions as
members.
 Can also declare some of its members as
‘private’.
 C++ introduces another user-defined type
known as ‘class’ to incorporate all these
extensions.
Unions
 A union is like a record
◦ But the different fields take up the same space
within memory
union foo {
int i;
float f;
char c[4];
}
 Union size is 4 bytes!
Operators
• C supports rich set of operators.
• An operator is a symbol that tells the compiler to
perform certain mathematical or logical
manipulations.
• Operators are used in programs to manipulate data
and variables.
Types of Operators
.
Operators
TERNA
RY
BINARY
UNARY
Unary Operators
• A unary operator is one which operates on one value
or operand. The minus sign (-) plays a dual role, it is
used for subtraction as a binary operator and for
negation as a unary operator. This operator has a
precedence higher than the rest of the arithmetic
operators.
• result = -x * y;
• in the above expression, if x has a value 20 and y has
a value 2, then result will contain a negative value of
40 which is -40.
1/28/2016
Binary and Ternary Operators
• Binary operators?
• Ternary operators?
Types of ‘C’ operators
1. UNARY OPERATORS
– Increment and Decrement operators
2. BINARY OPERATORS
– Arithmetic operators
– Relational operators
– Logical operators
– Assignment operators
– Bitwise operators
3. TERNARY OPERATORS
– Conditional operator
4. Other operators
– Scope resolution operator ::
– Insertion operator <<
– Extraction operator >>
– new (memory allocation operator)
– delete (memory release operator)
– setw
– endl (line feed operator)
setw operator specifies the field width
Example: setw(5)
Memory
management
operators
Manipulators
(used to format data
display)
1. Arithmetic operator
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division
1/28/2016
2. Relational operator
C supports six Relational Operators
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
• Suppose that a and b are integer variables whose
values are 100 and 4, respectively. Several arithmetic
expressions involving these variables are shown
below, together with their resulting values.
1/28/2016
a=100, b=4
3.Logical operators
• Logical Operators
– &&, || and ! are the three logical operators.
– expr1 && expr2 has a value 1 if expr1 and expr2 both are
nonzero i.e. if both have values 1(true)
– expr1 || expr2 has a value 1 if either expr1 or expr2 or both
are nonzero i.e 1(true).
– !expr1 has a value 1 if expr1 is zero else 0.
– Example
– if ( marks >= 40 && attendance >= 75 ) grade = ‘P’
– If ( marks < 40 || attendance < 75 ) grade = ‘N’
1/28/2016
Relational And Logical Operators
True
!True i.e !1 =0
4. Assignment operators
• Assignment operators are used to assign the result of an expression
to a variable.
• C has a set of ‘shorthand’ assignment operator :
variable name =expression;
Exam - a + = 3;
a = a + 3;
Both are same.
Left side must be an object that
can receive a value
Shorthand Assignment operators
Simple assignment
operator
Shorthand operator
a = a+1 a + =1
a = a-1 a - =1
a = a* (m+n) a * = m+n
a = a / (m+n) a / = m+n
a = a %b a %=b
5. Increment and decrement operators.
• Increment Operator ++
a=10;
a++ =10 (post increment but in memory its value is 11)
when you will again call value of a, then a=11
• Decrement Operator --
b=5;
b-- =4 in memory but output will be 5; when you will call b
again then value will be 4.
• Similarly increment and decrement operator is used in
subscripted variables as:
a[ i++]=5;
is equivalent to
a[ i]=5;
i=i+1;
6. Conditional operator
• The conditional expression can be used as shorthand for
some if-else statements. It is a ternary operator.
• This operator consist of two symbols: the question mark
(?) and the colon (:).
for example:
a=11;
b=20;
x=(a>b) ? a : b;
Identifier
Test Expression
Exp 1: Exp 2
7. Bitwise operator
• C supports bitwise operators for manipulation of data at bit
level.
• Bitwise operators may not be applied to float or double.
• Bitwise operators are as follows:
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ One’s Complements (bitwise NOT)
int a = 205; // In binary: 11001101
int b = 45; // In binary: 00101101
int c = a | b; // In binary: 11101101
println(c); // Prints "237", the decimal equivalent to 11101101
BINARY OR
11001101
00101101
11101101RESULT
OR means any one
input must be true to
get output as true
LEFT SHIFT <<
int m = 1 << 3
Output will be 8
_ _ _ 1
_ _ 1 _
_ 1_ _
1 _ _ _
Input
Output: 1000 in binary
So 8 in decimal
1<< 1st bit
1<< 2nd bit
1<< 3rd bit
8. Special operator
• C supports some special operators such as:
comma operator “,”
int a=5,b=6;
size of operator “sizeof()”
Address operator “&”
pointer operator “*”
member selection operator “. and -> ”
8. Special operator
• Scope Resolution Operator
– :: is a scope resolution operator
– Scope resolution operator(::) is used to define a
function outside a class or when we want to use a
global variable but also has a local variable with
same name.
– Why need?
– When local variable and global variable are having
same name, local variable gets the priority. C++
allows flexibility of accessing both the variables
through a scope resolution operator.
8. Special operator
• Scope Resolution Operator
– For example
8. Special operator
• Scope Resolution Operator
– For example
– Class MyClass
{
int n1, n2;
public:
{
void func1(); //Function Declaration
}
};
public void MyClass::func1()
{
// Function Code
}
Use of Scope Resolution
Operator to write function
definition outside class
definition
Precedence of operators
• Precedence establishes the hierarchy of one set of operators
over another when an arithmetic expression has to be
evaluated.
• It refers to the order in which c evaluates operators.
• The evaluation of operators in an arithmetic
expression takes place from left to right for operators having
equal precedence .
Precedence of operators
BODMAS RULE-
Brackets of Division Multiplication Addition Subtraction
Brackets will have the highest precedence and have to be evaluated
first, then comes of , then comes division, multiplication, addition
and finally subtraction.
C language uses some rules in evaluating the expressions and they r
called as precedence rules or sometimes also referred to as
hierarchy of operations, with some operators with highest
precedence and some with least.
The 2 distinct priority levels of arithmetic operators in c are-
Highest priority : * / %
Lowest priority : + -
Associativity of operators
• Associativity tells how an operator associates with its operands.
for eg:
Associativity means whether an expression like x R y R z
(where R is a operator such as + or <= ) should be evaluated
`left-to-right' i.e. as (x R y) R z or `right-to-left' i.e. as x R (y
R z)
The assignment operator = associates from right to left.
• Hence the expression on the right is evaluated first and its value is
assigned to the variable on the left.
• Associativity also refers to the order in which c evaluates operators in
an expression having same precedence.
• Such type of operator can operate either left to right or vice versa.
• The operator () function call has highest precedence & the comma
operator has lowest precedence
• All unary , conditional & assignment operators associate RIGHT
TO LEFT .
• All other remaining operators associate LEFT TO RIGHT
Rules for evaluation of expression
1. First parenthesized sub expression from left to right are
evaluated.
2. If parentheses are nested, the evaluation begins with the
innermost sub expression
3. The precedence rule is applied in determining the order of
application of operators in evaluating sub expressions
4. The associatively rule is applied when 2 or more operators
of the same precedence level appear in a sub expression.
5. Arithmetic expressions are evaluated from left to right using
the rules of precedence
6. When parentheses are used, the expressions within parentheses
assume highest priority
Hierarchy of operators
Operator Description Associativity
( ), [ ] Function call, array element
reference
Left to Right
+, -, ++, - -
,!,~,*,&
Unary plus, minus, increment,
decrement, logical negation,
1’s complement, pointer
reference, address
Right to Left
*, / , % Multiplication, division,
modulus
Left to Right
Type Casting
• Type casting is a way to convert a variable from one
data type to another data type.
• When variables and constants of different types are
combined in an expression then they are converted
to same data type. The process of converting one
predefined type into another is called type
conversion.
DATATYPE 1 DATATYPE 2
Implicit Type Casting
• When the type conversion is performed
automatically by the compiler without programmers
intervention, such type of conversion is known as
implicit type conversion or type promotion.
• For example when you add values having different
data types, both values are first converted to the
same type: when a short int value and an int value
are added together, the short int value is converted
to the int type.
1/28/2016
int + short int  int
• C does implicit DataType conversion when the need
arises.
• When a floating point value is assigned to an integer
variable, the decimal portion is truncated.
When a value 156.43 is assigned to an integer variable,
156 is stored and the decimal portion is discarded.
If an integer 200 is assigned to a floating point variable,
the value is converted to 200.000000 and stored.
(integer type variable)a= 156.43  156.43
(float type variable) float b = 200  200.000000
1/28/2016
Explicit Type Casting
• The type conversion performed by the programmer
by posing the data type of the expression of specific
type is known as explicit type conversion.
• Type casting in c is done in the following form:
(data_type) expression;
where, data_type is any valid c data type, and
expression may be constant, variable or expression.
For example,
x=(int)a+b*d;
Example
#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %fn",
mean );
}
Output is
Value of mean : 3.400000
It should be noted here
that the cast operator has
precedence over division,
so the value of sum is first
converted to type double
and finally it gets divided
by count yielding a double
value.
Rules for Implicit Type Casting
The following rules have to be followed while
converting the expression from one type to
another to avoid the loss of information:
• All integer types to be converted to float.
• All float types to be converted to double.
• All character types to be converted to integer.
Thank you
1/28/2016

More Related Content

What's hot (20)

PPTX
classes and objects in C++
HalaiHansaika
 
PDF
Managing I/O in c++
Pranali Chaudhari
 
PPTX
Exception handling c++
Jayant Dalvi
 
PPTX
Union in c language
tanmaymodi4
 
PPTX
Loc and function point
Mitali Chugh
 
PDF
Dbms 14: Relational Calculus
Amiya9439793168
 
PDF
Symbol table in compiler Design
Kuppusamy P
 
PPTX
Union in C programming
Kamal Acharya
 
PPTX
Polymorphism In c++
Vishesh Jha
 
PPT
Swing and AWT in java
Adil Mehmoood
 
PPT
Input and output in C++
Nilesh Dalvi
 
PPT
Strings Functions in C Programming
DevoAjit Gupta
 
PPTX
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
PPTX
OOPS In JAVA.pptx
Sachin33417
 
PPT
BINARY TREE REPRESENTATION.ppt
SeethaDinesh
 
PPT
File handling in c
David Livingston J
 
PPSX
Modules and packages in python
TMARAGATHAM
 
PPT
Data types and Operators
raksharao
 
PPTX
Storage classes in C
Self employed
 
PPTX
Attributes of output Primitive
SachiniGunawardana
 
classes and objects in C++
HalaiHansaika
 
Managing I/O in c++
Pranali Chaudhari
 
Exception handling c++
Jayant Dalvi
 
Union in c language
tanmaymodi4
 
Loc and function point
Mitali Chugh
 
Dbms 14: Relational Calculus
Amiya9439793168
 
Symbol table in compiler Design
Kuppusamy P
 
Union in C programming
Kamal Acharya
 
Polymorphism In c++
Vishesh Jha
 
Swing and AWT in java
Adil Mehmoood
 
Input and output in C++
Nilesh Dalvi
 
Strings Functions in C Programming
DevoAjit Gupta
 
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
OOPS In JAVA.pptx
Sachin33417
 
BINARY TREE REPRESENTATION.ppt
SeethaDinesh
 
File handling in c
David Livingston J
 
Modules and packages in python
TMARAGATHAM
 
Data types and Operators
raksharao
 
Storage classes in C
Self employed
 
Attributes of output Primitive
SachiniGunawardana
 

Viewers also liked (20)

PPTX
Operators
moniammu
 
PPT
New operator and methods.15
myrajendra
 
PPTX
Classes and objects
rajveer_Pannu
 
PPT
Unit 5 Java
arnold 7490
 
PPT
Unit 4 Java
arnold 7490
 
PPT
Console Io Operations
archikabhatia
 
PDF
Template at c++
Lusain Kim
 
PPT
Unit 1 Java
arnold 7490
 
PPTX
Managing console
Shiva Saxena
 
PPTX
constructor & destructor in cpp
gourav kottawar
 
PPTX
Mca ii dfs u-1 introduction to data structure
Rai University
 
PPT
Unit 2 Java
arnold 7490
 
PPTX
Templates in c++
Mayank Bhatt
 
DOCX
C++ Template
Saket Pathak
 
PPT
Unit 3 Java
arnold 7490
 
PPT
Operators in C++
Sachin Sharma
 
PPT
08 c++ Operator Overloading.ppt
Tareq Hasan
 
PPTX
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
PPTX
Templates in C++
Tech_MX
 
PPT
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
cprogrammings
 
Operators
moniammu
 
New operator and methods.15
myrajendra
 
Classes and objects
rajveer_Pannu
 
Unit 5 Java
arnold 7490
 
Unit 4 Java
arnold 7490
 
Console Io Operations
archikabhatia
 
Template at c++
Lusain Kim
 
Unit 1 Java
arnold 7490
 
Managing console
Shiva Saxena
 
constructor & destructor in cpp
gourav kottawar
 
Mca ii dfs u-1 introduction to data structure
Rai University
 
Unit 2 Java
arnold 7490
 
Templates in c++
Mayank Bhatt
 
C++ Template
Saket Pathak
 
Unit 3 Java
arnold 7490
 
Operators in C++
Sachin Sharma
 
08 c++ Operator Overloading.ppt
Tareq Hasan
 
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
Templates in C++
Tech_MX
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
cprogrammings
 
Ad

Similar to Chapter 2.datatypes and operators (20)

PPTX
Data types
Nokesh Prabhakar
 
PDF
2nd PUC Computer science chapter 5 review of c++
Aahwini Esware gowda
 
PPT
C++ data types
pratikborsadiya
 
PPTX
Concept of c data types
Manisha Keim
 
PPTX
Concept Of C++ Data Types
k v
 
PPTX
Data types
Sachin Satwaskar
 
PPT
Data Handling
Praveen M Jigajinni
 
PPTX
Object oriented programming 8 basics of c++ programming
Vaibhav Khanna
 
PPT
C++ chapter 2
SHRIRANG PINJARKAR
 
PPTX
OOPS (object oriented programming) unit 1
AnamikaDhoundiyal
 
PPTX
BASIC CONCEPTS OF C++ CLASS 12
Dev Chauhan
 
PPTX
Lecture 2 variables
Tony Apreku
 
PPTX
additional.pptx
Yuvraj994432
 
PDF
Data types, operators and control structures unit-2.pdf
gurpreetk8199
 
DOC
Data type
Isha Aggarwal
 
PPT
Key Concepts of C++ computer language.ppt
AjayLobo1
 
PDF
Object Oriented Programming Short Notes for Preperation of Exams
MuhammadTalha436
 
PPT
5-Lec - Datatypes.ppt
AqeelAbbas94
 
Data types
Nokesh Prabhakar
 
2nd PUC Computer science chapter 5 review of c++
Aahwini Esware gowda
 
C++ data types
pratikborsadiya
 
Concept of c data types
Manisha Keim
 
Concept Of C++ Data Types
k v
 
Data types
Sachin Satwaskar
 
Data Handling
Praveen M Jigajinni
 
Object oriented programming 8 basics of c++ programming
Vaibhav Khanna
 
C++ chapter 2
SHRIRANG PINJARKAR
 
OOPS (object oriented programming) unit 1
AnamikaDhoundiyal
 
BASIC CONCEPTS OF C++ CLASS 12
Dev Chauhan
 
Lecture 2 variables
Tony Apreku
 
additional.pptx
Yuvraj994432
 
Data types, operators and control structures unit-2.pdf
gurpreetk8199
 
Data type
Isha Aggarwal
 
Key Concepts of C++ computer language.ppt
AjayLobo1
 
Object Oriented Programming Short Notes for Preperation of Exams
MuhammadTalha436
 
5-Lec - Datatypes.ppt
AqeelAbbas94
 
Ad

More from Jasleen Kaur (Chandigarh University) (19)

PPTX
Graphs data structures
Jasleen Kaur (Chandigarh University)
 
PPTX
B+ trees and height balance tree
Jasleen Kaur (Chandigarh University)
 
PDF
Operating system notes pdf
Jasleen Kaur (Chandigarh University)
 
PPTX
Priority Based Congestion Avoidance Hybrid Scheme published in IEEE
Jasleen Kaur (Chandigarh University)
 
PDF
03 function overloading
Jasleen Kaur (Chandigarh University)
 
PDF
Remote desktop connection
Jasleen Kaur (Chandigarh University)
 
PPTX
Operators in C Programming
Jasleen Kaur (Chandigarh University)
 
PPTX
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
PPTX
Calculating garbage value in case of overflow
Jasleen Kaur (Chandigarh University)
 
PPTX
License Plate recognition
Jasleen Kaur (Chandigarh University)
 
PPTX
Afforestation environmental issue
Jasleen Kaur (Chandigarh University)
 
PPTX
Data aggregation in wireless sensor networks
Jasleen Kaur (Chandigarh University)
 
Graphs data structures
Jasleen Kaur (Chandigarh University)
 
B+ trees and height balance tree
Jasleen Kaur (Chandigarh University)
 
Operating system notes pdf
Jasleen Kaur (Chandigarh University)
 
Priority Based Congestion Avoidance Hybrid Scheme published in IEEE
Jasleen Kaur (Chandigarh University)
 
03 function overloading
Jasleen Kaur (Chandigarh University)
 
Remote desktop connection
Jasleen Kaur (Chandigarh University)
 
Operators in C Programming
Jasleen Kaur (Chandigarh University)
 
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
Calculating garbage value in case of overflow
Jasleen Kaur (Chandigarh University)
 
License Plate recognition
Jasleen Kaur (Chandigarh University)
 
Afforestation environmental issue
Jasleen Kaur (Chandigarh University)
 
Data aggregation in wireless sensor networks
Jasleen Kaur (Chandigarh University)
 

Recently uploaded (20)

PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PPTX
infertility, types,causes, impact, and management
Ritu480198
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Difference between write and update in odoo 18
Celine George
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Introduction presentation of the patentbutler tool
MIPLM
 
Horarios de distribución de agua en julio
pegazohn1978
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
infertility, types,causes, impact, and management
Ritu480198
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
Introduction to Indian Writing in English
Trushali Dodiya
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
epi editorial commitee meeting presentation
MIPLM
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 

Chapter 2.datatypes and operators

  • 2. IDENTIFIERS • Identifiers are the names of things that appear in the program. Such names are called as identifiers. All identifiers must obey the following rules: 1. It is a sequence of characters that consists of letters, digits and underscores. 2. It must start with a letter or underscore. It can not start with a digit. 3. It cannot be a reserved word. 4. It can be of any length. C++ is a case-sensitive so area, Area and AREA are All different identifiers.
  • 3. VARIABLES • Variables are used to store values so that these Values can be used later in the program. • They are called variables because their values can be changed. • The values to variables can be reassigned also. • Example: radius=1.0; //compute 1st area area= radius*radius*3.14; cout<<area; radius=2.0; //compute 2nd area area=radius*radius*3.14; cout<<area;
  • 4. VARIABLE DECLARATION • To use a variable, you declare it by telling the compiler its name and what type of data it represents. This is called Variable Declaration. datatype variable_name; It tells the compiler to allocate the appropriate memory space for the variable based on its data type. int count;// declare count to be an integer variable int count=1; OR //2 statements are equivalent to int count=1;
  • 5. DATATYPE • Datatype means what are the various types of data that a variable can hold. • The compiler allocates memory space to store each variable according to its datatype. Imagine this Notebook as a variable NoteBook name C++ Initially book Is empty means You have not defined the variable
  • 6. Data Types Data types are means to identify the type of data and associated operation of handling it . C++ has three types of data types :- • Built in data type. • Derived data type. • User defined data type.
  • 9. Built in data type Built in data types are those who are not composed of other data types. There are mainly 5 kinds of build in data type :- 1.int type. 2.char type. 3.float type. 4.double type. 5.void type.
  • 10. Void data type The void data type specifies an empty set of values . It is used as the return type for functions that do not return a value.
  • 11. Int data type Integers are whole number such as 5,39,- 1917,0 etc. they have no fractional part. Integers can have positive as well as negative value . An identifiers declared as int cannot have fractional part.
  • 12. Each integer comes in two flavors: 1. Signed 2. Unsigned • Half of the numbers represented by signed short Are positive and other half are negative. • All numbers represented by short are non-negative. • If you know that value stored in a variable is always negative, declare it as unsigned. • The size of datatype may vary depending on the compiler.
  • 13. Char data type characters can store any member of the c++ implementation’s basic character set . An identifiers declared as char becomes character variable . char set is often said to be a integer type .
  • 14. Float data type A number having a fractional part is a floating-point number . the decimal point shows that it is a floating-point number not an integer. for ex-31.0 is a floating-point number not a integer but simply 31 is a integer.
  • 15. Double data type It is used for handling floating-point numbers. It occupies twice as memory as float. It is used when float is too small or insufficiently precise.
  • 16. Data type modifiers The basic data type has modifiers preceding them .we use modifier to alter the meaning of the base type to fit various situation more precisely. There are 3 types of modifiers:- 1.Integer type modifiers. 2.Character type modifiers . 3.Float type modifiers .
  • 17. Integer type modifiers By using different number of bytes to store values , c++ offers 3 types of integers :short , int and long that can represent upto three different integer sizes. A short integer is at least 2 bytes . A int integer is at least as big as short . A long integer is at least 4 bytes .
  • 18. TYPE APPROXIMATE SIZE(IN BYTES) MINIMAL RANGE short 2 -32768 to 32767 Unsigned short 2 0 to 65,535 Signed short 2 same as short Int 2 -32768 to 32767 Unsigned int 2 0 to 65,535 Signed int 2 same as int Long 4 -2,147,483,648 to 2,147,483,647 Unsigned long 4 0 to 4,294,967,295
  • 19. character type modifiers The char type can also be signed or unsigned . The unsigned char represent the range 0 to 255. The signed char represent the range -128 to 127.
  • 20. Type Approximate size(in bytes) Minimal range Char 1 -128 to 127 Unsigned char 1 0 to 255 Signed char 1 same as char
  • 21. Floating-point type modifiers C++ has three floating-point types : float , double and long double. float type occupies 4 byte. Double occupies 8 byte . Long double occupies 10 byte.
  • 22. TYPE approximate size(in bytes) Digit of precision Float 4 7 Double 8 15 Long double 10 19
  • 23. Derived Data Types From the built in data types other types can be derived called derived data types. There are 5 types of derived data types :- 1.Arrays. 2.Functions. 3.Pointers. 4.References. 5.Constant.
  • 24. ARRAYS Values of similar type stored in continuous memory locations. int a[10]; char string[3]=“xyz”; Array can be one dimensional , two dimensional , multi dimensional. For ex-float a[3]; //declares array of three floats :a[0],a[1],a[2]. Int b[2][4]; //declares a 2 dimension array of integer:b[0][0], b[0][1], b[0][2], b[0][3], b[1][0], b[1][1], b[1][2], b[1][3].
  • 25. Functions Set of statements to perform specific tasks. A piece of code that perform specific task. Introduces modularity in the code. Reduces the size of program. C++ has added many new features to the functions to make them more reliable and flexible. It can be overloaded.
  • 26.  Function declaration ◦ return-type function-name (argument-list); ◦ void show(); ◦ float volume(int x,float y,float z);  Function definition return-type function-name(argument-list) { statement1; statement2; }  Function call ◦ function-name(argument-list); ◦ volume(a,b,c);
  • 27. Pointers Pointers can be declared and initialized as in C. int * ip; // int pointer ip = &x; // address of x assigned to ip *ip = 10; // 10 assigned to x through indirection
  • 28. References A reference is an alternative name of an object. Constant A constant is a data item whose data value can never change during the program run.
  • 29. Classes and Objects  Class is a way to bind the data and procedures that operates on data.  Class declaration: class class_name { private: variable declarations;//class function declarations;//members public: variable declarations;//class function declarations;//members };//Terminates with a semicolon
  • 30. Classes and Objects  Class members that have been declared as private can be accessed only from within the class.  Public class members can be accessed from outside the class also.  Supports data-hiding and data encapsulation features of OOP.
  • 31. Classes and Objects  Objects are run time instance of a class.  Class is a representation of the object, and Object is the actual run time entity which holds data and function that has been defined in the class.  Object declaration: class_name obj1; class_name obj2,obj3; class class_name {……}obj1,obj2,obj3;
  • 32. Structures  Structures Revisited ◦ Makes convenient to handle a group of logically related data items. struct student //declaration { char name[20]; int roll_number; float total_marks; }; struct student A;// C declaration student A; //C++ declaration A.roll_number=999; A.total_marks=595.5; Final_Total=A.total_marks + 5;
  • 33. Structures in C++  Can hold variables and functions as members.  Can also declare some of its members as ‘private’.  C++ introduces another user-defined type known as ‘class’ to incorporate all these extensions.
  • 34. Unions  A union is like a record ◦ But the different fields take up the same space within memory union foo { int i; float f; char c[4]; }  Union size is 4 bytes!
  • 35. Operators • C supports rich set of operators. • An operator is a symbol that tells the compiler to perform certain mathematical or logical manipulations. • Operators are used in programs to manipulate data and variables.
  • 37. Unary Operators • A unary operator is one which operates on one value or operand. The minus sign (-) plays a dual role, it is used for subtraction as a binary operator and for negation as a unary operator. This operator has a precedence higher than the rest of the arithmetic operators. • result = -x * y; • in the above expression, if x has a value 20 and y has a value 2, then result will contain a negative value of 40 which is -40. 1/28/2016
  • 38. Binary and Ternary Operators • Binary operators? • Ternary operators?
  • 39. Types of ‘C’ operators 1. UNARY OPERATORS – Increment and Decrement operators 2. BINARY OPERATORS – Arithmetic operators – Relational operators – Logical operators – Assignment operators – Bitwise operators 3. TERNARY OPERATORS – Conditional operator 4. Other operators
  • 40. – Scope resolution operator :: – Insertion operator << – Extraction operator >> – new (memory allocation operator) – delete (memory release operator) – setw – endl (line feed operator) setw operator specifies the field width Example: setw(5) Memory management operators Manipulators (used to format data display)
  • 41. 1. Arithmetic operator + Addition - Subtraction * Multiplication / Division % Modulo division
  • 43. 2. Relational operator C supports six Relational Operators < Is less than <= Is less than or equal to > Is greater than >= Is greater than or equal to == Is equal to != Is not equal to
  • 44. • Suppose that a and b are integer variables whose values are 100 and 4, respectively. Several arithmetic expressions involving these variables are shown below, together with their resulting values. 1/28/2016 a=100, b=4
  • 45. 3.Logical operators • Logical Operators – &&, || and ! are the three logical operators. – expr1 && expr2 has a value 1 if expr1 and expr2 both are nonzero i.e. if both have values 1(true) – expr1 || expr2 has a value 1 if either expr1 or expr2 or both are nonzero i.e 1(true). – !expr1 has a value 1 if expr1 is zero else 0. – Example – if ( marks >= 40 && attendance >= 75 ) grade = ‘P’ – If ( marks < 40 || attendance < 75 ) grade = ‘N’
  • 48. 4. Assignment operators • Assignment operators are used to assign the result of an expression to a variable. • C has a set of ‘shorthand’ assignment operator : variable name =expression; Exam - a + = 3; a = a + 3; Both are same. Left side must be an object that can receive a value
  • 49. Shorthand Assignment operators Simple assignment operator Shorthand operator a = a+1 a + =1 a = a-1 a - =1 a = a* (m+n) a * = m+n a = a / (m+n) a / = m+n a = a %b a %=b
  • 50. 5. Increment and decrement operators. • Increment Operator ++ a=10; a++ =10 (post increment but in memory its value is 11) when you will again call value of a, then a=11 • Decrement Operator -- b=5; b-- =4 in memory but output will be 5; when you will call b again then value will be 4. • Similarly increment and decrement operator is used in subscripted variables as: a[ i++]=5; is equivalent to a[ i]=5; i=i+1;
  • 51. 6. Conditional operator • The conditional expression can be used as shorthand for some if-else statements. It is a ternary operator. • This operator consist of two symbols: the question mark (?) and the colon (:). for example: a=11; b=20; x=(a>b) ? a : b; Identifier Test Expression Exp 1: Exp 2
  • 52. 7. Bitwise operator • C supports bitwise operators for manipulation of data at bit level. • Bitwise operators may not be applied to float or double. • Bitwise operators are as follows: & bitwise AND | bitwise OR ^ bitwise exclusive OR << shift left >> shift right ~ One’s Complements (bitwise NOT)
  • 53. int a = 205; // In binary: 11001101 int b = 45; // In binary: 00101101 int c = a | b; // In binary: 11101101 println(c); // Prints "237", the decimal equivalent to 11101101 BINARY OR 11001101 00101101 11101101RESULT OR means any one input must be true to get output as true
  • 54. LEFT SHIFT << int m = 1 << 3 Output will be 8 _ _ _ 1 _ _ 1 _ _ 1_ _ 1 _ _ _ Input Output: 1000 in binary So 8 in decimal 1<< 1st bit 1<< 2nd bit 1<< 3rd bit
  • 55. 8. Special operator • C supports some special operators such as: comma operator “,” int a=5,b=6; size of operator “sizeof()” Address operator “&” pointer operator “*” member selection operator “. and -> ”
  • 56. 8. Special operator • Scope Resolution Operator – :: is a scope resolution operator – Scope resolution operator(::) is used to define a function outside a class or when we want to use a global variable but also has a local variable with same name. – Why need? – When local variable and global variable are having same name, local variable gets the priority. C++ allows flexibility of accessing both the variables through a scope resolution operator.
  • 57. 8. Special operator • Scope Resolution Operator – For example
  • 58. 8. Special operator • Scope Resolution Operator – For example – Class MyClass { int n1, n2; public: { void func1(); //Function Declaration } }; public void MyClass::func1() { // Function Code } Use of Scope Resolution Operator to write function definition outside class definition
  • 59. Precedence of operators • Precedence establishes the hierarchy of one set of operators over another when an arithmetic expression has to be evaluated. • It refers to the order in which c evaluates operators. • The evaluation of operators in an arithmetic expression takes place from left to right for operators having equal precedence .
  • 60. Precedence of operators BODMAS RULE- Brackets of Division Multiplication Addition Subtraction Brackets will have the highest precedence and have to be evaluated first, then comes of , then comes division, multiplication, addition and finally subtraction. C language uses some rules in evaluating the expressions and they r called as precedence rules or sometimes also referred to as hierarchy of operations, with some operators with highest precedence and some with least. The 2 distinct priority levels of arithmetic operators in c are- Highest priority : * / % Lowest priority : + -
  • 61. Associativity of operators • Associativity tells how an operator associates with its operands. for eg: Associativity means whether an expression like x R y R z (where R is a operator such as + or <= ) should be evaluated `left-to-right' i.e. as (x R y) R z or `right-to-left' i.e. as x R (y R z) The assignment operator = associates from right to left. • Hence the expression on the right is evaluated first and its value is assigned to the variable on the left. • Associativity also refers to the order in which c evaluates operators in an expression having same precedence. • Such type of operator can operate either left to right or vice versa. • The operator () function call has highest precedence & the comma operator has lowest precedence • All unary , conditional & assignment operators associate RIGHT TO LEFT . • All other remaining operators associate LEFT TO RIGHT
  • 62. Rules for evaluation of expression 1. First parenthesized sub expression from left to right are evaluated. 2. If parentheses are nested, the evaluation begins with the innermost sub expression 3. The precedence rule is applied in determining the order of application of operators in evaluating sub expressions 4. The associatively rule is applied when 2 or more operators of the same precedence level appear in a sub expression. 5. Arithmetic expressions are evaluated from left to right using the rules of precedence 6. When parentheses are used, the expressions within parentheses assume highest priority
  • 63. Hierarchy of operators Operator Description Associativity ( ), [ ] Function call, array element reference Left to Right +, -, ++, - - ,!,~,*,& Unary plus, minus, increment, decrement, logical negation, 1’s complement, pointer reference, address Right to Left *, / , % Multiplication, division, modulus Left to Right
  • 64. Type Casting • Type casting is a way to convert a variable from one data type to another data type. • When variables and constants of different types are combined in an expression then they are converted to same data type. The process of converting one predefined type into another is called type conversion. DATATYPE 1 DATATYPE 2
  • 65. Implicit Type Casting • When the type conversion is performed automatically by the compiler without programmers intervention, such type of conversion is known as implicit type conversion or type promotion. • For example when you add values having different data types, both values are first converted to the same type: when a short int value and an int value are added together, the short int value is converted to the int type. 1/28/2016 int + short int  int
  • 66. • C does implicit DataType conversion when the need arises. • When a floating point value is assigned to an integer variable, the decimal portion is truncated. When a value 156.43 is assigned to an integer variable, 156 is stored and the decimal portion is discarded. If an integer 200 is assigned to a floating point variable, the value is converted to 200.000000 and stored. (integer type variable)a= 156.43  156.43 (float type variable) float b = 200  200.000000 1/28/2016
  • 67. Explicit Type Casting • The type conversion performed by the programmer by posing the data type of the expression of specific type is known as explicit type conversion. • Type casting in c is done in the following form: (data_type) expression; where, data_type is any valid c data type, and expression may be constant, variable or expression. For example, x=(int)a+b*d;
  • 68. Example #include <stdio.h> main() { int sum = 17, count = 5; double mean; mean = (double) sum / count; printf("Value of mean : %fn", mean ); } Output is Value of mean : 3.400000 It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value.
  • 69. Rules for Implicit Type Casting The following rules have to be followed while converting the expression from one type to another to avoid the loss of information: • All integer types to be converted to float. • All float types to be converted to double. • All character types to be converted to integer.