unit-1-new-cpp

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 35

Unit – I

Introduction to C++ : Evolution of C++ – Object Oriented Technology –


Disadvantage of Conventional Programming – Programming Paradigms – Key Concepts of Object –
Oriented Programming – Advantages of OOP – Object Oriented Languages.
Input and Output in C++: Streams in C++ - Pre-Defined Streams – Buffering – Stream Classes –
Formatted and Unformatted Data – Unformatted Console I/O Operations – Typecasting with cout
Statement – Member Functions of istream Class – Formatted Console I/O Operations.
C++ Declarations : Parts of C++ Program – Types of Tokens – Keywords – Identifiers – Dynamic
Initialization – Data Types in C++ - Basic Data Type – Derived Data Type – User-Defined Data Type
– The void Data Type – Type Modifiers – Wrapping Around – Typecasting – Constants – Constant
Pointers – Operators - Precedence of Operators.

Evolution of C++
 C++ is an object oriented language
 It is an extension of C language
 C++ was developed by Bjarne Stroustrup at AT&T Bell
laboratories in Murray Hill, New Jersey, USA during 1980's.
 Stroustrup combined the features of Simula67 and C into a more
powerful language that could support object-oriented
programming with features of C.
 C++ is an extension of C with a major addition of the class
construct features of Simula67
 Stroustrup initially called the new language 'C with classes’. In
1983 the name was changed to C++. The idea of C++ comes from
the C increment operator. Mascitti coined the term C++ in 1983.
 All the concepts of C are applicable to C++. During 1990's the
language underwent a number of improvements and changes.
 The most important facilities that C++ adds on to C are classes,
inheritance, function overloading and operator overloading.
These features enable creating of abstract data types, inherit
properties from existing data types and support polymorphism,
thereby making C++ a truly object oriented Language.
 The object Oriented features in C++ allow programmers to build
large programs with clarity, extensibility and ease of maintenance.
ANSI Standard
 ANSI stands for American National Standards Institute.
 The Institute ANSI was founded in 1918.
 The main goal for establishing this Institute was to suggest,
reform, recommend and publish standards for data processing
in the USA. This committee sets up standards for the computer
industry.
 The ANSI / ISO council has made an international standard for
C++ (ISO - International Standards Organization). The first draft
of the planned ANSI standard was made on 25 January 1994.
 In November 1997, the language underwent a number of
improvements and changes, and ANSI/ISO committee
standardised and added several new features.
 The ANSI standard is an attempt to ensure that C++ is portable.

Object Oriented Technology


"Object-oriented programming, is an approach that provides a way of
modularizing programs by creating partitioned memory area for both
data and functions that can be used as templates for creating copies
of such modules on demand"
 OOPs treats data as critical element in the program development
and does not allow it to flow freely around the system. Oops ties
data more closely to the functions that operate on it, and protects it
from accidental modification from outside functions.
 OOP allows decomposition of a problem into a number of entities
called Objects and then builds data and functions around these
objects.
 The organization of data and functions in object oriented programs
is shown below.

 The data of an object can be accessed only by the functions


associated with that object. However the functions of one object
can access the functions of other objects.
 Some of the striking features of object-Oriented programming are,

 Emphasis is on data rather than procedure.


 Programs are divided into objects.
 Data structures are designed to characterize the objects .
 Functions that operate on the data are of an object are tied
together into the data structure.
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through functions.
 New data and functions can be easily added whenever
necessary.
 Follows bottom-up approach in program design.
 Thus, an object is considered to be a partitioned area of computer
memory that stores data and set of operations that can access that
data.
 Since the memory partitions are independent, the objects can be
used in a variety of different programs without modification.

Disadvantage of Conventional Programming


 Traditional programming languages such FORTRAN, COBOL etc.
are commonly known as procedure-oriented languages (COBOL
- Common Business Oriented Language, FORTRAN - FORmula
TRANslation).
 The program written in traditional languages consists of a
sequence of instructions that tells the compiler or interpreter to
perform a given task.
 When programs are large, it is inconvenient to manage it. To
overcome this problem, procedures or subroutines were adopted
to make a program more understandable to the programmers. A
program is divided into many functions. Each function can call
another function as shown in fig.
 Each function can call another function, as shown in Fig. 1.3.
