Final UNIT-1 - C++

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

SREE NARAYANA GURU COLLEGE, KG CHAVADI

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.

Object oriented programming language


 It is a programming paradigm based on the concept of object which can contain data in the
form of fields, code and procedures.

1
Evolution of C++

S.NO YEAR DESCRIPTION


1 1960 ALGOL developed by International Group
2 1967 BCPL developed by Martin Richard
3 1970 B developed by Ken Thompson
4 1972 Traditional C developed by Dennis Ritchie
5 1978 K & R C developed by Kernighan & Dennis Ritchie
6 1979 Stroustrup starts to work on “C with Classes” in Bell Labs
7 1980 C++ developed by Bjarne Stroustrup
8 1983 “C with Classes” renamed to “C++”
9 1985 The first edition of <The C++ Programming Language>
10 1989 C++ 2.0 version was released
11 1998 The First ISO Standard (C++ 98)
12 2003 C++03, bug fixes of C++98
13 2011 C++11,a major revision
14 2014 C++14,bugfixes and small improvements on C++11
15 2017 Planned C++17, the upcoming major version

DIFFERENCE BETWEEN C AND C++


C C++
C++ is non-Procedural i.e. Object oriented
C is Procedural Language.
Language.
Top down approach is used in Program Bottom up approach adopted in Program
Design. Design.
Multiple Declaration of global variables are Multiple Declaration of global variables are
allowed. not allowed.
C++ allows the declaration of variable
C requires all the variables to be defined at
anywhere in the scope i.e. at time of its First
the starting of a scope.
use.
In C, malloc () and calloc () Functions are
In C++, new and delete operators are used
used for Memory Allocation and free ()
for Memory Allocating and Deallocating.
function for memory Deallocating.
Here input and output statements are scanf and Here input and output statements are Cin
printf and Cout
C programs are divided into Procedures and C++ programs are divided into Functions
Modules and Classes
In C you can’t use function in structure In C++ you can use function in structure
Does not provide features of Namespace Provide features of Namespace

Key Concepts of Object Oriented Programming (OOP)


 The major purpose of C++ programming is to introduce the concept of object orientation to
the C++ programming language.
 Object Oriented Programming is a paradigm that provides many concepts such as
inheritance, data binding, polymorphism etc.
 The programming paradigm where everything is represented as an object is known as truly
object-oriented programming language.
 Smalltalk is considered as the first truly object-oriented programming language.
 OOPs (Object Oriented Programming System)
 Object-Oriented Programming is a methodology or paradigm to design a program using
classes and objects.
2
 It simplifies the software development and maintenance by providing some concepts:

Concepts of Object Oriented Programming (OOP)


1. Object
2. Class
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message passing

Object

 Object is an basic run-time entities in a object oriented system


 Entities is an real world object
 Object may represent a person, place, or any item etc.
 Each object consist of
o Attributes (characteristics or data)
o Methods (functions )
Example
Object: STUDENT
DATA
Name
DoB
Marks
FUNCTIONS
Total
Average
Display
Classes
 Class is a collection of objects of similar type.
 Once a class has been defined, we can create any number of objects belonging to that class.
 Class is a user defined data types and behave like build in type of a programming language.

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

 Ability to take more than one form is known as polymorphism.


 Polymorphism allows the same function to act differently in different classes

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

Object Oriented Languages

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++

Properties of pure OOP and object based languages

Properties of Extended traditional language

Major features of OOP:


 Data encapsulation
 Data Hiding and access mechanisms
 Automatic Initialization and Clear up of objects
 Operator overloading

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;

Include Directives and Namespaces


• Include: directive copies that file into your program
• Namespace: a collection of names and their definitions. Allows different namespaces to
use the same names without confusion

Keyboard and Screen I/O


#include <iostream>

Insertion Operator ( << )


• Variable Cout is predefined to denote an output stream that goes to the standard output
device (display screen).
• The insertion operator << called “put to” takes 2 operands.
• The left operand is a stream expression, such as Cout.
• The right operand is an expression of simple type or a string constant.

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 ;

Output Statements (String constant)


• String constants (in double quotes) are to be printed as is, without the quotes.
Cout<<“Enter the number of candy bars ”;

OUTPUT: Enter the number of candy bars

• “Enter the number of candy bars ” is called a prompt.


• All user inputs must be preceded by a prompt to tell the user what is expected.
• You must insert spaces inside the quotes if you want them in the output.
• Do not put a string in quotes on multiple lines.

Output Statements (Expression)


• All expressions are computed and then outputted.
Cout << “The answer is ” << 3 * 4 ;
OUTPUT: The answer is 12

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.

Extraction Operator (>>)


• Variable cin is predefined to denote an input stream from the standard input device (the
keyboard)
• The extraction operator >> called “get from” takes 2 operands.
• The left operand is a stream expression, such as cin--the right operand is a variable of simple
type.
• Operator >> attempts to extract the next item from the input stream and store its value in the
right operand variable.

Structure of C++

Simple Program C++


//Hello world program /*Comment lines*/
#include<iostream.h> /*Header File*/
int main() /*Main Function*/
{
cout<<"\n*HELLO WORLD PROGRAM *\n"; /*Output Statements*/
}

9
C++ Data Types

Primary data type int, float, char, void


User defined data type structure, union, class, enumeration
Derived data type array, function, pointer, reference

Variables Scope in C++


 A scope is a region of the program and broadly speaking there are three places, where
variables can be declared
 Inside a function or a block which is called local variables,
 In the definition of function parameters which is called formal parameters.
 Outside of all functions which is called global variables.

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;
}

