0% found this document useful (0 votes)
10 views24 pages

Unit-1 in C++

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views24 pages

Unit-1 in C++

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIT-I

INTRODUCTION
1INTRODUCTION TO C++

Evolution of C++:-
C++ is an object-oriented programming language and is considered to be an extension of C.Bjarne
stroustrup at AT & T Bell laboratories.various ideas were derived from SIMULA 67 and ALGOL 68 .
Stroustrup called the new language “C with classes “.However in 1983 the name was changed to C++
.
The thought of C++ came from the c increment operator ++.Rick Mascitti coined the term C++ in
1983 .

ANSI stands for American National Standards Institute.This Institute was founded in 1918 .
The process of standardization is gradual and the first draft of the planned ANSI standard was made
on 25 January 1994.

Disadvantage Of Conventional Programming:-


The drawbacks observed in Monolithic,Procedural, and Structured programming languages :-
(1) Large size programs are divided into smaller programs known as functions .These functions can
call one another .Hence ,security is not provided.
(2) Importance is not given to security of data but on doing things
(3) Data passes globally from one function to another.
(4) Most functions have access to global data.

Programming Paradigms:-

(1) Monolithic Programming:-


(1) In monolithic programming languages such as BASIC and ASSEMBLY, the data variables
declared are global and the statements are written in sequence.
(2) The program contains jump statements such as goto ,that transfer control to any statement.

(2) Procedural Programming:-


. (1)In procedural programming languages such as FORTRAN and COBOL ,programs are divided into
a number of segments known as subprograms.
(2) Data is global and all the subprograms share the same data.
(3) These languages are used for developing medium size applications.

(3) Structured Programming:-


(1) In structured programming languages such as PASCAL and C larger programs are developed.
These programs are divided into multiple sub modules and procedures.
(2) Each procedure has to perform different task
(3) User-defined data types are introduced.

Object-Oriented Programming:-
Object-oriented programming language is a feature that allows a mode of modularizing programs by
forming separate memory area for data as well as functions that is used as object for making copies of
modules as per requirement.

The important characteristics of object-oriented programming:-


(1) OOP pays more importance to data than to function.
(2) Programs are divided into classes and their member functions.

1
(3) New data items and functions can be comfortably added whenever essential.
(4) Data is private and prevented from accessing external functions.
(5) Objects can communicate with each other through functions.

Key concepts of object-oriented programming

(1) Object :-
Objects are primary run-time entities is an object-oriented programming.Object occupy space in
memory.
Every object has its own properties or features.An object is a specimen of a class .The action of the
objects depends upon the member functions defined within its class.
Example of commonly available objects are Telephone, Computer etc.

(2) Classes:-
A class is grouping of objects having identical properties ,common behavior,and shared
relationship.
The entire group of data and code of an object can be built as a user-defined data type using class.A
class is a model of the object .
Ex Class : car
Properties : company, model, color and capacity
Actions : speed(), average(), and break()

(3) Method:-
An operation required for an object or entity when coded in a class is called a method.
Ex :
Class A
{
Private:
Data member1;
Data member1; Members
Data member n;
Public:
Method(1) { }
Method(2) { } Methods or Member functions
};

(4) Data Abstraction:-


Abstraction directs to the procedure of representing essential features without including the
background details.
Data abstraction is the procedure of identifying properties and methods related to a specific entity as
applicable to the application.
Ex: Computer as a single unit
(5) Encapsulation:-
The packing of data and functions into a single component is known as encapsulation.The data is not
accessible by outside functions .only those functions that are able to access the data are defined within the
class.
(6) Inheritance:-
Inheritance is the method by which objects of one class get the properties of objects of another class.
Advantages of inheritance :-
(1) Inheritance provides reusability.
(2) The programmer can add new properties to the existing class without changing it.
(3) Permits the reuse of an existing class to make a new class.

2
Example of inheritance:-
Red,yellow and blue are the main colours.Orange colour is created from the combination of
red and yellow ,green is created from yellow and blue,and violet is created from red and blue.

Red Yellow Blue

Orange Greeen Violet

(7) Polymorphism:-
Polymorphism allows the same function to act differently in different classes.Allowing objects of
different classes to share the same external interface.

Ex : Line Dotted Object


Display() Display (dotted)

Dash Object
Display(dash)

(8) Dynamic Binding:-


Binding means connecting one program to another program that is to be executed in reply to the call.
Dynamic binding is also as late binding .The code present in the specified program is unknown till it is
executed.

(9) Message Passing:-


Object-oriented programming includes object which communicate with each other.A message
contains name of the member function and parameters of the functions.
Ex: Object . Display (argument)

Object message data

Communication operator
(10) Reusability:-
Object-oriented technology of the classes by extending them to other classes using inheritance.

