Unit-1 in C++
Unit-1 in C++
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.
Programming Paradigms:-
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.
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.
(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
};
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.
(7) Polymorphism:-
Polymorphism allows the same function to act differently in different classes.Allowing objects of
different classes to share the same external interface.
Dash Object
Display(dash)
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)
Clog ------------ A fully bufferd version of cerr .It controls error messages
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.
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
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.
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 ?,:
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
(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:
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:
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.
}
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
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
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