Final UNIT-1 - C++
Final UNIT-1 - C++
Final UNIT-1 - C++
BSc CS, IT, CT, SS, CSA, MM & B.C.A (Regular) –II SEMESTER
CORE 3: C++ PROGRAMMING
UNIT-I
Staff Name: S. Ganeshmoorthy MCA., M.Phil., MBA (Ph.D.)
-----------------------------------------------------------------------------------------------------------------------------------------
UNIT I: Introduction to C++ - key concepts of Object-Oriented Programming –Advantages – Object
Oriented Languages – I/O in C++ - C++ Declarations. Control Structures : - Decision Making and
Statements : If .. else ,jump, goto, break, continue, Switch case statements - Loops in C++ : for,
while, do - functions in C++ - inline functions – Function Overloading.
------------------------------------------------------------------------------------------------------------------------------
Introduction to C++
Synopsis
1. Introduction
2. Object oriented programming language
3. Evolution of C++
4. Difference Between C AND C++
5. Key Concepts of Object Oriented Programming (OOP)
Object
Class
Data abstraction
Data encapsulation
Inheritance
Polymorphism
Dynamic binding
Message passing
6. Advantage of OOP
7. Disadvantage OF OOP
Introduction
C++ is a multi-paradigm programming language that supports object oriented programming
(OOP) concept.
It is created by Bjarne Stroustrup in 1983 at Bell labs
It is an extension of C programming and the programs written in C language can run in C++
compiler.
The development of C++ actually began four years before its release, in 1979.
It did not start with the name C++.
Its first name was C with classes.
In the late part of 1983, C with classes was first used for AT&T’s internal programming needs.
Its name was changed to C++ later in the same year.
It is of course also used in a wide range of other application domains, notable graphics
programming.
C++ supports inheritance through class derivation.
Dynamic binding is provided by Virtual class function.
1
Evolution of C++
Object
Example
o Apple, orange, and mango are the members of fruit
Fruit mango;
In the above example fruit is a class, where class creates an object called mango that belonging
to the class fruit.
3
Data Abstraction
Hiding internal details and showing functionality is known as Data abstraction.
For example: phone call, we don't know the internal processing.
In C++, we use abstract class and interface to achieve abstraction.
It is the process of providing only essential information about the data to the outside world
and hiding the background details or implementation known as data abstraction
Data Encapsulation
Encapsulation is the process of combining data and functions into a single unit called class
The wrapping up of data into a single unit is known as Data encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
Encapsulation means objects internal structure is hidden from the outside world.
Inheritance
Inheritance is the process of deriving a new class from the base class is known as inheritance.
Example
The bird robin is a part of flying bird which is again a part of the class bird.
Bird
Attributes: feathers, lay eggs
Flying bird
Attributes:
Peacock
Attributes:
Polymorphism
Dynamic Binding
Binding refers to the process which is used for converting functions and variables into
machine language addresses.
Dynamic binding is the method of linking a procedure call to the relevant code that will be
executed only at run time.
4
Message passing or message communication
An object oriented program consist of a set of object that communicate with each other.
It involves following steps.
o Creating classes that define object (with behavior)
o Creating objects from class definitions
o Establishing communication among objects
Example
Advantages of OOP
Using inheritance, we can eliminate redundant code and use of existing class
Using data hiding helps the programmer to build secure programs
Using Encapsulation helps to packing of data and functions into single class
Using Message Passing techniques used for communication between objects
Software complexity can be easily managed.
Code reuse and recycling
Faster development
Lower cost of development
Higher quality of software
Improved software maintainability
Improved software development productivity
Easy to partition the work in a project based object
It is possible to have multiple objects
Disadvantages of OOP
It requires more data protection
Inability to work with existing system
Large program size
Not suitable for all types of problems for smaller problems It is in general not suitable
Introduction
Like structured programming, OOP concepts can be implemented using languages such as C
and Pascal.
A language is specially designed to support the oop concepts makes it easier to implement
them.
OOP is the style of programming that primrily supports encapsulation and object identity.
There are many languages which support object-oriented programming
The OOP languages are widely accepted by the programmer
o C++
o SmallTalk
o Charm++
o Java
5
o C++
Applications of OOP:
Real time systems
Object oriented databases
AI and Expert systems
Neural Networks and parallel programming
6
Decision support and office automation
Simulation and modeling
CAM/CAD systems
I/O in C++
Synopsis
1. Introduction
2. Include Directives and Namespaces
3. Keyboard and Screen I/O
4. Insertion Operator ( << )
5. Output Statements
6. Output Statements (String constant)
7. Output Statements (Expression)
8. Input Statements
9. Escape Sequences
10. Newline
11. Extraction Operator (>>)
12. Structure of C++
13. Simple C++ Program
Introduction
• C++ treats input and output as a stream of characters.
• Stream : sequence of characters (printable or nonprintable)
• The functions to allow standard I/O are in iostream header file or iostream.h.
• Thus, we start every program with
#include <iostream>
Using namespace std;
7
Output Statements:
Syntax
Cout statements can be linked together using << operator.
These examples yield the same output:
cout << “The answer is “ ;
cout << 3 * 4 ;
cout << “The answer is “ << 3 * 4 ;
Input Statements
SYNTAX
Cin >> Variable >> Variable . . . ;
Cin statements can be linked together using >> operator.
These examples yield the same output:
Cin >> x;
Cin >> Y;
Cin >> x >> Y;
8
Escape Sequences
• The backslash is called the escape character.
• It tells the compiler that the next character is “escaping” it’s typical definition and is using
its secondary definition.
• Examples:
– new line: \n
– horizontal tab: \t
– backslash: \\
– double quote \”
Newline
• Cout<<“\n” and cout<<endl both are used to insert a blank line.
• Advances the cursor to the start of the next line rather than to the next space.
• Always end the output of all programs with this statement.
Structure of C++
9
C++ Data Types
Local Variables
#include <iostream.h>
int main ()
{
int a, b; // Local variable declaration
int c; // Local variable declaration
a = 10; // actual initialization
b = 20; // actual initialization
c = a + b; //Output =?
cout << c; // Output = 30
return 0;
}
Global Variables
#include <iostream.h>
// Global variable declaration:
Int g;
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization
a = 10; // Output = ?
b = 20; // Output = 30
g = a + b;
cout << g;
return 0;
}
10
Declaration in C++
Synopsis
1. Introduction
2. Definition of Data Types
3. Classification of Data types:
4. Primary Data types
5. Integer Data type
6. Floating Point Data types
7. Character Data type
8. Enumerated Data type
9. Void Data type
10. Derived Data types
11. Declaration Syntax &Example
12. Primary Data types
13. Example program for Declaration of variables
14. Assigning Values to Variables
15. Tokens, keywords, identifiers, constants and strings and operators
Introduction
In C++ program a declaration is a statement that defines a data type, variable or its “holding
tank” for some sort of value like a number or character.
// Program description
#include directives
int main()
{
Constant declarations
Variable declarations
Executable statements
Return 0;
}
12
Floating Point Data types
Floating point data types are set of numbers with decimal value.
Every floating point value must contain the decimal value.
The floating point data type has two variants...
• float
• Double
We use the keyword "float" to represent floating point data type and "double" to represent
double data type in c.
Both float and double are similar but they differ in number of decimal places.
The float value contains 6 decimal places whereas double value contains 15 or 19 decimal
places.
The following table provides complete details about floating point data types.
The following table provides complete information about all the data types in c programming
language...
13
Enumerated Data type
An enumerated data type is a user-defined data type that consists of integer constants and
each integer constant is given a name.
The keyword "enum" is used to define enumerated data type.
Syntax:
Enum identifier {value1, value2,...value n}
It is used to declare the variables that can have one of the values enclosed within braces.
Example
Enum day {Monday, Tuesday....Sunday}
Enum day week_beg, week_end;
We can assign value like this
Week_beg=Sunday;
Week_end=Saturday;
If (week_beg==Thursday)
Week_end=Saturday)
The compiler automatically assigns integer digits beginning with 0 to all the enumeration
constants.
Thus the enumeration constants assign value1 as 0, value as 1 and so on.
However the automatic assignments can be overridden by assigning values explicitly to the
enumeration constants.
Variables
Variable tells to the compiler to allocate required amount of memory with specified variable name
and allows only specified data type values into that memory location.
In C programming language, the declaration can be performed either before the function as global
variables or inside any block or function.
But it must be at the beginning of block or function.
Declaration Syntax:
Data type variable Name;
Example
int number;
The above declaration tells to the compiler that allocates 2 bytes of memory with the name number
and allows only integer values into that memory location.
14
Primary Data types
The primary data types in C programming language are the basic data types.
All the primary data types are already defined in the system.
Primary data types are also called as Built-In data types.
The following are the primary data types in c programming language...
1. Integer Data type
2. Floating Point Data type
3. Double Data type
4. Character Data type
Type definition
This allows the user to define the identifier that would represent an existing data type.
The user defined type is later used to declare variables.
General form
Typedef type identifier;
Typedef – keyword
Type – existing data type
Identifier – new name given to the data type
Typedef cannot create a new type.
Using identifier the variables can be declared using following syntax.
15
An enumerated data type is a user-defined data type that consists of integer constants and each
integer constant is given a name.
The keyword "enum" is used to define enumerated data type.
Syntax:
Enum identifier {value1, value2,...value n}
It is used to declare the variables that can have one of the values enclosed within braces.
Example
Enum day {Monday, Tuesday....Sunday}
Enum day week_beg, week_end;
We can assign value like this
Week_beg=Sunday;
Week_end=Saturday;
If (week_beg==Thursday)
Week_end=Saturday)
The compiler automatically assigns integer digits beginning with 0 to all the enumeration constants.
Thus the enumeration constants assign value1 as 0, value as 1 and so on.
However the automatic assignments can be overridden by assigning values explicitly to the
enumeration constants.
Local Variables
It is visible and meaningful only inside the function in which they are declared.
Example:
/* Example of storage classes */
Int m; GLOBAL VARIABLES (before Main)
Main ( )
{
Int i; LOCAL VARIABLES (declared inside the function)
Float balance;
................
................
Function1 ( );
}
Function1 ( )
{
Int j;
Float sum;
..........
...........
}
Syntax:
16
Variable_name = constants;
Examples:
Initial_value = 0;
Final_value = 100;
Balance = 75.84;
Yes=’x’;
Tokens
The smallest individual units in a program are known as tokens
In a C++ program, collection of all the keywords, identifiers, operators, special symbols,
constants, strings and data values are called as tokens
They are
o Keywords (data types)
o Identifiers (variable name)
o Constants
o Strings
o Operators
Keywords
Keywords have a constant and fixed meaning and the meaning cannot be changed.
The keywords serve as building blocks for program statements.
All keywords must be written in lower case.
For eg: int, char, float etc all types of data types
int marks;
Char student Name [30];
Here, int and char are Keywords
17
Identifiers
It refers to the names of variables, functions and arrays.
It is a user defined name and consist of sequence letters and digits, with a letter as a first
character
int marks;
Char student Name [30];
Here, marks and student Name are identifiers
Constants
A constant refers to fixed values that do not change during the execution of program.
It refers to a sequence of digits.
int age=”21”;
Char student Name = ”AKIL”;
Here, 21 and AKIL are Constants Value that cannot change at the time of execution
18
Strings
A sequence of characters enclosed by double quotes.
The character may be any letter, digits, special characters and blank space.
A string constant is a collection of characters, digits, special symbols and escape sequences that
are enclosed in double quotations.
Example:
1.”Welcome to c programming”
2. “2001”
3. “Well done”
4.”34+23”
5.”d”
Control Structures
Synopsis
1. Introduction
2. Sequence
3. Repetition(loop or Iteration)
4. Selection(branching)
5. Flow control
6. Conditional statement)
Definition
Decision making statements are the statements that are used to verify a given condition and
decides whether a block of statements gets executed or not based on the condition result.
In c programming language, there are two decision making statements they are as follows...
1. if statement
2. switch statement
If statement in c++
In c++, if statement is used to make decisions based on a condition. The if statement verifies the
given condition and decides whether a block of statements are executed or not based on the
condition result. In c, if statement is classified into four types as follows...
1. Simple if statement
2. if - else statement
3. Nested if statement
4. if-else-if statement (if-else ladder)
Simple if statement
Simple if statement is used to verify the given condition and executes the block of statements
based on the condition result. The simple if statement evaluates specified condition. If it is TRUE,
it executes block of statements. If the condition is FALSE, it skips the execution of the block of
statements.
19
General syntax and execution flow of the simple if statement.
Simple if statement is used when we have only one option that is executed or skipped based on a
condition.
if - else statement
The if - else statement is used to verify the given condition and executes only one out of the
two blocks of statements based on the condition result. The if-else statement evaluates the
specified condition. If it is TRUE, it executes a block of statements (True block). If the condition
is FALSE, it executes another block of statements (False block).
20
The if-else statement is used when we have two options and only one option has to be executed
based on a condition result (TRUE or FALSE).
Nested if statement
Writing a if statement inside another if statement is called nested if statement. The general syntax
of the nested if statement is as follows...
The nested if statement can be defined using any combination of simple if & if-else statements.
21
if - else - if statement (if-else ladder)
Writing a if statement inside else of a if statement is called if - else - if statement. T
The if-else-if statement can be defined using any combination of simple if & if-else statements.
Switch statement in C
Consider a situation in which we have more number of options out of which we need to select only
one option that is to be executed. Such kind of problems can be solved using nested if statement.
But as the number of options increases, the complexity of the program also gets increased. This
type of problems can be solved very easily using switch statement. Using switch statement, one can
select only one option from more number of options very easily. In switch statement, we provide a
22
value that is to be compared with a value associated with each option. Whenever the given value
matches with the value associated with an option, the execution starts from that option. In switch
statement every option is defined as a case.
The switch statement has the following syntax and execution flow diagram..
The switch statement contains one or more number of cases and each case has a value
associated with it. At first switch statement compares the first case value with the switch
Value, if it gets matched the execution starts from the first case. If it doesn't match the switch
statement compares the second case value with the switch Value and if it is matched the
execution starts from the second case. This process continues until it finds a match. If no case
value matches with the switch Value specified in the switch statement, then a special case
called default is executed.
When a case value matches with the switch Value, the execution starts from that particular
case. This execution flow continues with next case statements also. To avoid this, we use "break"
statement at the end of each case. That means the break statement is used to terminate the switch
statement. However it is optional.
23
While Statement in C
Consider a situation in which we execute a single statement or block of statements repeatedly
for required number of times. Such kind of problems can be solved using looping statements
in C. For example, assume a situation where we print a message for 100 times. If we want to
perform that task without using looping statements, we have to either write 100 printf
statements or we have to write the same message for 100 times in a single printf statement. Both
are complex methods. The same task can be performed very easily using looping statements.
The looping statements are used to execute a single statement or block of statements repeatedly
until the given condition is FALSE.
C language provides three looping statements...
1. while statement
2. do-while statement
3. for statement
While Statement
The while statement is used to execute a single statement or block of statements repeatedly as
long as the given condition is TRUE. The while statement is also known as Entry control looping
statement.
The while statement has the following syntax...
24
At first, the given condition is evaluated. If the condition is TRUE, the single statement or block of
statements gets executed. Once the execution gets completed the condition is evaluated again. If it
is TRUE, again the same statements gets executed. The same process is repeated until the
condition is evaluated to FALSE. Whenever the condition is evaluated to FALSE, the execution
control moves out of the while block.
Do -while Statement in C
The do-while statement is used to execute a single statement or block of statements repeatedly as
long as given the condition is TRUE. The do-while statement is also known as Exit control
looping statement. The do-while statement has the following syntax...
25
The do-while statement has the following execution flow diagram...
At first, the single statement or block of statements which are defined in do block are executed.
After execution of do block, the given condition gets evaluated. If the condition is evaluated to
TRUE, the single statement or block of statements of do block are executed again. Once the
execution gets completed again the condition is evaluated. If it is TRUE, again the same
statements are executed. The same process is repeated until the condition is evaluated to FALSE.
Whenever the condition is evaluated to FALSE, the execution control moves out of the while
block.
for Statement in C
The for statement is used to execute a single statement or a block of statements repeatedly as
long as the given condition is TRUE. The for statement has the following syntax and execution
flow diagram...
26
At first, the for statement executes initialization followed by condition evaluation. If the condition is
evaluated to TRUE, the single statement or block of statements of for statement are executed.
Once the execution gets completed, the modification statement is executed and again the condition is
evaluated. If it is TRUE, again the same statements are executed. The same process is repeated
until the condition is evaluated to FALSE. Whenever the condition is evaluated to FALSE, the
execution control moves out of the for block.
27
Break, continue and goto in C
In c, there are control statements which does not need any condition to control the program
execution flow. These control statements are called as unconditional control statements. C
programming language provides the following unconditional control statements...
break
continue
goto
The above three statements does not need any condition to control the program execution flow.
Break statement
In C, the break statement is used to perform the following two things...
break statement is used to terminate switch case statement
Break statement is also used to terminate looping statements like while, do-while and for.
When a break statement is encountered inside the switch case statement, the execution
control moves out of the switch statement directly. For example consider the following
program...
When the break statement is encountered inside the looping statement, the execution control
moves out of the looping statements.
The break statement execution is as shown in the following figure.
28
Continue Statement
The continue statement is used to move the program execution control to the beginning of
looping statement. When continue statement is encountered in a looping statement, the
execution control skips the rest of the statements in the looping block and directly jumps to
the beginning of the loop. The continue statement can be used with looping statements like
while, do-while and for.
When we use continue statement with while and do-while statements the execution control
directly jumps to the condition. When we use continue statement with for statement the
execution control directly jumps to the modification portion (increment / decrement / any
modification) of the for loop. The continue statement execution is as shown in the following
figure...
29
Goto statement
The goto statement is used to jump from one line to another line in the program. Using goto
statement we can jump from top to bottom or bottom to top. To jump from one line to another
line, the goto statement requires a lable. Lable is a name given to the instruction or line in the
program. When we use goto statement in the program, the execution control directly jumps to
the line with specified lable.
30
Functions in C++
Synopsis
1. Introduction
2. Importance of function
3. Advantage of Code
4. C++ Functions
5. User defined Functions
6. Function Input and Output
7. Function definition
8. Syntax of Function Definition
9. Function Declaration
10. Example of Function Declaration & Function Definition
11. Function Call
12. Function Call Mechanism
13. Example of Function Call
14. Scope of Functions
15. Difference between Call by value and Call by Reference
16. Difference between Local Variable and Global Variable
17. Register Variable
18. function prototype
19. Inline function
20. Function overloading
Introduction: Function
It is group of statements that together perform a task.
Every C++ program has atleast one function, which is main (), and all the most trivial
programs can define additional functions.
Syntax of Function
Importance of Function
A program may need to repeat the same piece of code at various places.
It may be required to perform certain task repeatedly.
The program may become very large if functions are not used.
The real reason for using function is to divide program into different parts.
Advantages of Functions
Easier to Code
Easier to Modify
Easier to Maintain
Reusability
Less Programming Time
Easier to Understand
C++ Functions
31
C++ allows the use of both internal (userdefined) and external (Built in) functions.
External functions are usually grouped into specialized libraries (e.g., iostream, stdlib, math,
etc.)
Function definition
A set of statements that explains what a function does is called FUNCTION Definition
A function definition can be written at:
• Before main() function
• After main() function
• In a separate file
{
Statement 1;
Statement 2;
:
: Function Body
:
Statement N;
}
Function Declaration
It tells the compiler about function name, return type, and parameters
Function declaration is the model of a function.
It is also known as FUNCTION PROTOTYPE.
It provides information to compiler about the structure of function to be used in program.
It ends with semicolon (;).
It consists of:
o FUNCTION NAME
o FUNCTION RETURN TYPE
o NUMBERS & TYPES OF PARAMETERS
32
Syntax of Function Declaration
Function Call
The statement that activates a function is known as FUNCTION CALL.
The following steps take place when a function is called:
1. The control moves to the function that is called.
2. All statements in function body are executed.
3. Control returns back to calling function.
33
Example of Function Call
Scope of Functions
Area in which a function can be accessed is known as SCOPE OF FUNCTION.
These are two types:
1. Local Function
A function that is declared in another function is called Local Function.
2. Global Function
A function that is declared outside any function is called Global Function.
CALLING A FUNCTION
Functions are called by their names.
If the function is without argument, it can be called directly using its name.
But for functions with arguments, we have two ways to call them,
1. Call by Value
2. Call by Reference
34
35
Difference between Local variable and Global variable
Local Variable Global variable
Local variables are declares within a function. Global variables are declares outside any
function
It can be used only in function in which they Global variables can be used in all function.
declared.
Local variable are destroyed when control leave Global variable are destroyed when the program
the function. is terminated.
Local variables are used when the vales are to be Global variables are used when values are to be
used within a function. shared among different functions.
A program that calls a function for five times using loop & also using static (local) variable.
A local variable declared with keyword STATIC is called STATIC VARIABLE.
It is used to increase the lifetime of local variable.
This program declare function Fun ( ).
Function declare static variable
Initializes it to 0.
The main ( ) function calls five time.
Using FOR LOOP & Last statement display value of “n”.
#include <iostream>
Using namespace std;
Int fun();
Int main()
{
int I;
for( i=0;i<=5;i++)
fun();
return 0; }
Int fun()
{
static int n=0;
n++
cout<<“value of n=“<<n<<endl;
}
Register Variable
A variable declared with keyword register is known as Register variable.
The value of register is stored in Registers instead of RAM because Registers are faster than
RAM so value stored in Registers can be accessed faster than RAM.
36
Inline function
Synopsis
1. Introduction
2. Definition for inline function
3. Syntax of Inline function
4. Example Program For Inline Function
5. Output
6. Working of inline function
Introduction
It can be implemented using the keyword inline
It is a request to the compiler
This function cannot be inline by the compiler
The complicated functions will not be inline
Inline function-header
{
Function body
}
Example
Inline double cube(double a)
{
Return(a*a*a*);
}
Example Program For Inline Function
#include <iostream.h>
Inline int cube(int s)
{
Retrn s*s*s;
}
Inline int inc(int a)
{
Return ++a;
}
Int main()
{
Int a=11;
Cout<<The cube of 3 is:”<<cube(3)<<”\n”;
Cout<<”Incrementing a:”<<inc(a) <<”\n”;
Return 0;
}
37
Output
Function prototyping
Synopsis
1. Introduction
2. Syntax of function prototype
3. Example
4. Declaration of Function Prototype
5. Uses of function prototype
Introduction
If the function should be declared before they are used in a program then it is called function
prototyping.
Declaration of a function is made through a function prototype
<type><function identifier><arguments>;
Example
#include <iostream.h>
Void fun (char name [ ]); Function prototype (declaration of function)
Void main( )
{
Char n[ ]={“C++ programming…”};
Fun (n);
}
Void fun(char name [ ] ) Function definition
{
Cout <<name;
}
38
Uses of function prototype
Function Overloading
Synopsis
1. Introduction
2. Definition of function overloading
3. Declarations of function overloading
4. Example program of function overloading
5. Output
Introduction
The process of using same function for different purposes is called function overloading
//Function calls
#include<iostream.h>
Using namespace std
39
{
Cout<<”The Integer number is: “<<i<<endl;
}
Void print (float f)
{
Cout<<”The floating number is: “<<f<<endl;
}
Void print (char const *c)
{
Cout<<”The Char* is: “<<c<<endl;
}
Int main()
{
Print(10);
Print(10.10);
Print(“ten”);
Return 0;
}
Output:
The Integer number is: 10
The floating number is: 10.10
The Char* is: ten
40