Advantage of reusability:-
 It saves time
 It saves the memory space
(11) Delegation:-
One class can be derived from other class and relationship between them is known as kind of
relationship.When object of one class is used as data member in other class,such composition of objects is
known as delegation.
(12) Genericity:-
The software components of a program have more than one version depending on the data types of
arguments ,The compiler identifies the data type at run-time.The template feature in C++ allows generic
programming.
List Advantages of OOPs:-
Object-oriented programming provides many advantages to the programmer and the user. It
provide improved quality ,and low cost software.
3
(1) Object-oriented programs can be comfortably upgraded.
(2) Using inheritance ,redundant program codes can be eliminated.
(3) Data hiding facilitates the programmer to design and develop safe programs
(4) Encapsulation feature provided by OOP languages allows programmer to define the class with many
functions
(5) All object-oriented programming languages can create extended.
(6) Process of a programmer leading to rapid development of new software in short span of time.
Object-oriented languages:-
There are many languages which support object-oriented programming.
Following object-oriented languages are widely accepted by the programmer:-
(1) C++
(2) Smalltalk
(3) Charm++
(4) Java
(1) Smalltalk:-
Smalltalk is purely an object-oriented programming language. Smalltalk uses run-time binding. Faster
than C++ and needs longer time to learn .Programs are written using smalltalk browser. It also provides
automatic garbage collection and memory is released when object is no longer in use.
(2) Charm++:-
Charm++ is also an object –oriented programming languages. It provides features such as inheritance,
strict type checking ,overloading ,and reusability. Work efficiently with different parallel systems , together
with shared memory.

(3) Java:-
Java was developed by Patrick Naughton, James Gosling, Chris Warth ,Mike Sheridan and Ed frank at
sun Microsystems .Java is an object-oriented programming languages. Java allows client/server
programming. The Java programs are downloaded by the client machines and executed on different types of
hardware .The Java compiler converts the source program to JVM(Java Virtual Machine).Java program is
known as byte code .The Java interpreter translates byte code into object code .
List any five application of OOPS
The most popular application of object-oriented programming is windows.
Following are the areas for which OOP is considered.
(1) Object-oriented DBMS
(2) Office automation software
(3) AI and expert systems
(4) CAD/CAM software
(5) Network programming
(6) System software
2 INPUT AND OUTPUT IN C++
Streams in C++
The stream is an intermediator between I/O devices and the user. Stream is flow of data in bytes in
sequence.
If data is received from input devices in sequence then it is called as source stream. When the data is
passed to output devices then it is called as destination stream.
Data in source stream can be used as input data by the programs. so ,the source stream is also called
as input stream . The destination stream that collects output data from the program is known as output stream
.
The input stream pulls the data from keyboard or storage devices such as disk , floppy disk ..etc .The
data present in output stream is passed on to the output devices such as monitor or printer.
Pre-Defined Streams:-
C++ has a number of pre-defined streams. These pre-defined streams .These pre-defined streams are
also called as standard I/O objects .These streams are automatically activated when the program execution
starts.

4
Cin ------------ Standard input (stdin)

Cout ------------ standard output (stdout)

Clog ------------ A fully bufferd version of cerr .It controls error messages

Cerr ------------ Standard error output.(stderr).it catches the errors and


Passes to standard error device monitor.
Buffering:-
.It is a block of memory used to hold data temporarily .It is always located between a peripheral device
and faster computer .Buffers are used to pass data between computer and devices .The buffer increases the
performance of the computer .

Unformatted console I/O operations


Input and Output streams:-
Input stream:-
The input stream does read operation through keyboard .It uses cin as object .The cin statements uses >>
(extraction operator) before variable name . The cin statement is used to read data through the input device
.
Syntax:-
Cin >> variable
Example:-
int v1;
float v2;
char v3;
cin >> v1>>v2>>v3…>>vn;
Output stream:-
The output stream manages output of the stream . I t uses << insertion operator before variable name . It
uses the cout object to perform console write operation .
Syntax:-
Cout<<variable
Example:-
Cout << v1<<v2<<v3…<<vn;
Get() function :
The single character input and output operations in C++ can be done with the help of put( ) and get( )
functions . The get( ) is used to read a character.
The get ( ) function has two syntaxes.
(a) get (char*);
(b) get (void);
If syntax (a) is used ,the get ( ) function assigns the read data to its argument , whereas if syntax (b) is
used ,the get ( ) function returns the data read .
Ex: cin.get(sex)- read a single character.
Put ( ) function
The put ( ) function is used to display the character on the screen. It is a member of ostream class.
The syntax of put ( ) is given below .
(a) cout . put (‘A’) – displays the character on the screen.
(b) cout .put (x) - displays the contents of variable x on the screen.
getline ( ) function
The getline ( ) function reads the string including white space. The getline() statement terminates the
accepting data when enter is pressed.
cin.getline(variable , size );
Ex: cin.getline(name,20) - The variable ‘name’ read maximum 20 characters.
5
read ( ) function
The read ( ) function is also used to read text through the keyboard. The syntax of read is given below.
cin.read(variable, size);
where as the read ( ) continues to read characters till the number of characters entered are equal to the
size specified.
Ex: cin.read(name,20)- The variable ‘name’ read maximum 20 characters.
Write ( ) function:
The write ( ) function is used to display the string on the screen .Its format is the same as getline
( ) but the function is exactly opposite .
The syntax is given below.
cout.write ( variable , size );
Where variable name is a character type and size is the size of the character arrays .The cout.write ( )
statements displays only specified number of characters given in the second argument.
Ex : cout.write(“SUNDAY”,3) , The output is “SUN”.
Member Functions Of istream class
Peek ( ) - It returns the succeeding characters without extraction.
Ignore ( )-Maximum number of charcters to avoid ,and the termination character Putback ( )- replaces the
given character into the input stream.
Formatted Console I/O Operations
They are of three types.
(1) ios class function and flags
(2) manipulators
(3) User-defined output functions.