Each function has its own task. If the program is too large the
function also creates problems. In many programs, important
data variables are declared as global.
 In case of programs containing several functions, every function
can access the global data as per the simulation in Fig. 1.4.. Due
to this the program may contain several logical errors.

Key Concepts of Object Oriented Programming


The major Concepts of Object Oriented Programming are:

1. Class
2. Object
3. Abstraction
4. Encapsulation
5. Data Hiding
6. Inheritance
7. Reusability
8. Polymorphism
9. Virtual Functions
10.Message passing

Class: Class is an abstract data type (user defined data type) that
contains member variables and member functions that operate on
data. It starts with the keyword class. A class denotes a group of
similar objects.

e.g.: class employee


{
int empno;
char
name[25],desg[25];
float sal;
public:
void getdata ();
void putdata ();
};

Object: An object is an instance of a class. It is a variable that


represents data as well as functions required for operating on the
data. They interact with private data and functions through public
functions.

e.g.: employee e1, e2;

In the above example employee is the class name and e1 and e2


are objects of that class.

Abstraction: Abstraction refers to the process of concentrating


on the most essential features and ignoring the details. There are
two types of abstraction

i) Procedural Abstraction
ii) Data Abstraction

Procedural Abstraction: Procedural abstraction refers to the


process of using user-defined functions or library functions to
perform a certain task, without knowing the inner details. The
function should be treated as a black box. The details of the body
of the function are hidden from the user.

Data Abstraction: Data Abstraction refers to the process of


formation of user defined data type from different predefined data
types. e.g: structure, class.

Encapsulation: Encapsulation is the process of combining data


members and member functions into a single unit as a class in
order to hide the internal operations of the class and to support
abstraction.

Data Hiding: All the data in a class can be restricted from using it
by giving some access levels (visibility modes). The three access
levels are private, public, protected.
 Private data and functions are available to the public
functions only. They cannot be accessed by the other part
of the program. This process of hiding private data and
functions from the other part of the program is called as
data hiding.
Inheritance: Inheritance is the process of acquiring (getting) the
properties of some other class. The class whose properties are
being inherited is called as base class and the class which is
getting the properties is called as derived class.

Reusability: Using the already existing code is called as


reusability. This is mostly used in inheritance. The already existing
code is inherited to the new class. It saves a lot of time and effort.
It also reduces the size of the program.

Polymorphism: Polymorphism means the ability to take many


forms. Polymorphism allows to take different implementations for
same name.

poly  many

morphism  forms

There are two types of polymorphism, Compile time polymorphism


and run time polymorphism.

In Compile time polymorphism binding is done at compile time and


in runtime polymorphism binding is done at runtime.

e.g.: Function overloading, operator overloading


Function Overloading: Function overloading is a part of
polymorphism. Same function name having different
implementations with different number and type of arguments.

Operator Overloading: Operator overloading is a part of


polymorphism. Same operator can have different implementations
with different data types.

Virtual Functions: Virtual functions are special type of functions


which are defined in the base class and are redefined in the
derived class. When virtual function is called with a base pointer
and derived object then the derived class function will be called. A
function can be defined as virtual by placing the keyword virtual
for the member function.
Message Passing: An object-oriented program contains a set of
objects that communicate with one another. A message for an
object is a request for execution of a procedure and therefore will
invoke a function (procedure) in the receiving object that
generates the desired result. Message passing involves specifying
the name of the object, the name of the function (message) and
information to be sent.
Advantage of OOP
Object oriented technology provides many advantages to the programmer
and the user. This technology solves many problems related to software
development, provides improved quality and low cost software.

1. Object oriented programs can be comfortably upgraded.


2. Using inheritance, we can eliminate redundant program code and
continue the use of previously defined classes.
3. The technology of data hiding facilitates the programmer to design and
develop safe programs that do not disturb code in other parts of the
program.
4. The encapsulation feature provided by OOP languages allows
programmer to define the class with many functions and characteristics
and only few functions are exposed to the user.
5. All object oriented programming languages allows creating
extended and reusable parts of programs.
6. Object oriented programming changes the way of thinking of a
programmer. This results in rapid development of new software in a
short time.
7. Objects communicate with each other and pass messages.