C++ Data Type


 Data used in c program is classified into different types based on its properties.
 In c programming language, data type can be defined as a set of values with similar
characteristics.
 All the values in a data type have the same properties.
 Data types in c programming language are used to specify what kind of value can be stored in a
variable.
 The memory size and type of value of a variable are determined by variable data type.
 In a c program, each variable or constant or array must have a data type and this data type
specifies
o How much memory is to be allocated
o What type of values are to be stored in that variable or constant or array.

Definition of Data Types


 Data type is a set of value with predefined characteristics.
 Data types are used to declare variable, constants, arrays, pointers and functions.

Classification of Data types:


1. Primary Data types (Basic Data types OR Predefined Data types)
11
2. Derived Data types (Secondary Data types OR User defined Data types)
3. Enumeration Data types
4. Void Data type

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

Integer Data type


 Integer data type is a set of whole numbers.
 Every integer value does not have the decimal value.
 We use the keyword "int" to represent integer data type in c.
 We use the keyword int to declare the variables and to specify return type of a function.
 The integer data type is used with different type modifiers like short, long, signed and
unsigned.
 The following table provides complete details about integer data type

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.

Character Data type


 Character data type is a set of characters enclosed in single quotations.
 The following table provides complete details about character data type

 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.

Void Data type


 The void data type means nothing or no value.
 Generally, void is used to specify a function which does not return any value.
 We also use the void data type to specify empty parameters of a function.

Derived Data types


 It is a data types that are derived out of the primary data types ( pointers, arrays, function)
 Derived data types are user-defined data types.
 The derived data type
 s are also called as user defined data types or secondary data types.
 In c programming language, the derived data types are created using the following concepts...
 Arrays
 Structures
 Unions
 Enumeration

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

Example program for Declaration of variables

Main( ) /* ………….Program Name…………..*/


{
/* ……………………….Declaration…………………..*/
Float x, y;
Int code;
Short int count;
Long int amount;
Double deviation;
Unsigned n;
Char c;
/*…………..computation………*/

….
….
}/*……….program ends……….*/

User defined type declaration


 It consist of two types
1. Type definition
2. Enumerated 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.

Identifier var1, var2....varn;


Examples:
Typedef int units;
Units batch1, batch2;

Enumerated Data type

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.

Global and local variables:


Global variables
 It is visible to all functions in the file.
 It is necessary to declare the variable before the main function.
 No need to declare the global in all functions.
 It is also known as external variables.

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;
..........
...........
}

Assigning Values to Variables

 Values can be assigned to variables using the assignment operator =.

Syntax:
16
Variable_name = constants;
Examples:
Initial_value = 0;
Final_value = 100;
Balance = 75.84;
Yes=’x’;

 C permits multiple assignments in one line.


 For example
Initial_value = 0; final_value = 100;
Are valid statments.

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

Example for Keywords

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

Example for Identifiers

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.

Example for Constants

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).

General syntax and execution flow of the if-else statement

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

General syntax of the if-else-if statement is as follows...

 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...

 The while statement has the following execution flow diagram..

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

return-type function-name (parameters)


{
// function-body
}

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.)

User defined Functions

Function Input and Output

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

Syntax of Function Definition

Return-type Function-name (parameters)  Function header

{
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

Example of Function Declaration & Function Definition

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.

Function Call Mechanism

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

Difference between Call by value and Call by Reference

Call by value Call by Reference


Call by value passes the value of actual parameter Call by reference passes the address of actual
to formal parameter. parameter to formal parameter.
Actual & formal parameter refer to different Actual & formal parameter refer to same memory
memory location. Location.
It requires more memory. It requires less memory.
It is less efficient. It is more efficient.

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.

Syntax for declaring is:

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

Definition for inline function


 It is a function that in expanded in line when it is invoked (called)
 It must be defined before they are called
 Inline keyword sends a request , not a command to the compiler

Syntax of Inline function

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

The cube of 3 is: 27


Incrementing a: 12

Working of inline function

 It is just a code replacement instead of the function call


 It is a need of stack storage and other special mechanism for function call and return
 It is used to store the return value and return address for function call and return process
 While passing the parameter the stack storage needed to store the parameter values, and from
the stack area the values moved to data area

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

Syntax of function prototype

<type><function identifier><arguments>;

Example

Void fun (char);


Int max(int, int);
Int max(int a, int b);

Declaration of Function Prototype

//Program for function prototype

#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

 To help the compiler to check the data requirement of the funciton


 A template is always used when declaring and defining a function
 When a function is called , the compiler uses the template to ensure that proper arguments are
passed and return value is treated correctly.

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

Definition of function overloading


 The process of using same functions name to create functions that perform a variety of
different task is called FUNCTION OVERLOADING.
 The function is based on the following ways
o Different argument –[void add(int a); void add(float a);]
o Different no of argument–[ void add(int a); void add(float a,float b);]
o Different function type-[int disp(), char disp()]
 For eg: add( ) function handles different types of data as shown in below
 If two or more function having same name but different arguments are known as function
overloading

Declarations of function overloading

Int add(int a, int b); //prototype1


Int add (int a, int b, int c); //prototype2
Double add(double x, double y); //prototype3
Doube add(int p,double q); //prototype4
Double add (double p, int q); // prototype5

//Function calls

Cout <<add(5,10); //uses prototype1


Cout<<add(5,10,15) //uses prototype2
Cout<<add(15,10.0); //uses prototype4
Cout<<add(12.5,7.5); //uses prototype3
Cout<< add(0.75, 5); //uses prototype5
Example program of function overloading

#include<iostream.h>
Using namespace std

Void print (int i)

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

All the Best

40

You might also like