1. ios class function and flags:-


Function Working
Width ( ) To set the required field width
Presicion ( ) To set number of decimal point .
Fill( ) To set a character to fill in the blank space.
Setf( ) To set various flags for formatting output.
Unsetf ( ) To remove the flag setting.

Syntax of width :_
Width ( );
Declaration :-
(a) int width ( );
(b) int width (int);
Ex: cout.width(10);
cout<< “B”;
The output is B
Syntax of precision:-
Precision ( );
Declaraction:-
(a) int precision (int);
(b) int precision ( );
Ex: cout.precision(2);
Cout<<3.1452;
Output is 3.14
Syntax of fill:-
Fill ( );
Declaration:-
6
(a) char fill ( );
(b) char fill (char ) ;
Ex: cout.fill(‘-‘);
cout.width(10);
cout<<”done”
output is ------done

Syntax of setf:-
long setf ( );
Declaration:-
(a) long setf (long sb , long f ) ;
(b) long setf (long ) ;
Bit fields :-
The ios class contains the setf ( ) member function. The flag indicates the format design .The syntax
of the unsetf ( ) function is used to clear the flags.The syntax of function are as follows.
Syntax: cout .setf(v1, v2);
Syntax : cout .unsetf( v1);
Where v1 and v2 are two flags.

format Flag (v1) Bit-field (v2)


Left justification ios :: left ios :: adjustfield
Right justification ios :: right ios :: adjustfield
Padding after sign and base ios :: internal ios :: adjustfield
Scientific notation ios:: scientific ios :: floatfield
Fixed point notation ios:: fixed ios :: floatfield
Decimal point ios:: dec ios :: basefield
Octal base ios:: oct ios :: basefield
Hexa decimal base ios::hex ios :: base field