Applications of OOPS :The promising areas for application of OOP includes:


 Real-time systems
 Simulation and modelling
 Object-oriented databases
 Hypertext, hypermedia and expert text
 AI and expert systems
 Neural networks and parallel programming
 Decision support and Automation system
 CIM/CAM/CAD systems

Object Oriented Languages
The following are the object-oriented languages, which are widely accepted by the
programmer.

 C++
 Smalltalk
 Charm ++
 Java
SMALLTALK
Smalltalk is a pure object oriented language. C++ makes few compromises to ensure
quick performance and small code size. Smalltalk uses run-time binding. Smalltalk
programs are considered to be faster than the C++. Smalltalk needs longer time to learn
than C++. Smalltalk programs are written using Smalltalk browser. Smalltalk uses
dynamic objects and memory is allocated from free store. It also provides automatic
garbage collection and memory is released when object is no longer in use.
CHARM++
Charm ++ is also an object oriented programming language. It is a portable. The
language provides features such as inheritance, strict type checking, overloading, and
reusability. It is designed in order to work efficiently with different parallel systems
together with shared memory systems, and networking.

Programming paradigms
 Monolithic programming paradigm
 Structured-oriented programming paradigm
 Procedure-oriented programming paradigm
 Object-oriented programming paradigm

(i)Monolithic Programming Paradigm


The Monolithic programming paradigm is the oldest. It has the
following characteristics. It is also known as the imperative
programming paradigm.

 In this programming paradigm, the whole program is written in a


single block.
 We use the goto statement to jump from one statement to
another statement.
 It uses all data as global data which leads to data insecurity.
 There are no flow control statements like if, switch, for, and
while statements in this paradigm.
 There is no concept of data types.

An example of a Monolithic programming paradigm is Assembly


language.

(ii)Structure-oriented Programming Paradigm


The Structure-oriented programming paradigm is the advanced
paradigm of the monolithic paradigm. It has the following
characteristics.

 This paradigm introduces a modular programming concept


where a larger program is divided into smaller modules.
 It provides the concept of code reusability.
 It is introduced with the concept of data types.
 It also provides flow control statements that provide more
control to the user.
 In this paradigm, all the data is used as global data which leads
to data insecurity.
Examples of a structured-oriented programming paradigm is ALGOL,
Pascal, PL/I and Ada.

(iii)Procedure-oriented Programming Paradigm


The procedure-oriented programming paradigm is the advanced
paradigm of a structure-oriented paradigm. It has the following
characteristics.

 This paradigm introduces a modular programming concept


where a larger program is divided into smaller modules.
 It provides the concept of code reusability.
 It is introduced with the concept of data types.
 It also provides flow control statements that provide more
control to the user.
 It follows all the concepts of structure-oriented programming
paradigm but the data is defined as global data, and also local
data to the individual modules.
 In this paradigm, functions may transform data from one form to
another.

Examples of procedure-oriented programming paradigm is C, visual


basic, FORTRAN, etc.

(iv)Object-oriented Programming Paradigm


The object-oriented programming paradigm is the most popular. It
has the following characteristics.

 In this paradigm, the whole program is created on the concept of


objects.
 In this paradigm, objects may communicate with each other
through function.
 This paradigm mainly focuses on data rather than functionality.
 In this paradigm, programs are divided into what are known as
objects.
 It follows the bottom-up flow of execution.
 It introduces concepts like data abstraction, inheritance, and
overloading of functions and operators overloading.
 In this paradigm, data is hidden and cannot be accessed by an
external function.
 It has the concept of friend functions and virtual functions.
 In this paradigm, everything belongs to objects.

Examples of procedure-oriented programming paradigm is C++,


Java, C#, Python, etc.
PARTS OF C++ PROGRAM
● A C++ Program consists of different sections
● Every C++ program starts with function main(). If the user
writes a program without main() it will not be executed.
● Different sections of a C++ program is given below

