SlideShare une entreprise Scribd logo
1  sur  40
Télécharger pour lire hors ligne
Data Types in C++
By Rushikesh Gaikwad
Indian Institute of Information Technology
Pune
Email Id: grushikesh718@gmail.com
Linked In: https://www.linkedin.com/in/rushikesh-gaikwad-b6700215a/
Data Types in C++
A data type is a classification that specifies the type of value a variable can
hold.
Data types in C++ categories in mainly three types:
1. Built-in Data Type
2. Derived Data Type
3. User Defined Data Type
Built-In Data Type
It is predefined data type and can be used directly by the user to declare variables.
Integer Data Type
Keyword: int
Storage: 4 Bytes in 64 & 32 bit OS and 2 Bytes in 16 bit OS
Range:
1. Signed data Type:
Keyword: signed
Int min = ( pow ( 2, number of bits assigned to data type) / 2 ) * -1
Int max = ( pow ( 2, number of bits assigned to data type) / 2 ) - 1
1. Unsigned data Type:
Keyword: unsigned
Int min = 0
Int max = pow ( 2, number of bits assigned to data type) - 1
Integer Data Type
Modifiers for data
Type:
1. Long
2. Short
3. Signed
4. Unsigned
Data Type Size(In Bytes) Range
Short int 2 -32768 to 32767
Unsigned short int 2 0 to 65535
Unsigned int 4 0 to 4,294,967,295
int 4 -2,147,483,648 to
2,147,483,647
Long int 4 -2,147,483,648 to
2,147,483,647
Unsigned long int 4 0 to 4,294,967,295
Integer Data Type
Program says:
1. Declaration of Int
2. Introduction of pointer variable
int main()
{
int c=4;
int *b;
b= &c;
cout << c << endl;
cout << &c << endl;
cout << *b << endl;
cout << b << endl;
cout << &b << endl;
return 0;
}
Integer Data Type
Program says:
1. Size of Int and its modifiers
#include <iostream>
using namespace std;
int main() {
int intType;
short int shortintType;
long int longintType;
// sizeof evaluates the size of a variable
cout << "Size of int: " << sizeof(intType) <<" bytes" << endl;
cout << "Size of short int: " << sizeof(shortintType)<<" bytes" << endl;
cout << "Size of long int: " << sizeof(longintType) <<" bytes" << endl;
return 0;
}
Integer Data Type
Program says:
1. Maximum and Minimum Limits of Int and its modifier
#include <iostream>
#include <climits> // integer limits in header file
using namespace std;
int main()
{
cout << "nn Check the upper and lower limits of integer :n";
cout << "--------------------------------------------------n";
cout << " The maximum limit of int data type : " << INT_MAX << endl;
cout << " The minimum limit of int data type : " << INT_MIN << endl;
cout << " The maximum limit of unsigned int data type : " << UINT_MAX << endl;
cout << " The maximum limit of long data type : " << LONG_MAX << endl;
cout << " The minimum limit of long data type : " << LONG_MIN << endl;
cout << " The maximum limit of unsigned long data type : " << ULONG_MAX << endl;
cout << " The minimum limit of short int data type : " << SHRT_MIN << endl;
cout << " The maximum limit of short int data type : " << SHRT_MAX << endl;
cout << " The maximum limit of unsigned short data type : " << USHRT_MAX << endl;
cout << endl;
return 0;
}
Integer Data Type
How the int is stored in Memory:
For data types int, signed int, 32 bits are allocated in memory.
Let us try to understand one by one.
1. int a = 456;
Value of variable a is 456. Now let us convert it to binary.
1 1 1 0 0 1 0 0 0
Now you get 9 bit number. Since int allocates 32 bits, fill the remaining 23 bits with 0.
So the value stored in memory is
00000000 00000000 00000001 11001000
Integer Data Type
2. int a = - 456;
Variable value is -456.Now let us convert it to binary.
Binary value of 456-
0 1 1 1 0 0 1 0 0 0
Stored as 32 bit so this becomes- 00000000 00000000 00000001 11001000
1’s complement of binary value of 456: 11111111 11111111 11111110 00110111
2’s complement of binary value of 456: ( 11111111 11111111 11111110 00110111) + 1 =
( 11111111 11111111 11111110 00111000)
So the value stored in memory is
( 11111111 11111111 11111110 00111000)
Character Data type
Keyword: char
Storage: 1 Byte
Two types based on Modifiers:
1. Signed char: MSB is used as signed and
rest 7 bits as data bits
Sign bit = 1 i.e. negative number
Sign bit = 0 i.e. positive number
1. Unsigned char: No sign bit in Unsigned
char
Character Data type
Range of char:
Signed char: -128 to 127 i.e
-(2^8)/2 to (2^8)/2-1
Unsigned char: 0 to 255 i.e
0 to 2^8 - 1
Character Data type
#include <iostream>
using namespace std;
int main()
{
char ch=130;
unsigned char uch=130;
signed char sch=130;
cout<< ch<<endl;
cout<< uch<<endl;
cout<< sch<<endl;
cout<<"Integer"<<endl;
cout<<int(ch)<<endl;
cout<<int(uch)<<endl;
cout<<int(sch)<<endl;
return 0;
}
Binary form of 130:
10000010
And it’s representation in signed
format is -126
Character is printed according to ascii
code 130
Integer for signed is printed as -126
Integer for unsigned is printed as 130
Ch and sch both are the signed type
of variable
Character Data type
How characters are Stored into memory:
For example, if we want to store char ‘A’ in computer, the corresponding ASCII
value will be stored in computer.
ASCII value for capital A is 65.
To store character value, computer will allocate 1 byte (8 bit) memory.
65 will converted into binary form which is (1000001) . Because computer
knows only binary number system.
Then 1000001 will be stored in 8-bit memory.
https://www.ascii-code.com/
Character data type is often called as integral data type because
memory implementation of char data type is in terms of number
code
Floating Data Type
1. Floating Point: Floating Point data type is used for storing single precision floating point
values or decimal values. Keyword used for floating point data type is float. Float
variables typically requires 4 byte of memory space.
2. Double Floating Point: Double Floating Point data type is used for storing double
precision floating point values or decimal values. Keyword used for double floating point
data type is double. Double variables typically requires 8 byte of memory space.
Void data Type
Void means without any value. void
datatype represents a valueless entity.
Void data type is used for those function
which does not returns a value.
#include <iostream>
using namespace std;
void fun()
{
cout << "Hello";
return;
}
int main()
{
fun();
return 0;
}
Data Type Conversion
Two Types of Conversion:
1. Implicit Type:
Also known as automatic type conversion
Done by the compiler on its own, without any external trigger from the user.
1. Explicit Type:
This process is also called type casting and it is user-defined. Here the user can
typecast the variable to make it of a particular data type.
Implicit Conversion
#include<iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int.
// ASCII value of 'a' is 97
x = x+y;
// x is implicitly converted to float
float z = x + 1.1;
cout << "x = " << x << endl
<< "y = " << y << endl
<< "z = " << z << endl;
return 0;
}
Explicit Conversion
Converting by assignment: This is done by explicitly defining the required data type in front of the
variable in parenthesis. This can be also considered as forceful casting.
Syntax: (datatype) variable
Explicit Conversion
// explicit type casting
#include <iostream>
using namespace std;
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
cout << "Sum = " << sum;
return 0;
}
Derived Data Type
ARRAY
An array is a series of elements of the same type placed in contiguous memory
locations .
NOTE: The elements field within brackets [ ] which represents the number of elements
the array is going to hold, must be a constant value.
Since arrays are blocks of non-dynamic memory whose size must be determined before
execution.
Syntax: Datatype Array_name[size_of_array]
ARRAY
// C++ program to demonstrate Array
#include <iostream>
using namespace std;
int main()
{
int arr[5];
arr[0] = 5;
arr[2] = -10;
// this is same as arr[1] = 2
arr[3 / 2] = 2;
arr[3] = arr[0];
cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<" "<<arr[3];
cout<<arr; // address of first element
cout<<arr+1; // address of second element
return 0;
}
ARRAY
//Program to find the sum of elements of array
#include <iostream>
using namespace std;
int array [] = {16, 2, 77, 40, 12071};
int n;
result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += array[n];
}
cout << result;
return 0;
}
Function
1. A function is a group of statements that performs the task.
1. A function is generally defined to save the user from writing the same lines of code again and
again for the same input.
1. All the lines of code are put together inside a single function and this can be called anywhere
required.
1. main() is a default function that is defined in every program of C++.
Syntax: returnType FunctionName(parameters) // Declaring the function
FunctionName(parameters) // Calling Function
returnType FunctionName(parameters) // defination of function
{ //Code}
Function
Example-1
#include <iostream>
using namespace std;
// declaring a function
void greet() {
cout << "Hello there!";
}
int main() {
// calling the function
greet();
return 0;
}
Example-2
// Function with Parameters
#include <iostream>
using namespace std;
// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}
int main() {
int num1 = 5;
double num2 = 5.5;
// calling the function
displayNum(num1, num2);
return 0;
}
Pointers
A pointer is a variable whose value is the address of another variable.
Like any variable or constant, you must declare a pointer before you can
work with it. The general form of a pointer variable declaration is −
Syntax: type *var_name;
Pointers
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}
Pointers Size
#include <iostream>
using namespace std;
int main()
{
int c=4;
int *b= &c;
char ch='b';
char* pc= &ch;
cout << sizeof(c) << endl;
cout << sizeof(ch) << endl;
cout << sizeof(b)<< endl;
cout << sizeof(pc) << endl;
return 0;
}
Reference
A reference variable is an alias,
that is, another name for an
already existing variable. Once a
reference is initialized with a
variable, either the variable name
or the reference name may be
used to refer to the variable.
Syntax: itype& ref-var = var-name;
// C++ program to illustrate Reference Derived
Type
#include <iostream>
using namespace std;
int main()
{
int x = 10;
// ref is a reference to x.
int& ref = x;
// Value of x is now changed to 20
ref = 20;
cout << "x = " << x << endl;
// Value of x is now changed to 30
x = 30;
cout << "ref = " << ref << endl;
return 0;
}
Reference vs Pointer
References are often confused with pointers but three major
differences between references and pointers are −
● You cannot have NULL references. You must always be
able to assume that a reference is connected to a
legitimate piece of storage.
● Once a reference is initialized to an object, it cannot be
changed to refer to another object. Pointers can be
pointed to another object at any time.
● A reference must be initialized when it is created.
Pointers can be initialized at any time
User Defined Data Type
Structure
1. A structure is a group of data elements grouped together under one name.
These data elements, known as members, can have different types and
different lengths.
1. Structures are declared in C++ using the following syntax:
struct structure_name
{
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} structure_variable;
1. Structure is different from an array in the sense that an array represents an
aggregate of elements of same type whereas a structure represents an
aggregate of elements of arbitrary types.
Structure
#include <iostream>
using namespace std;
struct Point {
int x,
char y;
};
int main()
{
// Create an array of structures
struct Point arr[10];
// Access array members
arr[0].x = 10;
arr[0].y = ‘a’;
cout << arr[0].x << ", " << arr[0].y;
return 0;
}
Union
1. Union is a user-defined datatype. All the members of union share
same memory location.
2. Size of union is decided by the size of largest member of union.
3. If you want to use same memory location for two or more
members, union is the best for that.
4. Unions are similar to structures. Union variables are created in
same manner as structure variables
5. If we change one variable, we can see the changes being reflected
in others.
Union
#include <iostream>
using namespace std;
// Declaration of union is same as the structures
union test {
int x,
char y;
};
int main()
{ union test t;
// t.y also gets value 2
t.x = 97;
cout << "After making x = 97:"<< endl << "x = " << t.x << ", y = " << t.y << endl;
// t.x is also updated to 10
t.y = ‘b’;
cout << "After making Y = ‘ b’:" << endl<< "x = " << t.x << ", y = " << t.y << endl;
return 0;
}
Class
It is a user-defined data type, which holds its own data members
and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an
object.
Classes are generally declared using the keyword class, with the
following format:
class class_name
{
access_specifier_1: member1;
access_specifier_2: member2;
.
.
} object_name;
Class // C++ program to demonstrate Class
#include <bits/stdc++.h>
using namespace std;
class Car{
// Access specifier
public:
// Data Members
string carname;
// Member Functions()
void printname()
{
cout << "carname is: " <<carname;
}
};
int main()
{
// Declare an object of class geeks
Car obj1;
// accessing data member
obj1.carname = "TATA NEXON";
// accessing member function
obj1.printname();
return 0;
}
Enumerate
An enumeration is a user-defined data type that consists of integral constants. To define
an enumeration, keyword enum is used.
enum season { spring, summer, autumn, winter };
Here, the name of the enumeration is season.
And, spring, summer and winter are values of type season.
By default, spring is 0, summer is 1 and so on. You can change the default value of an
enum element during declaration (if necessary).
enum season { spring = 0, summer = 4, autumn = 8, winter = 12};
Enumerate
Example 1: Enumeration Type
#include <iostream>
using namespace std;
enum week { Sunday, Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday };
int main()
{
week today;
today = Wednesday;
cout << "Day " << today+1;
return 0;
}
Example2: Changing Default Value of
Enums
#include <iostream>
using namespace std;
enum seasons { spring = 34, summer = 4,
autumn = 9, winter = 32};
int main() {
seasons s;
s = summer;
cout << "Summer = " << s << endl;
return 0;
}

