SlideShare ist ein Scribd-Unternehmen logo
1 von 70
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.
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Break and continue
Break and continueBreak and continue
Break and continue
 
1. over view and history of c
1. over view and history of c1. over view and history of c
1. over view and history of c
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programming
 
Basic Data Types in C++
Basic Data Types in C++ Basic Data Types in C++
Basic Data Types in C++
 
Forloop
ForloopForloop
Forloop
 
Storage classes in c++
Storage classes in c++Storage classes in c++
Storage classes in c++
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Data types in C language
Data types in C languageData types in C language
Data types in C language
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Structure in c
Structure in cStructure in c
Structure in c
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
C functions
C functionsC functions
C functions
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Tokens in C++
Tokens in C++Tokens in C++
Tokens in C++
 
Control structures in C
Control structures in CControl structures in C
Control structures in C
 

Andere mochten auch

New operator and methods.15
New operator and methods.15New operator and methods.15
New operator and methods.15myrajendra
 
Console Io Operations
Console Io OperationsConsole Io Operations
Console Io Operationsarchikabhatia
 
Template at c++
Template at c++Template at c++
Template at c++Lusain Kim
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cppgourav kottawar
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureRai University
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++gourav kottawar
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 

Andere mochten auch (20)

Operators
OperatorsOperators
Operators
 
New operator and methods.15
New operator and methods.15New operator and methods.15
New operator and methods.15
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
Unit 4 Java
Unit 4 JavaUnit 4 Java
Unit 4 Java
 
Console Io Operations
Console Io OperationsConsole Io Operations
Console Io Operations
 
Template at c++
Template at c++Template at c++
Template at c++
 
Unit 1 Java
Unit 1 JavaUnit 1 Java
Unit 1 Java
 
Managing console
Managing consoleManaging console
Managing console
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
 
Unit 2 Java
Unit 2 JavaUnit 2 Java
Unit 2 Java
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
C++ Template
C++ TemplateC++ Template
C++ Template
 
Unit 3 Java
Unit 3 JavaUnit 3 Java
Unit 3 Java
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 

Ähnlich wie Chapter 2.datatypes and operators

Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C ProgrammingQazi Shahzad Ali
 
Concept Of C++ Data Types
Concept Of C++ Data TypesConcept Of C++ Data Types
Concept Of C++ Data Typesk v
 
cassignmentii-170424105623.pdf
cassignmentii-170424105623.pdfcassignmentii-170424105623.pdf
cassignmentii-170424105623.pdfYRABHI
 
Concept of c data types
Concept of c data typesConcept of c data types
Concept of c data typesManisha Keim
 
Chapter 2: Elementary Programming
Chapter 2: Elementary ProgrammingChapter 2: Elementary Programming
Chapter 2: Elementary ProgrammingEric Chou
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageRakesh Roshan
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++Neeru Mittal
 
variablesfinal-170820055428 data type results
variablesfinal-170820055428 data type resultsvariablesfinal-170820055428 data type results
variablesfinal-170820055428 data type resultsatifmugheesv
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming NeedsRaja Sekhar
 
Introduction to c
Introduction to cIntroduction to c
Introduction to cAjeet Kumar
 
5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt5-Lec - Datatypes.ppt
5-Lec - Datatypes.pptAqeelAbbas94
 
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.pptFatimaZafar68
 
Module 1:Introduction
Module 1:IntroductionModule 1:Introduction
Module 1:Introductionnikshaikh786
 

Ähnlich wie Chapter 2.datatypes and operators (20)

Data types
Data typesData types
Data types
 
C++ data types
C++ data typesC++ data types
C++ data types
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
 
Concept Of C++ Data Types
Concept Of C++ Data TypesConcept Of C++ Data Types
Concept Of C++ Data Types
 
cassignmentii-170424105623.pdf
cassignmentii-170424105623.pdfcassignmentii-170424105623.pdf
cassignmentii-170424105623.pdf
 
Data Handling
Data HandlingData Handling
Data Handling
 
Concept of c data types
Concept of c data typesConcept of c data types
Concept of c data types
 
Python
PythonPython
Python
 
Chapter 2: Elementary Programming
Chapter 2: Elementary ProgrammingChapter 2: Elementary Programming
Chapter 2: Elementary Programming
 
C Language Part 1
C Language Part 1C Language Part 1
C Language Part 1
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
 
variablesfinal-170820055428 data type results
variablesfinal-170820055428 data type resultsvariablesfinal-170820055428 data type results
variablesfinal-170820055428 data type results
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt
 
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.ppt
 
Module 1:Introduction
Module 1:IntroductionModule 1:Introduction
Module 1:Introduction
 
Datatypes
DatatypesDatatypes
Datatypes
 

Mehr von Jasleen Kaur (Chandigarh University)

Priority Based Congestion Avoidance Hybrid Scheme published in IEEE
Priority Based Congestion Avoidance Hybrid Scheme published in IEEE Priority Based Congestion Avoidance Hybrid Scheme published in IEEE
Priority Based Congestion Avoidance Hybrid Scheme published in IEEE Jasleen Kaur (Chandigarh University)
 

Mehr von Jasleen Kaur (Chandigarh University) (19)

Graphs data structures
Graphs data structuresGraphs data structures
Graphs data structures
 
B+ trees and height balance tree
B+ trees and height balance treeB+ trees and height balance tree
B+ trees and height balance tree
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
Static variables
Static variablesStatic variables
Static variables
 
Operating system notes pdf
Operating system notes pdfOperating system notes pdf
Operating system notes pdf
 
Priority Based Congestion Avoidance Hybrid Scheme published in IEEE
Priority Based Congestion Avoidance Hybrid Scheme published in IEEE Priority Based Congestion Avoidance Hybrid Scheme published in IEEE
Priority Based Congestion Avoidance Hybrid Scheme published in IEEE
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Remote desktop connection
Remote desktop connectionRemote desktop connection
Remote desktop connection
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Calculating garbage value in case of overflow
Calculating garbage value in case of overflowCalculating garbage value in case of overflow
Calculating garbage value in case of overflow
 
Final jasleen ppt
Final jasleen pptFinal jasleen ppt
Final jasleen ppt
 
License Plate recognition
License Plate recognitionLicense Plate recognition
License Plate recognition
 
The solar system
The solar system The solar system
The solar system
 
The solar system
The solar systemThe solar system
The solar system
 
Afforestation environmental issue
Afforestation environmental issueAfforestation environmental issue
Afforestation environmental issue
 
Data aggregation in wireless sensor networks
Data aggregation in wireless sensor networksData aggregation in wireless sensor networks
Data aggregation in wireless sensor networks
 
Network security
Network securityNetwork security
Network security
 

Kürzlich hochgeladen

Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 

Kürzlich hochgeladen (20)

Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 

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.
  • 7.
  • 8.
  • 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.