Include files : It controls the header files for function declaration. Each header
file has an extension .h
e.g # include “ iostream.h” (or)
# include <iostream.h>
iostream.h file defines all the definitions and prototypes of functions. The header
file also gets compiled with the original program.
Class declaration or definition: A class is defined in this section. It contains
data variable, data member, function prototypes or function definitions. The
class definition is always terminated by a semi-colon.
Class function definition :This part contains definition of functions. The
function definition can be done outside or inside the class. the functions defined
inside the class are implemented as inline functions. when a function is large, the
function prototype is declared Inside the class and defined outside the class.
main() function: C++ program always start execution from main().
Structure Of A Program :

Here is our first program:


// my first program in C++

#include <iostream.h>

int main ()
{
cout << "Hello World!"; return 0;
}

Output:-Hello World!
We are going to look line by line at the code we have just written:
// my first program in C++
This is a comment line. All lines beginning with two slash signs (//) are considered comments..
The programmer can use them to include short explanations or observations within the source
code itself.
#include <iostream.h>
Lines beginning with a hash sign (#) are directives for the preprocessor. In this case the directive
#include<iostream.h> tells the preprocessor to include the iostream standard file. This specific
file (iostream) includes the declarations of the basic standard input-output library in C++.
int main ()
This line corresponds to the beginning of the definition of the main function. The main
function is the point by where all C++ programs start their execution. It is essential that all C++
programs have a main function.
The word main is followed in the code by a pair of parentheses (()). That is because it is a
function declaration. Right after these parentheses we can find the body of the main function
enclosed in braces ({}). What is contained within these braces is what the function does when it
is executed.
cout << "Hello World!";
cout represents the standard output stream in C++, and the meaning of the entire statement
is to insert a sequence of characters (in this case the Hello World sequence of characters) into the
standard output stream (which usually is the screen).
The statement ends with a semicolon character (;).
return 0;
The return statement causes the main function to finish. A return code of 0 for the main function
is generally interpreted as the program worked as expected without any errors during its
execution. This is the most usual way to end a C++ console program.

· Example :-

# include<iostream.h>
class person
{
char name[30];
int age;
public:
void getdata(void);
void display(void);
};

void person :: getdata ( void )


{
cout<<”enter name”;
cin>>name;
cout<<”enter age”;
cin>>age;
}
void display()
{
cout<<”\n name:”<<name;
cout<<”\n age:”<<age;
}
int main( )
{
person p;
p.getdata();
p.display();
return(0);
}
Types of Tokens

The smallest individual units in a program are known as tokens. C++


has the following tokens.
i. Keywords
ii. Identifiers
iii. Constants
iv. Strings
v. Operators
(i)KEYWORDS:
 The keywords implement specific C++ language feature.
 They are explicitly reserved identifiers and can’t be used as
names for the program variables or other user defined program
elements.
 All C keywords are valid in C++.
 There are 63 keywords in C++. In addition, TurboC++ permits
14 extra keywords.

(ii)IDENTIFIERS:
Identifiers refers to the name of variable , functions, arrays, classes,
objects etc. created by programmer.. The following rules are used for
naming the identifiers,.
1. Only alphabetic chars, digits and under score are
permitted.
2. The name can’t start with a digit.
3. Upper case and lower case letters are distinct.
4. A declared keyword can’t be used as a variable name.
In ANSI C the maximum length of a variable is 32 chars but in C++
there is no bar.

(iii) Constants
 Constants are values to the variable, which do not change during
the execution of a program.
 Constants are also like normal variables. only difference is, their
values can not be modified by the program once they are
defined. Constants refer to fixed values. They are also called as
literals.
 Constants may belong to any of the data type.
 Two types of constants, Literal constant and symbolic constants.
 Literal constant contain 3 categories. They are string constant,
numeric constant and charcter constant.
Syntax:
const data_type variable_name; (or)
const data_type *variable_name;
EXAMPLES:
Integer constants – Example: 0, 1, 1218, 12482
Real or Floating point constants – Example: 0.0, 1203.03, 30486.184
Octal & Hexadecimal constants – Example: octal: 013
Hexadecimal: 0X13
Character constants -Example: ‘a’, ‘A’, ‘z’
String constants -Example: “nicas”
(iv) operators

 Operators are symbols that triggers an action when applied to


variables and other objects. The data items on which operators
act upon are called operands.
 Depending on the number of operands that an operator can act
upon, operators can be classified as follows:
 Unary Operators: Those operators that require only single
operand to act upon are known as unary operators.For Example
increment and decrement operators
 Binary Operators: Those operators that require two operands
to act upon are called binary operators. Binary operators are
classified into :
Arithmetic operators = - * / %
Relational Operators < <= > >= ==
Logical Operators && || !
Increment and decrement ++ --
Assignment Operators = += -= *= /= %=
Conditional Operators ?:
Bitwise Operators & | ^ << >> ~
Other operators :: ::* ->* .* delete endl new
setw
 Ternary Operators: These operators requires three operands
to act upon. For Example Conditional operator(?:).
(v) strings

A string is a sequence of characters. C++ supports two types of


string representations:
 C-style strings: The strings are character arrays, which are
terminated by character arrays.
 String class: The string class is used to create string objects
and they can be used like anyother built-in-type data.
___________________________________________________________
IDENTIFIERS

 A variable is a name given to a memory location. It is the basic


unit of storage in a program. A variable may take different values
at different times during execution.
 The value stored in a variable can be changed during program
execution.
 A variable is only a name given to a memory location, all the
operations done on the variable effects that memory location.
 In C++, all the variables must be declared before use.
How to declare variables?
 A typical variable declaration is of the form:
// Declaring a single variable
type variable_name;
// Declaring multiple variables:
type variable1_name, variable2_name,
variable3_name;
 A variable name can consist of alphabets (both upper and lower
case), numbers and the underscore ‘_’ character. However, the
name must not start with a number.
Difference between variable declaration and definition
 The variable declaration refers to the part where a variable is first declared or introduced
before its first use.
 A variable definition is a part where the variable is assigned a memory location and a value.
Most of the times, variable declaration and definition are done together.
 Sample C++ program :
Dynamic initialization of variables

Initialization of a variable is of two types:


 Static Initialization: Here, the variable is assigned a value in advance. This variable then
acts as a constant.
 Dynamic Initialization: Here, the variable is assigned a value at the run time. The value of
this variable can be altered every time the program is being run.

Dynamic Initialization : Value is being assigned to variable at run time.


Example:
int a;
printf("Enter the value of a");
scanf("%d", &a);

The process of initializing a variable at the moment it is declared at runtime is called dynamic
initialization of the variable. Thus, during the dynamic initialization of a variable, a value is
assigned to execution when it is declared.

Example program :
# include<iostream.h>
void main()
{
int a;
cout<<“Enter Value of a”;
cin>>a;
int cube = a * a * a;
}
In the above example, the variable cube is initialized at run time using expression a * a * an at the
time of its declaration.
________________________________________________
BASIC DATA TYPES IN C++

Both C and C++ compilers support all the built in types. With the exception of void the basic
datatypes may have several modifiers preceding them to serve the needs of various situations.
The modifiers signed, unsigned, long and short may applied to character and integer basic data
types. However the modifier long may also be applied to double.
3 basic types: integer, float and void

(i) Integer
 Integers are whole numbers
 Integers Occupy 1 word of storage( 1 word= 2 bytes /16 bits)
 C++ defines this type as consisting of the values ranging from -32768 to 32767. (-215
to 215)
 3 classes of int type: short int, int, long int
 Long and unsigned int are used to increase the range of values.
 Signed is default
 If long integer is needed the type long or long int can be used. The range of long int
is too big that is from -2147483648 to 2147483647, which occupies 4 bytes in
memory.
(ii) float

 C++ defines the data type float as representing numbers that have fractional part.
 Floating point variables can either be small or large.
 A variable with type float occupies 4 bytes in size with 6 digits of precision
 Floating type number are Known as single precision numbers
 Example: float f;

(iii)double

 When the accuracy provided by float number is not sufficient, the type double
can be used.
 A double data type uses 64 bits giving a precision of 14 digits.
 14 digits precision
 Long double takes 80 bits (10 bytes)
 Known as double precision numbers
 Example: double d;

(iv)Char

 A single character can be defined as char type data


 C++ offers a predefined data type that is one byte (8 bits) in size, which can hold
exactly one character such as ‘a’ or ‘A’.
 The qualifier signed or unsigned may be applied to char.
 To declare a variable of type char, we have

Example: Char ch;

 Signed char have values from -128 to 127


 Unsigned char have values from 0 to 255
 Suppose we want to store a character value ‘a’, in a char data type ch, it is
enclosed within a single quote.

Ch = ‘a’;

Void type

The type void normally used for:


1) To specify the return type of function when it is not returning any value.
2) To indicate an empty argument list to a function.
Example:

void function(void);
~~~~~~~~~~~~~~~~~~~~~~~~~~

Derived data type


The data-types that are derived from the primitive or built-in datatypes
are referred to as Derived Data Types. These can be of four types
namely:
Function

 Array
 Pointers
 References
1.Function:
A function is a self-contained block of code or program-segment that is

defined to perform a specific well-defined task.
 A function is generally defined to save the user from writing the same
lines of code again and again for the same input.
 All the lines of code are put together inside a single function and this can
be called anywhere required.
 main() is a default function that is defined in every program of C++.
Syntax:

FunctionType FunctionName(parameters)
{
}

Example program:

// C++ program to demonstrate Function Derived Type

#include <iostream.h>

// max here is a function derived type


int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}

// main is the default function derived type


int main()
{
int a = 10, b = 20;

// Calling above function to find max of 'a' and 'b'


int m = max(a, b);

cout << "m is " << m;


return 0;
}

Output:
m is 20

2. Array
An array is a set of elements that are kept in memory in a continuous
manner and also have the same type of data present within the array.
The purpose of an array is to store a lot of data in a single variable
name and sequential order.

Syntax:
DataType ArrayName[size_of_array];

Example:

int arr[4]={0,1,2,3};

Here, we have defined an integer array of size 4, which can


continuously store four integer variables in memory.