Contenu connexe

Tendances

Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingIqra khalil
 
sSCOPE RESOLUTION OPERATOR.pptx
sSCOPE RESOLUTION OPERATOR.pptxsSCOPE RESOLUTION OPERATOR.pptx
sSCOPE RESOLUTION OPERATOR.pptxNidhi Mehra
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloadinggarishma bhatia
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vishal Patil
 
C data types, arrays and structs
C data types, arrays and structsC data types, arrays and structs
C data types, arrays and structsSaad Sheikh
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in javaHrithikShinde
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vineeta Garg
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statementsKuppusamy P
 

Tendances (20)

Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
sSCOPE RESOLUTION OPERATOR.pptx
sSCOPE RESOLUTION OPERATOR.pptxsSCOPE RESOLUTION OPERATOR.pptx
sSCOPE RESOLUTION OPERATOR.pptx
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
C data types, arrays and structs
C data types, arrays and structsC data types, arrays and structs
C data types, arrays and structs
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in java
 
class and objects
class and objectsclass and objects
class and objects
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 

Similaire à Data types in c++

Fundamentals of Programming Constructs.pptx
Fundamentals of  Programming Constructs.pptxFundamentals of  Programming Constructs.pptx
Fundamentals of Programming Constructs.pptxvijayapraba1
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ toolAbdullah Jan
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxShashiShash2
 
