70
DATA TYPES and OPERATORS IN C++

Chapter 2.datatypes and operators

Embed Size (px)

Citation preview

Page 1: Chapter 2.datatypes and operators

DATA TYPESand

OPERATORS IN C++

Page 2: Chapter 2.datatypes and operators

IDENTIFIERS

• Identifiers are the names of things that appearin 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.

Page 3: Chapter 2.datatypes and operators

VARIABLES

• Variables are used to store values so that theseValues can be used later in the program.

• They are called variables because their values canbe 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;

Page 4: Chapter 2.datatypes and operators

VARIABLE DECLARATION

• To use a variable, you declare it by telling thecompiler 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;

Page 5: Chapter 2.datatypes and operators

DATATYPE

• Datatype means what are the various types of data that a variable can hold.

• The compiler allocates memory space to storeeach variable according to its datatype.

Imagine this Notebook as a variable

NoteBook nameC++

Initially bookIs empty meansYou have not defined the variable

Page 6: Chapter 2.datatypes and operators

Data TypesData 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.

Page 7: Chapter 2.datatypes and operators
Page 8: Chapter 2.datatypes and operators
Page 9: 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.

Page 10: Chapter 2.datatypes and operators

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.

Page 11: Chapter 2.datatypes and operators

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.

Page 12: Chapter 2.datatypes and operators

Each integer comes in two flavors:1. Signed2. Unsigned

• Half of the numbers represented by signed shortAre 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 thecompiler.

Page 13: Chapter 2.datatypes and operators

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 .

Page 14: Chapter 2.datatypes and operators

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.

Page 15: Chapter 2.datatypes and operators

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.

Page 16: Chapter 2.datatypes and operators

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 .

Page 17: Chapter 2.datatypes and operators

Integer type modifiersBy 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 .

Page 18: Chapter 2.datatypes and operators

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

Page 19: Chapter 2.datatypes and operators

character type modifiersThe 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.

Page 20: Chapter 2.datatypes and operators

Type Approximate size(in bytes)

Minimal range

Char 1 -128 to 127

Unsigned char 1 0 to 255

Signed char 1 same as char

Page 21: Chapter 2.datatypes and operators

Floating-point type modifiersC++ has three floating-point types : float , double and long double.

float type occupies 4 byte.

Double occupies 8 byte .

Long double occupies 10 byte.

Page 22: Chapter 2.datatypes and operators

TYPE approximate size(in bytes)

Digit of precision

Float 4 7

Double 8 15

Long double 10 19

Page 23: Chapter 2.datatypes and operators

Derived Data TypesFrom 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.

Page 24: Chapter 2.datatypes and operators

ARRAYSValues 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].

Page 25: Chapter 2.datatypes and operators

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.

Page 26: Chapter 2.datatypes and operators

Function declaration◦ return-type function-name (argument-list);◦void show();◦float volume(int x,float y,float z);

Function definitionreturn-type function-name(argument-list){statement1;statement2;

} Function call

◦ function-name(argument-list);◦ volume(a,b,c);

Page 27: Chapter 2.datatypes and operators

PointersPointers can be declared and initialized as in C.

int * ip; // int pointerip = &x; // address of x assigned to ip*ip = 10; // 10 assigned to x through indirection

Page 28: Chapter 2.datatypes and operators

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.

Page 29: Chapter 2.datatypes and operators

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;//classfunction declarations;//memberspublic:variable declarations;//classfunction declarations;//members};//Terminates with a semicolon

Page 30: Chapter 2.datatypes and operators

Classes and ObjectsClass 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.

Page 31: Chapter 2.datatypes and operators

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;

Page 32: Chapter 2.datatypes and operators

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 declarationstudent A; //C++ declarationA.roll_number=999;A.total_marks=595.5;Final_Total=A.total_marks + 5;

Page 33: Chapter 2.datatypes and operators

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.

Page 34: Chapter 2.datatypes and operators

UnionsA 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!

Page 35: Chapter 2.datatypes and operators

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.

Page 36: Chapter 2.datatypes and operators

Types of Operators

.

Operators

TERNARY

BINARYUNARY

Page 37: Chapter 2.datatypes and operators

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.

05/01/2023

Page 38: Chapter 2.datatypes and operators

Binary and Ternary Operators

• Binary operators?

• Ternary operators?

Page 39: Chapter 2.datatypes and 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

Page 40: Chapter 2.datatypes and 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 widthExample: setw(5)

Memory management operators

Manipulators(used to format data display)

Page 41: Chapter 2.datatypes and operators

1. Arithmetic operator

+ Addition - Subtraction * Multiplication / Division % Modulo division

Page 42: Chapter 2.datatypes and operators

05/01/2023

Page 43: Chapter 2.datatypes and operators

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

Page 44: Chapter 2.datatypes and operators

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

05/01/2023

a=100, b=4

Page 45: Chapter 2.datatypes and operators

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’

Page 46: Chapter 2.datatypes and operators

05/01/2023

Relational And Logical Operators

Page 47: Chapter 2.datatypes and operators

True

!True i.e !1 =0

Page 48: Chapter 2.datatypes and operators

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 thatcan receive a value

Page 49: Chapter 2.datatypes and operators

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

Page 50: Chapter 2.datatypes and operators

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;

Page 51: Chapter 2.datatypes and operators

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

Page 52: Chapter 2.datatypes and operators

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)

Page 53: Chapter 2.datatypes and operators

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

110011010010110111101101RESULT

OR means any oneinput must be true toget output as true

Page 54: Chapter 2.datatypes and operators

LEFT SHIFT <<

int m = 1 << 3Output will be 8

HOW?

_ _ _ 1

_ _ 1 _

_ 1_ _

1 _ _ _

Input

Output: 1000 in binarySo 8 in decimal

1<< 1st bit

1<< 2nd bit

1<< 3rd bit

Page 55: Chapter 2.datatypes and operators

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 -> ”

Page 56: Chapter 2.datatypes and operators

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.

Page 57: Chapter 2.datatypes and operators

8. Special operator

• Scope Resolution Operator – For example

Page 58: Chapter 2.datatypes and operators

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

Page 59: Chapter 2.datatypes and operators

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 .

Page 60: Chapter 2.datatypes and operators

Precedence of operatorsBODMAS RULE-Brackets of Division Multiplication Addition SubtractionBrackets 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 : + -

Page 61: Chapter 2.datatypes and operators

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

Page 62: Chapter 2.datatypes and operators

Rules for evaluation of expression1. First parenthesized sub expression from left to right are

evaluated.2. If parentheses are nested, the evaluation begins with the

innermost sub expression3. The precedence rule is applied in determining the order of

application of operators in evaluating sub expressions4. 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 precedence6. When parentheses are used, the expressions within parentheses

assume highest priority

Page 63: Chapter 2.datatypes and operators

Hierarchy of operatorsOperator 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

Page 64: Chapter 2.datatypes and operators

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

Page 65: Chapter 2.datatypes and operators

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.

05/01/2023

int + short int int

Page 66: Chapter 2.datatypes and operators

• 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 05/01/2023

Page 67: Chapter 2.datatypes and operators

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;

Page 68: Chapter 2.datatypes and operators

Example

#include <stdio.h>main(){ int sum = 17, count = 5; double mean; mean = (double) sum / count; printf("Value of mean : %f\n", mean );}Output isValue 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.

Page 69: Chapter 2.datatypes and operators

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.

Page 70: Chapter 2.datatypes and operators

Thank you

28-Jan-16