#include <iostream.h>
int main()
{
int arr[5]={10, 30, 20, 40, 30}; //creating and initializing
array
//traversing array
for (int i=0; i<5: i++)
{
cout<<arr[i]<<"\n";
}
}
Output:

10
30
20
40
30

3. Pointer

 Pointers are symbolic representations of addresses.


 Pointers store the addresses of the variables having the same datatype as that of
the pointer.
 The size of the pointer is either 4 bytes or 8 bytes, no matter what the data type is.
They enable programs to create and change dynamic data structures, as well as to
imitate call-by-reference. In C/C++, its generic declaration looks like this:

Syntax:

data_type *variable_name;

Example:

int *ptr;

ptr holds the address of a variable of an integer datatype.

Example program:

// C++ program to illustrate Pointers Derived Type

#include <iostream.h>
#include<conio.h>
void main()
{
int var = 20;

// Pointers Derived Type declare pointer variable


int* ptr;
// note that data type of ptr and var must be same
ptr = &var;
clrscr();
// assign the address of a variable to a pointer
cout << "Value at ptr = "<< ptr << "\n";
cout << "Value at var = " << var << "\n";
cout << "Value at *ptr = " << *ptr << "\n";
}

Output:
Value at ptr = 0x7ffc10d7fd5c
Value at var = 20
Value at *ptr = 20

4. Reference Variables

 A reference variable allows us to create an alternative name


for the already defined variable. It is introduced in C++.
 Once you define a reference variable that references an
already defined variable then you can use any of them
alternatively in the program. Both refer to the same memory
location.
 If you change the value of any of the variables it will affect
both variables because one variable references another
variable.
 The general syntax for creating a reference variable is as
follows:

Data-type & Referace_Name = Variable_Name;

The reference variable must be initialized during the declaration.


Example:
int count;
count = 5;
int & incre = count;
Here, we have already defined a variable named count.
USER DEFINED DATA TYPES:
The data types that are defined by the user are called the abstract datatype or user-
defined data type.
These types include:

 Class
 Structure
 Union
 Enumeration
 Typedef defined DataType
1. Class: The building block of C++ that leads to Object-Oriented programming is
a 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.
Syntax:

Example:

#include <iostream.h>
#include<conio.h>
class scaler
{
public:
string student_name;

void print_name()
{
cout << "Student name is: " << student_name << endl;
}
};

int main()
{
scaler student1, student2;
clrscr();
student1.student_name = "Shivam Singla";
student1.print_name();
student2.student_name = "Sachin Singla";
student2.print_name();
return 0;
}
2. STRUCTURES

Structure is a collection of variables of different data types under a