What is Data Types and Functions?
What is Data Types and Functions?What is Data Types and Functions?
What is Data Types and Functions?AnuragSrivastava272
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxshivam460694
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - ReferenceMohammed Sikander
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfyamew16788
 
Lecture # 1 introduction revision - 1
Lecture # 1   introduction  revision - 1Lecture # 1   introduction  revision - 1
Lecture # 1 introduction revision - 1SajeelSahil
 
Lecture # 1 - Introduction Revision - 1 OOPS.pptx
Lecture # 1 - Introduction  Revision - 1 OOPS.pptxLecture # 1 - Introduction  Revision - 1 OOPS.pptx
Lecture # 1 - Introduction Revision - 1 OOPS.pptxSanaullahAttariQadri
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming NeedsRaja Sekhar
 

Similaire à Data types in c++ (20)

Theory1&amp;2
Theory1&amp;2Theory1&amp;2
Theory1&amp;2
 
Fundamentals of Programming Constructs.pptx
Fundamentals of  Programming Constructs.pptxFundamentals of  Programming Constructs.pptx
Fundamentals of Programming Constructs.pptx
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ tool
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
CP 04.pptx
CP 04.pptxCP 04.pptx
CP 04.pptx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
What is Data Types and Functions?
What is Data Types and Functions?What is Data Types and Functions?
What is Data Types and Functions?
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
 