Ex: cout.fill(‘=’);
cout.setf(ios::right,ios::adjustfield);
Cout.width(20);
Cout<<”Figure”;
Output is ==============Figure
Flags without Bit Field:-
Flag Working
Ios :: showbase Use base indicator on output
Ios :: showpos Display + preceding positive number
Ios :: showpoint Show trailing decimal point and zeroes
Ios :: skipus Skip white space on input
Ios :: unitbuf Flush all streams after insertion
Ios :: uppercase Use capital characters for scientific and hexa decimal values
Ios :: stdio Adjust the stream with c standard input and output
Converts bool values to text ( “true “ or “false “
Ex: cout.setf(ios:: showpos);
cout<<1254;
outptu is +1254
2. Manipulators:-

7
The output formats can be controlled using manipulators . The header file iomaniph. But the
manipulator does not return to previous setting.

Manipulator Function
Setw ( int n ) The field width is fixed to n.
Setbase Sets the base of the number system.
Setprecision (int p) The precision point is fixed to p .
Setfill (char f) The fill character is set to character stored in variable f.
Setiosglags ( long l ) Format flag is set to 1.
Resetiosflags (long l) Removes the flags indicated by 1.
endl Spilts a new line.
Skipws Omits white space on input
noskipws Does not omit white space on in put.
Ends Adds null character to close an output string.
flush Flushes the buffer stream.
Lock Locks the file associated with the file handle.
Ws Used to omit the leading white spaces present before the first field.
Hex,oct,dec Displays the number in hexa-decimal,octal,and decimal format

Ex: cout<<setprecision(2)<<2.5555;
Output is 2.56
3. User-Defined Manipulators:-
The programmer can also define his/her ownmanipulator according to the requirement of the
program.
Syntax :-
ostream & m_name ( ostream & o)
{
statement1;
statement2;
return 0;
}
where m_name is the name of the manipulator
ex:
#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
ostream & tab(ostream &o)
{
o<<”\t”;
return 0;
}
void main()
{
clrscr();
cout<<1<<tab<<2;
}
Output is 1 2
8
Custom built I/O Objects

(1) Creating Output Object:


It is also possiable to declare objects equivalent to these objects . The object declaraction is same
as variable declaration.
ostrean print ( 1 );
In the above example , print is an object of class ostream.The ostream handles the output functions .The
parenthesis with value one calls the constructor.
Ex: char text[10]=”hello”
ostream print(1);
print<<text;
Output is hello
(2) Creating Input object:-
The object equivalent to cin can be declared as follows
istream_withassign in ;
Here ,the istream_withassign is a class ,which provides assignment operator
in=cin;
The operator associated with cin is assigned to object in.
Ex: in.getline(text,20);

3 C++ DECLARATIONS
Structure of the C++ PROGRAM
A Program consists of different sections. C++ allows combining variable and functions in
structures and classes. The structure and classes are same and used for the same purpose. Functions can be
defined inside or outside class.
(1) INCLUDE FILES SECTION:
C++ Program also depends upon some header files for function definition. Each header file has an
extension.
Example: # include <iostream.h> or # include “iostream.h”.
The header files are include at the top of the program.

(2)CLASS DECLARATION OR DEFINITION:


Declaration of a class is done in this section. The class definition is always terminated by a semi-
colon. The function definition tells the compiler how the function works.
Syntax of class declaration:

Class <name of class> class item


{ {
private: private:
declaration of variables; int codeno;
prototype declaration of function; float prize;
public: int qty;
declaration of variables; public:
prototype declaration of function; void input();
}; void show();
};

3.CLASS FUNCTION DEFINITION:


This part contains definition or function. the function definition can be outside or inside the class. The
function defined inside the class or implemented as inline functions. Prototype of a function declared inside
the class.
Function definition can be Inside the class {
class item int a,b;
9
public: int a,b;
void input() public:
{ void input();
cin>>a>>b; }
}
void item::input()
{
Function definition can be Inside the class cin>>a>>b;
class item }
{
4.THE main () FUNCTION
The c++ programs always start execution from main () function. Thus execution of every program in
c++ starts with main () function.
main()
{
item i;
i.input();
}
TYPES OF TOKENS
The c++ programs contain various components. Tokens are classified in the following type.
(a) keywords (b) variable (c) constants
(d) special character (e) operators

a. KEYWORDS
The c++ keywords are reserved words by the compiler and have the fixed meaning. There are 63
keywords in c++. Turbo c++ permits 14 extra keywords.
Example: auto,double,int.
b.IDENTIFIERS or VARIABLE
Identifiers are names of variables, functions and arrays etc. They are user defined names, consisting of
a sequence of letters and digits, with a letter as a first character.
Rules for the Identifiers
1.Lower case letters are preferred.
2. he upper case letters are also permitted.
3. The ( _ ) underscore symbol can be used as an identifier.
Example: stu-name, stu-regno.
4. The identifier must begin with a character and should start with a digit. There should not be any space
between the characters in the variable but underscore is allowed.
5. The identifier name should not be a c++ keyword.
6. The identifier name may be a combination of upper and lower characters. For example, the variables
suM,sum and Sum are not the same.

c.CONSTANTS:
The values does not changed during the program execution is called constant.
Various types of constant including integers, characters, floating, and string constants. C++ has two types of
constants literal and symbolic.
(a)literal constant:
A literal constant is directly assigned to a variable.
Example: int x=5;
X is a variable of type int and 5 is a literal constant.
(b)symbolic constant:
A symbolic constant is defined in the same way as variable. Initialization of constant the assigned
value cannot be altered.
The constant can be defined in the following three ways:

10
(1) # define
(2) The const keyword
(3) The enum keyword
(1) the # define preprocessor directive:
# define price 152
(2) const keyword:
const int price=152;
Defines a constant of type int. data type is strictly maintained while doing operation. The value of
constant cannot be changed at run-time.
(3)constants can be define using enumeration:
Enum [a=5,b=10,c=15];
Here a,b and c are declared as integer constants with values 5,10 and 15.

d. Special Characters
The operators such as #(preprocessor directive),? (conditional operator) and ~(bitwise operator)are
known as special characters.

e. OPERATORS :
Operator is an instruction to the compiler of interpreter, specify by a single or double symbol to
perform certain operation with constants.
Example: 5+10
The symbol ‘+’ is an operator that indicates the operation to be performed and performs addition of
numbers and is a single operator.
Int x=5;
++ x;
The operator ++ is an increment operator.
Type of operators
Types of operators Symbolic Representation
Arithmetic Operators +,-,*, /, %
Relational Operators <, <=, >, >=, == and !=
Logical Operators &&, || and !
Increment and Decrement Operators ++ and --
Assignment Operators =
Bitwise Operators &, |, ^, >>, << and ~
Special Operators ,
Conditional Operators ?,:

VARIABLE DECLARATION & INITIALIZATION


Variable is used to store values. Every variable has memory location. The memory locations are used to
store the values of the variables. The variables can be of any type. It may be integer, char, float etc.
Syntax:
data-type v1,v2…..vn ;
Example:
(a) int a;
(b) float c,d,e;
INITIALIZATION:
Assigning a value to the variable is called as initialization. The declaration of variable is done only
once but initialization of variable can be done for any number of times.
DYNAMIC INITIALIZATION:

11
The declaration and initialization of variable in a single statement at any place in the program is called
as dynamic initialization.
Example:
Float area=3.14*r*r;
In the above statement float variable area is declared and product of 3.14*r*r is assigned to area. The
assignment carried out at run-time.
DATA TYPES IN C++
Data is a collection of characters, digits, symbols etc. it is used to represent information. The data are
classified in various types.
(a)basic data type (b)derived type
(c)user-defined type (d)void data type
(A) BASIC DATA TYPE:
The basic data types are integer, Float and Void datatypes.
Integer Float Void

Char Float
int Double
int
Data Type Size in Bytes Range
char 1 -128 to 127
int 2 -32768 to 32767
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.1. E+308

THE void DATA TYPE or do nothing function

It is also known as Empty data type.


(a) When specified as a function return type.void means that the function does not return a value.
void message (char * name)
{
Printf (“ hello, %s.”, name );
}
Here, message () is a void function. The keyword void is preceded by the function name. this function when
executed displays only message does not return any value to the calling function.

(b)the void keyword is also used as argument for function. when found in a function heading, void means
that the function does not take any arguments.
int fun(void)
{

return 1;
}
(c) when specified as a function return type and in function heading i.e., the function neither returns a value
nor requires any argument.
void function (void) ;
The above function neither returns a value nor requires any argument.
(B) DERIVED DATA TYPE:
The derived data types are of following types:
(1) POINTERS
(2) FUNCTIONS
(3) ARRAYS
(4) REFERENCES

12
(1) POINTERS:
A pointer is a memory variable that stores a memory address.
Syntax is
Data type *variable name;
Ex : int x=2,*p;
p=&x
cout << “value of x = “<<*p;
The output of the above statement is
Value of x =2

(2) FUNCTIONS:
A function is a self-contained block or a sub-program of one or more statements that perform
a special task when called.
Ex:

main() funA()
{ {
funA(); ……….
…….. return;
} }

funA() is a user defined functions. These are invoked from the body of main. After Execution fo the
funA(), the program control returns back to the calling function main().

(3) ARRAYS:
Array is a collection of elements of similar data types in which each element is located in
separate memory location. For example,
int b[4]={2,3,4,6};
cout <<”Value of first element is “<<b[0];
the cout statement displays the value of first element. The b[0] refers to first element. So the output is
value of first element is 2.
(4) REFERENCES:
They declare aliases for object variables and allow the programmer to use variable by reference.
The Reference operator is &.
Syntax:
Datatype & reference variablename=variable name
Example
int q=20;
int &qt=q;
qt=qt*2

Now , the contents of q and qt will be 40. because, any changes made in one of the variable causes
change in both the variables.
Dereferencing operator (*):
The asterisk (*) is a variable expression used to declare a pointer to a given type. In the example int
*x; where, x is a pointer of integer type,

Example:
int b=10;
printf ( “%u” , &b);---- displays the address of the variable b.
printf(“%d”,*(&b));---- display the value of variable b.

13
(C)USER-DEFINED DATA TYPE:

User defined data types are of the following types:


(1) structures and classes
(2) union
(3) enumerated data type

1. structure and classes:


keyword struct:
The struct is a keyword and used to combine variables of different data types into a single
record.
Syntax:
Struct [< struct name >
<data-type> <variable-name 1, variable-name 2 >;
<data-type> <variable-name 3, variable-name 4 >;
} < structure variable declarations >;

Struct name: An optional tag name that defines the structure type.
Structure variables: These are member variables and hold data.
Example:
struct my_friend
{
char fname [80], phone [80];
int age, height;
} friendA ;

2. Union:
A union is same as compared to a struct, the only difference is that it lets the user to declare variables
that share same memory space.
Syntax:

union [<union name>]


<data-type> <variable name>;
} [<union variables name>];
Example:
Union charorint
{
char c;
int I;
} number;
The union member variable number . c and number . I uses the same memory location in memory.

3.Enumerated data type

Te enum is a keyword. It is used for declaring enumeration data types. The programmer can declare new
data type and define the variables of these data types that can hold.
Syntax:
eum enumeratedvaraiable { value};
enum logical { false, true };
This statement declares a user-defined data type. The keyword enum is followed by the tag name logical.
The enumerators are the identifiers false and true.
Cout<<”True “<<true<<”False <<false;
14
The cout statement displays the contents of true and false.The true contains value 1 and false contains value
0.
TYPECASTING
Typecasting is essential when the value of variables are to be converted from one type to another type.
C++ allows implicit and explicit type conversion.
(1) Explicit typecasting:
Sometimes errors may be encountered in the program while using implicit typecasting. The explicit type
conversion is done using typecast operator. The compiler is instructed to do type conversion using typecast
operator.
data-type name (expression)
Example:
float x;
x=(int) 5/2.0
the above expression returns the value 2.5.

(2) Implicit type conversion:


When the compiler carries type conversion itself by using inbuilt data types in routines then it is called
implicit type conversion.
Example:
char x=65;
cout<<x;
The output of the above statement is ‘A’
SCOPE ACCESS OPERATOR
The Scope access ( or resolution) operator :: ( two semicolons) allows a programmer to access a global
( or file duration) name even if it is hidden by a local re-declaration of that name.
Exampale
int a=5;
main()
{
int a=10;
cout <<”a =”<<a;
cout<<”::a =”<<::a;
}
Ouput is
a=10
:a=5

MEMORY MANAGEMENT OPERATORS


C++ provides operators which help us to allocate and release the memory. These new operators are new
and delete. The new operator creates an object and delete destroys the object.
The new operator:
Pointer memory variable = new data type [size];
The new operator allocates memory of specified type and returns back the starting address to the pointer
memory variable.
Example:
(a) pv= new int;
In example (a) pv is a pointer variable of integer type.
The delete operator:
The delete operator frees the memory allocated by the new operator. This operator is used when the
memory allocated is no longer usable in the program.
Syntax:
(a) delete < pointer memory variable >
15
(b) delete [element size] < pointer memory variable>
example:
(a) delete p;
(b) delete [5] p or delete [ ]p;
Example program
main()
{
int *p=new int;
cout<<”Enter number”;
cin>>*p
*p=*p+1;
cout<<”sum is”<<*p;
delete p;
}
Output:
Enter number 5
Sum is 6
Type modifiers are signed, unsigned, short, and long are type modifiers.
4 CONTROL STRUCTURES
The Decision Making Statements
The decision making statements are
1. The if statement
2. The switch()
1. The if statement
a. simple if statement
b. if else statement
c. nested if else statement
d. if else if ladder statement
a.Simple if statement:
Syntax for the simplest if statement:
If (expression)
{
Statement1;
Statement1;
}
Statement 3;
When the expression is true, the statement in if block is executed. when the expression is false the if block is
skipped and the statement (statement3) after if block is executed.
b. The if else statement
The format of if….else statement is as follows :
if (the condition is true)
execute the statement1;
else
execute the statement2;
OR
if ( expression is true)
{
Statement 1; → if block
Statement 2;
}
else
{
Statement 3;
16
Statement 4; → else block
}
Both if and else block contain statements. when the expression is true if block contain statements. When the
expression is true if block is executed otherwise else block is executed.
c. THE NESTED if-else STATEMENT
Syntax of if-else…if statement:
if ( condition)
{
Statement 1; ─> if block
Statement 2;

}
else if (condition)
{
Statement 3; ─> else block
Statement 4;
}
else
{
Statement 5;
Statement 6;
}
Rules for applying nested if .. else.. if statements
1. Nested if. . else can be chained with one another.
2. If the condition is false, control passes to else block where condition is again checked with the if
statement. This process continues till there is no if statement in the last else block.
3. If one of the if statement satisfies the condition, other nested if. . else will not be executed.
d. THE if-else-if Ladder Statement
A common programming construct is the if-else-if ladder, sometimes called the if-else-if staircase
because of it’s appearance. It’s general form is
if ( expression) statement block1;
else if (expression) statement block2;
else if (expression) statement block3;
. . .
else statement block n;
The conditions are evaluated from the top. As soon as a true condition is met, the associated statement
block gets executed. if none of the conditions are met then the final else block gets executed.
Example program
#include <iostream.h>
main()
{
int x;
cout<,”enter number”;
cin>>x;
if(x%2==0)
cout<<”Given No. is even”;
else
cout<<”Given No. is odd”;
}

output is
enter number
3
17
Given no. is odd

2. THE switch case STATEMENT


The switch statement evaluates the expression and then looks for its value among the case constants.
if the value is matched with a case constant then that case constant is executed until a break statement is
found or end of switch block is reached.
The default is normally present at the bottom of switch case structure.
Syntax of the switch case statements:
switch (variable or expression)
{
Case constant A:
Statement;
break;
case constant B:
statement;
break;
default :
statement;
}
Example program
main()
{
char x;
int a,b;
cout<<”enter two number”;
cin>>a>>b;
cout<<”ener arithmetic symbols”;
cin>>x;
switch(x)
{
case ‘+’:c=a+b;break;
case ‘-‘:c=a-b;break;
}
cout<<”output is “<<c;
}
output:
enter two number 5 7
enter arithmetic symbols +
ouput is 12
THE jump STATEMENT:
C++ has four statements that perform an unconditional control transfer. These are return (), goto,
break , and continue.
(i) THE goto STATEMENT
The general format is ……
goto label; ……
…… Label:

Where, label is any valid label either before or after goto. The label must start with any character and
can be constructed with rules used for forming identifiers.
(ii) THE break STATEMENT
The break skips from the loop or the block in which it is defined.the control then automatically
passes on to the first statement after the loop or the block.
(iii) THE continue STATEMENT

18
It is useful in programming situation when you want particular iterations to occur only up to
some extent or you want to neglect some part of your code. the programs on break and continue can be
performed by the programmer.
LOOPS stucture IN C++
The c++ language supports three types of loop control structures. they are
1. for loop
2. while loop
3. Do while loop
1. THE for LOOP
Syntax of for loop:
for (initialization; condition; increment/decrement)
Statement block;
The initialization is an assignment statement that is used to set the loop control variable(s).
The condition is a relational expression that determines the number of the iterations desired or the condition
to exit the loop.
The increment or the re-evaluation parameter decides how to change the state of the variable(s). the body of
the loop may consist of a block of statements.
2.THE while LOOP
Syntax of while loop:
While (test condition)
{
Body of the loop
}
The test condition may be any expression. the loop statements will be executed till the condition is
true.
if the condition is true, then the body of the loop is executed. When the condition becomes false the
execution will be out of the loop.
3.THE do-while LOOP
Syntax of do while loop:
do
{
Statements;
}
While (condition);
In do-while, the condition is checked at the end of the loop. The do-while loop will execute al least once
even if the condition is false initially. The do-while loop executes until the condition becomes false.
Example program:
main()
{
int i, sum=0;
for(i=1;i<=5;i++)
sum=sum+i;
cout<<”Sum is :”<<sum;
}
output is
sum :15
Summary
 The decision making statements are
o The if statement
o The switch()
 The c++ language supports three types of loop control structures. they are
 for loop
 while loop
 Do while loop
19
 The break statement skips from the loop
 The Continue Statement continue to the loop
FUNCTIONS IN C++
Functions
C++ language is that a large sized program can be divided into smaller ones. The smaller
programs can be written in the form of functions. The message passing between a caller (calling function )
and callee ( called function ) takes place using arguments.
The advantages of functions:
a) support for modular programming.
b) Reduction in program size.
c) Code duplication is avoided.
d) Functions can be called repetitively.
e) Aset of functions can be used to form libraries.
The C++ supports two types of functions.
They are (1) library functions
(2) User defined functions.
The library functions can be used in any program by including respective header files . The
header files must be included using # include preprocessor directive .
The user-defined functions are those that are define in a class . They are called as member
functions .
Parts Of Function :-
A function has the following parts:-
(a) Function prototype declaration
(b) Definition of a function ( function declarator )
(c) Function call
(d) Actual and formal arguments
(e) The return statement
(1) Function prototypes:-
A prototype statement helps the compiler to check the return and argument type of the function .
It tells the compiler
(a) The name of the function ,
(b) The type of value return ,
(c) The type and number of arguments.
The following statements are the examples of the function prototypes .
(a) void show ( void );
(b) float sum ( float , int ) ;
(c) float sum ( float x , int y );
(2) Function definition :-
The first line is called function declarator and is followed by function body . The block of statements
followed by function declarator is called as function definition .The function body is enclosed with curly
braces .
Ex:
Float sum(float a,int b)
{
Set of statements
}
(3) Function call :-
It gets activated only when a call to function is invoked .A function must be called by its name ,
followed by argument list enclosed in parenthesis and terminated by semi-colon .
Ex: void main()
{
cout<<sum(12.5,7);
}
(4) Actual and formal arguments :-
20
The arguments declared in caller function and given in the function call are called as actual arguments
. The arguments declared in the function declarator are known as formal arguments .
(5) The return statement :-
The return statement is used to return value to the caller function . The return statement returns only
one value at a time .
Syntax of return statement is
return ( variable name ); or return variable name;
The parenthesis is optional
Ex: float sum(float a, int b)
{
return(a+b);
}
Example program
//Main Program
void main()
{
float a;
int b;
cout<<”enter number”;
cin>>a>>b;
cout<<”sum “<<sum(a,b);
}
// sub program
float sum(float a, int b)
{
return(a+b);
}
output is
enter number 3 4
sum 7