single name. It is similar to a class in that, both holds a collecion of
data of different data types.
struct structureName
{
member1;
member2;
member3;
.
.
.
memberN;
};
In the above declaration, a structure is declared by preceding
the struct keyword followed by the identifier(structure name). Inside
the curly braces, we can declare the member variables of different
types.

struct Person
{
char name[30];
int citizenship;
int age;
}
Example 1:
#include <iostream.h>

struct Person
{
int citizenship;
int age;
};
int main(void)
{
struct Person p;
p.citizenship = 1;
p.age = 27;
cout << "Person citizenship: " << p.citizenship << endl;
cout << "Person age: " << p.age << endl;

return 0;
}
Output:

3. Union

 Union is a user-defined data type that is used to store the


different data type's values.
 However, in the union, one member will occupy the memory at
once. In other words, we can say that the size of the union is
equal to the size of its largest data member size.
 Union offers an effective way to use the same memory location
several times by each data member.
 The union keyword is used to define and create a union data
type.
Syntax of Union
union [union name]
{
type member_1;
type member_2;
...
type member_n;
};

4. ENUMERATED DATA TYPE:

An enumerated data type is another user defined type which provides a way for
attaching names to number, these by increasing comprehensibility of the code. The enum
keyword automatically enumerates a list of words by assigning them values 0,1,2 and soon.
This facility provides an alternative means for creating symbolic.

Data type Modifiers

We can modify some of the fundamental data types using modifiers with them. C++ offers 4 modifiers:

1. signed

2. unsigned

3. short

4. long

1. signed Modifier

Signed variables can store positive, negative integers, and zero.

Example:

signed int a = 45;


signed int b = -67;
signed int c = 0;

Here,

 ‘a’ is a positive valued integer.


 ‘b’ is a negative valued integer.

 ‘c’ is a zero-valued integer.

Example:

C++

// C++ program to demonstrate

// the signed modifier

#include <iostream>

using namespace std;

// Driver Code

int main()

cout << "Size of signed int : " <<

sizeof(signed int) <<

" bytes" << endl;

cout << "Size of signed char : " <<

sizeof(signed char) <<

" bytes" << endl;

return 0;

Output

Size of signed int : 4 bytes

Size of signed char : 1 bytes

Note: The int datatype is signed by default. So, int can be directly be used instead of signed int.

2. unsigned Modifier
Unsigned variables can store only non-negative integer values.

Example:

unsigned int a = 9;
unsigned int b = 0;

Here,

 ‘a’ is a positive valued integer.

 ‘b’ is a zero-valued integer.

Example:

C++

// C++ program to demonstrate

// the unsigned modifier

#include <iostream>

using namespace std;

// Driver Code

int main()

cout << "Size of unsigned int : " <<

sizeof(unsigned int) <<

" bytes" << endl;

cout << "Size of unsigned char : " <<

sizeof(unsigned char) <<

" bytes" << endl;

return 0;

Output

Size of unsigned int : 4 bytes


Size of unsigned char : 1 bytes

Difference Between Signed and Unsigned Modifiers

 The signed value of the signed variable is stored in the allocated memory. However, the
signed value is not stored by the unsigned variables.

 The sign takes 1 bit extra. So, if the unsigned value is being used then one-bit extra space is
used to save the value of a variable.

 The range of values for unsigned types starts from 0. For example, for unsigned int, the value
range is from 0 to 4,294,967,295. However, for signed int, the value range is from -
2,147,483,648 to 2,147,483,647.

Note: signed and unsigned modifiers can only be used with int and char datatypes.

3. short Modifier

The short keyword modifies the minimum values that a data type can hold. It is used for small
integers that lie in the range of −32,767 to +32,767.

Example:

short int x = 4590;

Example:

C++

// C++ program to demonstrate

// the short modifier

#include <iostream>

using namespace std;

// Driver Code

int main()

cout << "Size of short int : " <<

sizeof(short int) <<

" bytes" << endl;


return 0;

Output

Size of short int : 2 bytes

Note: The short int can be written as short also. They are equivalent.

4. long Modifier

The long keyword modifies the maximum values that a data type can hold. It is used for large integers
that are in the range of -2147483647 to 2147483647.

Example:

long int y = 26936;

Example:

C++

// C++ program to demonstrate