Computer Programming- Lecture 7
Computer Programming- Lecture 7Computer Programming- Lecture 7
Computer Programming- Lecture 7
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Lecture # 1 introduction revision - 1
Lecture # 1   introduction  revision - 1Lecture # 1   introduction  revision - 1
Lecture # 1 introduction revision - 1
 
Lecture # 1 - Introduction Revision - 1 OOPS.pptx
Lecture # 1 - Introduction  Revision - 1 OOPS.pptxLecture # 1 - Introduction  Revision - 1 OOPS.pptx
Lecture # 1 - Introduction Revision - 1 OOPS.pptx
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 

Dernier

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 

Dernier (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 

Data types in c++

  • 1. Data Types in C++ By Rushikesh Gaikwad Indian Institute of Information Technology Pune Email Id: grushikesh718@gmail.com Linked In: https://www.linkedin.com/in/rushikesh-gaikwad-b6700215a/
  • 2. Data Types in C++ A data type is a classification that specifies the type of value a variable can hold. Data types in C++ categories in mainly three types: 1. Built-in Data Type 2. Derived Data Type 3. User Defined Data Type
  • 3. Built-In Data Type It is predefined data type and can be used directly by the user to declare variables.
  • 4. Integer Data Type Keyword: int Storage: 4 Bytes in 64 & 32 bit OS and 2 Bytes in 16 bit OS Range: 1. Signed data Type: Keyword: signed Int min = ( pow ( 2, number of bits assigned to data type) / 2 ) * -1 Int max = ( pow ( 2, number of bits assigned to data type) / 2 ) - 1 1. Unsigned data Type: Keyword: unsigned Int min = 0 Int max = pow ( 2, number of bits assigned to data type) - 1
  • 5. Integer Data Type Modifiers for data Type: 1. Long 2. Short 3. Signed 4. Unsigned Data Type Size(In Bytes) Range Short int 2 -32768 to 32767 Unsigned short int 2 0 to 65535 Unsigned int 4 0 to 4,294,967,295 int 4 -2,147,483,648 to 2,147,483,647 Long int 4 -2,147,483,648 to 2,147,483,647 Unsigned long int 4 0 to 4,294,967,295
  • 6. Integer Data Type Program says: 1. Declaration of Int 2. Introduction of pointer variable int main() { int c=4; int *b; b= &c; cout << c << endl; cout << &c << endl; cout << *b << endl; cout << b << endl; cout << &b << endl; return 0; }
  • 7. Integer Data Type Program says: 1. Size of Int and its modifiers #include <iostream> using namespace std; int main() { int intType; short int shortintType; long int longintType; // sizeof evaluates the size of a variable cout << "Size of int: " << sizeof(intType) <<" bytes" << endl; cout << "Size of short int: " << sizeof(shortintType)<<" bytes" << endl; cout << "Size of long int: " << sizeof(longintType) <<" bytes" << endl; return 0; }
  • 8. Integer Data Type Program says: 1. Maximum and Minimum Limits of Int and its modifier #include <iostream> #include <climits> // integer limits in header file using namespace std; int main() { cout << "nn Check the upper and lower limits of integer :n"; cout << "--------------------------------------------------n"; cout << " The maximum limit of int data type : " << INT_MAX << endl; cout << " The minimum limit of int data type : " << INT_MIN << endl; cout << " The maximum limit of unsigned int data type : " << UINT_MAX << endl; cout << " The maximum limit of long data type : " << LONG_MAX << endl; cout << " The minimum limit of long data type : " << LONG_MIN << endl; cout << " The maximum limit of unsigned long data type : " << ULONG_MAX << endl; cout << " The minimum limit of short int data type : " << SHRT_MIN << endl; cout << " The maximum limit of short int data type : " << SHRT_MAX << endl; cout << " The maximum limit of unsigned short data type : " << USHRT_MAX << endl; cout << endl; return 0; }
  • 9. Integer Data Type How the int is stored in Memory: For data types int, signed int, 32 bits are allocated in memory. Let us try to understand one by one. 1. int a = 456; Value of variable a is 456. Now let us convert it to binary. 1 1 1 0 0 1 0 0 0 Now you get 9 bit number. Since int allocates 32 bits, fill the remaining 23 bits with 0. So the value stored in memory is 00000000 00000000 00000001 11001000
  • 10. Integer Data Type 2. int a = - 456; Variable value is -456.Now let us convert it to binary. Binary value of 456- 0 1 1 1 0 0 1 0 0 0 Stored as 32 bit so this becomes- 00000000 00000000 00000001 11001000 1’s complement of binary value of 456: 11111111 11111111 11111110 00110111 2’s complement of binary value of 456: ( 11111111 11111111 11111110 00110111) + 1 = ( 11111111 11111111 11111110 00111000) So the value stored in memory is ( 11111111 11111111 11111110 00111000)
  • 11. Character Data type Keyword: char Storage: 1 Byte Two types based on Modifiers: 1. Signed char: MSB is used as signed and rest 7 bits as data bits Sign bit = 1 i.e. negative number Sign bit = 0 i.e. positive number 1. Unsigned char: No sign bit in Unsigned char
  • 12. Character Data type Range of char: Signed char: -128 to 127 i.e -(2^8)/2 to (2^8)/2-1 Unsigned char: 0 to 255 i.e 0 to 2^8 - 1
  • 13. Character Data type #include <iostream> using namespace std; int main() { char ch=130; unsigned char uch=130; signed char sch=130; cout<< ch<<endl; cout<< uch<<endl; cout<< sch<<endl; cout<<"Integer"<<endl; cout<<int(ch)<<endl; cout<<int(uch)<<endl; cout<<int(sch)<<endl; return 0; } Binary form of 130: 10000010 And it’s representation in signed format is -126 Character is printed according to ascii code 130 Integer for signed is printed as -126 Integer for unsigned is printed as 130 Ch and sch both are the signed type of variable
  • 14. Character Data type How characters are Stored into memory: For example, if we want to store char ‘A’ in computer, the corresponding ASCII value will be stored in computer. ASCII value for capital A is 65. To store character value, computer will allocate 1 byte (8 bit) memory. 65 will converted into binary form which is (1000001) . Because computer knows only binary number system. Then 1000001 will be stored in 8-bit memory. https://www.ascii-code.com/ Character data type is often called as integral data type because memory implementation of char data type is in terms of number code
  • 15. Floating Data Type 1. Floating Point: Floating Point data type is used for storing single precision floating point values or decimal values. Keyword used for floating point data type is float. Float variables typically requires 4 byte of memory space. 2. Double Floating Point: Double Floating Point data type is used for storing double precision floating point values or decimal values. Keyword used for double floating point data type is double. Double variables typically requires 8 byte of memory space.
  • 16. Void data Type Void means without any value. void datatype represents a valueless entity. Void data type is used for those function which does not returns a value. #include <iostream> using namespace std; void fun() { cout << "Hello"; return; } int main() { fun(); return 0; }
  • 17. Data Type Conversion Two Types of Conversion: 1. Implicit Type: Also known as automatic type conversion Done by the compiler on its own, without any external trigger from the user. 1. Explicit Type: This process is also called type casting and it is user-defined. Here the user can typecast the variable to make it of a particular data type.
  • 18. Implicit Conversion #include<iostream> using namespace std; int main() { int x = 10; // integer x char y = 'a'; // character c // y implicitly converted to int. // ASCII value of 'a' is 97 x = x+y; // x is implicitly converted to float float z = x + 1.1; cout << "x = " << x << endl << "y = " << y << endl << "z = " << z << endl; return 0; }
  • 19. Explicit Conversion Converting by assignment: This is done by explicitly defining the required data type in front of the variable in parenthesis. This can be also considered as forceful casting. Syntax: (datatype) variable
  • 20. Explicit Conversion // explicit type casting #include <iostream> using namespace std; int main() { double x = 1.2; // Explicit conversion from double to int int sum = (int)x + 1; cout << "Sum = " << sum; return 0; }
  • 22. ARRAY An array is a series of elements of the same type placed in contiguous memory locations . NOTE: The elements field within brackets [ ] which represents the number of elements the array is going to hold, must be a constant value. Since arrays are blocks of non-dynamic memory whose size must be determined before execution. Syntax: Datatype Array_name[size_of_array]
  • 23. ARRAY // C++ program to demonstrate Array #include <iostream> using namespace std; int main() { int arr[5]; arr[0] = 5; arr[2] = -10; // this is same as arr[1] = 2 arr[3 / 2] = 2; arr[3] = arr[0]; cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<" "<<arr[3]; cout<<arr; // address of first element cout<<arr+1; // address of second element return 0; }
  • 24. ARRAY //Program to find the sum of elements of array #include <iostream> using namespace std; int array [] = {16, 2, 77, 40, 12071}; int n; result=0; int main () { for ( n=0 ; n<5 ; n++ ) { result += array[n]; } cout << result; return 0; }
  • 25. Function 1. A function is a group of statements that performs the task. 1. A function is generally defined to save the user from writing the same lines of code again and again for the same input. 1. All the lines of code are put together inside a single function and this can be called anywhere required. 1. main() is a default function that is defined in every program of C++. Syntax: returnType FunctionName(parameters) // Declaring the function FunctionName(parameters) // Calling Function returnType FunctionName(parameters) // defination of function { //Code}
  • 26. Function Example-1 #include <iostream> using namespace std; // declaring a function void greet() { cout << "Hello there!"; } int main() { // calling the function greet(); return 0; } Example-2 // Function with Parameters #include <iostream> using namespace std; // display a number void displayNum(int n1, float n2) { cout << "The int number is " << n1; cout << "The double number is " << n2; } int main() { int num1 = 5; double num2 = 5.5; // calling the function displayNum(num1, num2); return 0; }
  • 27. Pointers A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is − Syntax: type *var_name;
  • 28. Pointers #include <iostream> using namespace std; int main () { int var = 20; // actual variable declaration. int *ip; // pointer variable ip = &var; // store address of var in pointer variable cout << "Value of var variable: "; cout << var << endl; // print the address stored in ip pointer variable cout << "Address stored in ip variable: "; cout << ip << endl; // access the value at the address available in pointer cout << "Value of *ip variable: "; cout << *ip << endl; return 0; }
  • 29. Pointers Size #include <iostream> using namespace std; int main() { int c=4; int *b= &c; char ch='b'; char* pc= &ch; cout << sizeof(c) << endl; cout << sizeof(ch) << endl; cout << sizeof(b)<< endl; cout << sizeof(pc) << endl; return 0; }
  • 30. Reference A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable. Syntax: itype& ref-var = var-name; // C++ program to illustrate Reference Derived Type #include <iostream> using namespace std; int main() { int x = 10; // ref is a reference to x. int& ref = x; // Value of x is now changed to 20 ref = 20; cout << "x = " << x << endl; // Value of x is now changed to 30 x = 30; cout << "ref = " << ref << endl; return 0; }
  • 31. Reference vs Pointer References are often confused with pointers but three major differences between references and pointers are − ● You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage. ● Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time. ● A reference must be initialized when it is created. Pointers can be initialized at any time
  • 33. Structure 1. A structure is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths. 1. Structures are declared in C++ using the following syntax: struct structure_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . . } structure_variable; 1. Structure is different from an array in the sense that an array represents an aggregate of elements of same type whereas a structure represents an aggregate of elements of arbitrary types.
  • 34. Structure #include <iostream> using namespace std; struct Point { int x, char y; }; int main() { // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = ‘a’; cout << arr[0].x << ", " << arr[0].y; return 0; }
  • 35. Union 1. Union is a user-defined datatype. All the members of union share same memory location. 2. Size of union is decided by the size of largest member of union. 3. If you want to use same memory location for two or more members, union is the best for that. 4. Unions are similar to structures. Union variables are created in same manner as structure variables 5. If we change one variable, we can see the changes being reflected in others.
  • 36. Union #include <iostream> using namespace std; // Declaration of union is same as the structures union test { int x, char y; }; int main() { union test t; // t.y also gets value 2 t.x = 97; cout << "After making x = 97:"<< endl << "x = " << t.x << ", y = " << t.y << endl; // t.x is also updated to 10 t.y = ‘b’; cout << "After making Y = ‘ b’:" << endl<< "x = " << t.x << ", y = " << t.y << endl; return 0; }
  • 37. Class It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object. Classes are generally declared using the keyword class, with the following format: class class_name { access_specifier_1: member1; access_specifier_2: member2; . . } object_name;
  • 38. Class // C++ program to demonstrate Class #include <bits/stdc++.h> using namespace std; class Car{ // Access specifier public: // Data Members string carname; // Member Functions() void printname() { cout << "carname is: " <<carname; } }; int main() { // Declare an object of class geeks Car obj1; // accessing data member obj1.carname = "TATA NEXON"; // accessing member function obj1.printname(); return 0; }
  • 39. Enumerate An enumeration is a user-defined data type that consists of integral constants. To define an enumeration, keyword enum is used. enum season { spring, summer, autumn, winter }; Here, the name of the enumeration is season. And, spring, summer and winter are values of type season. By default, spring is 0, summer is 1 and so on. You can change the default value of an enum element during declaration (if necessary). enum season { spring = 0, summer = 4, autumn = 8, winter = 12};
  • 40. Enumerate Example 1: Enumeration Type #include <iostream> using namespace std; enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; int main() { week today; today = Wednesday; cout << "Day " << today+1; return 0; } Example2: Changing Default Value of Enums #include <iostream> using namespace std; enum seasons { spring = 34, summer = 4, autumn = 9, winter = 32}; int main() { seasons s; s = summer; cout << "Summer = " << s << endl; return 0; }