Passing arguments to function


The main objective of passing argument to function is message passing . The message passing is also
known as communication between two functions (i.e) between caller and callee function .
There are three methods are
(a) Call by value (pass by value ).
(b) Call by address (pass by address ) ,
(c) Call by reference (pass by reference ).
( 1) Pass by value:-
In this type , value of actual argument is passed to the formal argument and operation is done on the
formal arguments . Any change in the formal argument does not effect the actual argument because formal
arguments are photocopy of actual arguments .
(2) Pass by address :-
In this type , instead of passing values , addresses are passed . Funtion operators on addresses rather
than values . Here the the formal arguments are pointers
to the actual arguments . Hence changes made in the arguments are permanent .
(3) Passing by reference:-
C++ reference types , declared with & operator are nearly identical but not exactly same to pointers
types . They declare aliases for object variables and allow the programmer to pass arguments by reference to
function . The reference decelerator ( &) can be used to declare reference outside functions .
Example program void funA(int s);
#include <iostream.h> void funB(int &)
void main() void funC(int *)
{ int s=4;
21
funA(s); //passed by value k++;
cout<<”Value is “<<s; }
funB(s); //passed by reference void funC(int *j)
cout<<”Value is “<<s; {
funC(&s); //passed by address ++*j;
cout<<”Value is “<<s; }
}void funA(int i) output is
{ i++; } value is 4
void funB(int &k) value is 5
{ value is 6

Default arguments in function


When the function is called with less parameter or without parameter , the default values are used for
the operation in case the function is define before caller function.
Hence, the default arguments are placed in function declarator .
The complier checks for the default values in function prototype and function declarator and provides these
values to those arguments that are omitted in function call.
Using default arguments , the function call can continue to use previous arguments with the new arguments .
Example :-
void main()
{
int sum (int a , int b=10 ,int c=15,int d = 20 )
int a=2;
cout<<”Sum =”<<sum(a);
}
sum(int i, int j, int k, int l)
{
return(i+j+k+l)
}
Inline function
When a function is declared as inline , the compiler copies the code of the function in the calling
function .
Inline function is mostly useful when calling function is small.
Inline function needs more memory space.
Advantage
1. Passing of control between caller and callee functions is avoided.
2. It increases execution performance in terms of speed.
inline function name
{
statement 1;
statement 2; // function body
}
Example:-
inline float square ( float k )
{
return ( k*k);
}
The following situation where Inline functions may not work
(1) The function should not be recursive .
(2) Function should not contain static variables .
(3) Function containing control structure statements such as switch , if , for loop etc…
(4) The function main ( ) cannot work as inline ,
Function overloading

22
Defining multiple functions with same name is known as function overloading or function
polymorphism. The overloaded function must be different in its argument list and with different data types.
Principles of Function Overloading :-
(1) If two functions have the similar type and number of arguments, the function cannot be
overloaded
(2) Passing constant values directly instead of variables also resulting ambiguity.
(3) The compiler attempts to find an accurate function definition that matches in types and
numbers of arguments and invokes the function.
(4)If there is no accurate match found , compiler makes the implicit conversion of actual
arguments.
(5 ) If internal conversion fails user-defined conversion is carried out with implicit conversion and
integral promotion .
Example
void main()
{
int sum(int,int);
int sum(int,int,int);
int a,b,c;
cout<<”enter input”;
cin>>a>>b>>c;
cout<<”Sum of two values “<<sum(a,b);
cout<<”Sum of three values
“<<sum(a,b,c);
}
int sum(int x,int y)
{
return(x+y);
}
int sum(int x, int y, int z)
{
return(x+y+z);
}

output is
enter input 3 5 6
sum of two values 8
sum of three values 14

23
Library function
ceil and ceil1 : round up the given float number.
floor and floor1: round down the float number.
modf : breaks double into integer and fraction elements
modf1 : breaks long double into integer and fraction elements.
abs : returns the absolute value of an integer.
fabs : returns the absolute value of a floating point number
labs : returns the absolute value of a long number
complex : creates a complex number from given real and imaginary parts .
real : returns the real parts of the complex
imag :returns the imaginary part of the complex number
conj : returns complex conjugate of a complex number.
Lvalues and Rvalues
(1) Lvalues ( Left values );
lvalue could suitably stand on the left(the assignment side ) of an assignment statement .
(2)Rvalues ( Right values ):-
x+y=z is invalid because the expression on the left is not related to a variable such
expressions are often called rvalues .
The const argument :-
The constant variable can be declared using const keyword .The const keyword makes
variable value stable . The constant variable should be initialized while declaring .
Syntax :-
) const <variable name > = <value > ;
Ex:
int const x // in valid

24

You might also like