SlideShare a Scribd company logo
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;
}

More Related Content

PPT
OSI 7 Layer Model
Pritom Chaki
 
PPTX
Number system and its conversions
ShilpaKrishna6
 
PPTX
عرض تقديمي - معتز حاج محمد - اساسيات البرمجة.pptx
MoetazHM
 
PPTX
Constant, variables, data types
Pratik Devmurari
 
PPT
Operators in C++
Sachin Sharma
 
PPTX
Scheduling
pradeepa velmurugan
 
PPTX
uloom e panjgana.pptx
umerfarooq648026
 
PPTX
Ch 4 linker loader
Malek Sumaiya
 
OSI 7 Layer Model
Pritom Chaki
 
Number system and its conversions
ShilpaKrishna6
 
عرض تقديمي - معتز حاج محمد - اساسيات البرمجة.pptx
MoetazHM
 
Constant, variables, data types
Pratik Devmurari
 
Operators in C++
Sachin Sharma
 
uloom e panjgana.pptx
umerfarooq648026
 
Ch 4 linker loader
Malek Sumaiya
 

What's hot (20)

PPTX
Pointers in c++
Vineeta Garg
 
PPTX
Dynamic memory allocation
Viji B
 
PPTX
Function overloading
Selvin Josy Bai Somu
 
PPT
Function overloading(c++)
Ritika Sharma
 
PPTX
Presentation on Function in C Programming
Shuvongkor Barman
 
PPTX
Data types in c++
Venkata.Manish Reddy
 
PPTX
Values and Data types in python
Jothi Thilaga P
 
PDF
Function in C
Dr. Abhineet Anand
 
PPT
RECURSION IN C
v_jk
 
PPT
FUNCTIONS IN c++ PPT
03062679929
 
PPTX
Pointers in c++
sai tarlekar
 
PPTX
C if else
Ritwik Das
 
PPTX
If else statement in c++
Bishal Sharma
 
PPT
Modular programming
Mohanlal Sukhadia University (MLSU)
 
PPTX
Functions in c language
tanmaymodi4
 
PPT
Variables in C Programming
programming9
 
PPTX
classes and objects in C++
HalaiHansaika
 
PPTX
POINTERS IN C
Neel Mungra
 
PPTX
Operators and expressions in C++
Neeru Mittal
 
PPTX
Functions in c++
Rokonuzzaman Rony
 
Pointers in c++
Vineeta Garg
 
Dynamic memory allocation
Viji B
 
Function overloading
Selvin Josy Bai Somu
 
Function overloading(c++)
Ritika Sharma
 
Presentation on Function in C Programming
Shuvongkor Barman
 
Data types in c++
Venkata.Manish Reddy
 
Values and Data types in python
Jothi Thilaga P
 
Function in C
Dr. Abhineet Anand
 
RECURSION IN C
v_jk
 
FUNCTIONS IN c++ PPT
03062679929
 
Pointers in c++
sai tarlekar
 
C if else
Ritwik Das
 
If else statement in c++
Bishal Sharma
 
Functions in c language
tanmaymodi4
 
Variables in C Programming
programming9
 
classes and objects in C++
HalaiHansaika
 
POINTERS IN C
Neel Mungra
 
Operators and expressions in C++
Neeru Mittal
 
Functions in c++
Rokonuzzaman Rony
 
Ad

Similar to Data types in c++ (20)

PPT
3.pptirgggggggggggggggggggggggggggrrrrrrrrrrger
edukuldeep2005
 
DOCX
Theory1&amp;2
Dr.M.Karthika parthasarathy
 
PPTX
Fundamentals of Programming Constructs.pptx
vijayapraba1
 
PPTX
Pointer in C++
Mauryasuraj98
 
PPTX
Programming using c++ tool
Abdullah Jan
 
PDF
Lecture 2
Mohamed Zain Allam
 
PPTX
CP 04.pptx
RehmanRasheed3
 
PPTX
Java Programming Tutorials Basic to Advanced 2
JALALUDHEENVK1
 
PPTX
C++ FUNCTIONS-1.pptx
ShashiShash2
 
PPT
C++ Language
Syed Zaid Irshad
 
PPTX
UNIT - 1- Ood ddnwkjfnewcsdkjnjkfnskfn.pptx
crazysamarth927
 
PPTX
What is Data Types and Functions?
AnuragSrivastava272
 
PPTX
Nitin Mishra 0301EC201039 Internship PPT.pptx
shivam460694
 
PPTX
Programming_in_C_language_Unit5.pptx course ATOT
jagmeetsidhu0012
 
PPT
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
abdurrahimk182
 
PDF
Embedded_C_1711824726engéiiiring_with_the_best.pdf
AliAbdelli
 
PPT
Computer Programming- Lecture 7
Dr. Md. Shohel Sayeed
 
PPT
CPP Language Basics - Reference
Mohammed Sikander
 
PPT
C++ Functions.ppt
WaheedAnwar20
 
PDF
C++ Nested loops, matrix and fuctions.pdf
yamew16788
 
3.pptirgggggggggggggggggggggggggggrrrrrrrrrrger
edukuldeep2005
 
Fundamentals of Programming Constructs.pptx
vijayapraba1
 
Pointer in C++
Mauryasuraj98
 
Programming using c++ tool
Abdullah Jan
 
CP 04.pptx
RehmanRasheed3
 
Java Programming Tutorials Basic to Advanced 2
JALALUDHEENVK1
 
C++ FUNCTIONS-1.pptx
ShashiShash2
 
C++ Language
Syed Zaid Irshad
 
UNIT - 1- Ood ddnwkjfnewcsdkjnjkfnskfn.pptx
crazysamarth927
 
What is Data Types and Functions?
AnuragSrivastava272
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
shivam460694
 
Programming_in_C_language_Unit5.pptx course ATOT
jagmeetsidhu0012
 
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
abdurrahimk182
 
Embedded_C_1711824726engéiiiring_with_the_best.pdf
AliAbdelli
 
Computer Programming- Lecture 7
Dr. Md. Shohel Sayeed
 
CPP Language Basics - Reference
Mohammed Sikander
 
C++ Functions.ppt
WaheedAnwar20
 
C++ Nested loops, matrix and fuctions.pdf
yamew16788
 
Ad

Recently uploaded (20)

PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PDF
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
Understanding operators in c language.pptx
auteharshil95
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 

Data types in c++

  • 1. Data Types in C++ By Rushikesh Gaikwad Indian Institute of Information Technology Pune Email Id: [email protected] 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; }