// the long modifier

#include <iostream>

using namespace std;

// Driver Code

int main()

cout << "Size of long int : " <<

sizeof(long int) <<

" bytes" << endl;

cout << "Size of long double : " <<

sizeof(long double) <<


" bytes" << endl;

return 0;

Output

Size of long int : 8 bytes

Size of long double : 16 bytes

. Literals (Constants)

Literals are data items whose values do not change during the execution of a program.
Therefore Literals are called as Constants. C++ has several kinds of literals:

Numeric Constants:

As the name indicates, the numeric constants are numeric values, which are used as
constants. Numeric constants are further classified as:
• Integer Constants (or) Fixed point constants.

• Real constants (or) Floating point constants.

(1) Integer Constants (or) Fixed point constants

Integers are whole numbers without any fractions. An integer constant must have at
least one digit without a decimal point. It may be signed or unsigned. Signed integers
are considered as negative, commas and blank spaces are not allowed as part of it. In C+
+, there are three types of integer constants: (i) Decimal (ii) Octal (iii) Hexadecimal

(i) Decimal

Any sequence of one or more digits (0 …. 9)

If you assign 4.56 as an integer decimal constant, the compiler will accept only the
integer portion of 4.56 ie. 4. It will simply ignore .56.

If a Decimal constant declared with fractions, then the compiler will take only the
integer part of the value and it will ignore its fractional part. This is called as “Implicit
Conversion”. It will be discussed later.

(ii) Octal

Any sequence of one or more octal values (0 …. 7) that begins with 0 is considered as
an Octal constant.
When you use a fractional number that begins with 0, C++ has consider the number as
an integer not an Octal.

(iii) Hexadecimal

Any sequence of one or more Hexadecimal values (0 …. 9, A …. F) that starts with 0x


or 0Xis considered as an Hexadecimal constant.

The suffix L or l and U or u added with any constant forces that to be represented as a
long or unsigned constant respectively.

(2) Real Constants (or) Floating point constants

A real or floating point constant is a numeric constant having a fractional component.


These constants may be written in fractional form or in exponent form.

Fractional form of a real constant is a signed or unsigned sequence of digits including a


decimal point between the digits. It must have at least one digit before and after a
decimal point. It may have prefix with + or - sign. A real constant without any sign will
be considered as positive.

Exponent form of real constants consists of two parts: (1)


Mantissa and (2) Exponent. The mantissa must be either an integer or a real constant.
The mantissa followed by a letter E or e and the exponent. The exponent should also be
an integer.

For example, 58000000.00 may be written as 0.58 × 108 or 0.58E8.

Example:
Boolean Literals

Boolean literals are used to represent one of the Boolean values(True or false).
Internally true has value 1 and false has value 0.

Character constant

A character constant is any valid single character enclosed within single quotes. A
character constant in C++ must contain one character and must be enclosed within a
single quote.

Valid character constants : ‘A’, ‘2’, ‘$’

Invalid character constants : “A”

The value of a single character constant has an equivalent ASCII value. For example,
the value of ‘A’ is 65.

Escape sequences (or) Non-graphic characters

C++ allows certain non-printable characters represented as character constants. Non-


printable characters are also called as non-graphical characters. Non-printable characters
are those characters that cannot be typed directly from a keyboard during the execution
of a program in C++, for example: backspace, tabs etc. These non-printable characters
can be represented by using escape sequences. An escape sequence is represented by a
backslash followed by one or two characters.

Table 9.2 Escape Sequences


Even though an escape sequence contains two characters, they should be enclosed
within single quotes because, C++ consider escape sequences as character constants and
allocates one byte in ASCII representation.

ASCII (American Standard Code for Information Interchange) was first developed and
published in 1963 by the X3 committee, a part of the American Standards Association
(ASA).

String Literals

Sequence of characters enclosed within double quotes are called as String literals. By
default, string literals are automatically added with a special character ‘\0’ (Null) at the
end. Therefore, the string “welcome” will actually be represented as “welcome\0” in
memory and the size of this string is not 7 but 8 characters i.e., inclusive of the last
character \0.

Valid string Literals : “A”, “Welcome” “1234”

Invalid String Literals : ‘Welcome’, ‘1234’

You might also like