Unit - 2
Functions in C++
 A Function is a reusable block of code designed to perform
a specific task.
 It helps break large programs into smaller, logical parts.
 Functions make code cleaner, easier to understand, and
more maintainable.
 Just like in other languages, C++ functions can take inputs
(called parameters), execute a block of statements, and
optionally return a result.
 C++ also supports advanced features like function
overloading, default arguments, and inline functions,
which give more flexibility compared to C.
Function Structure and Usage
Function Syntax in C++:
Return_type function_name(parameter_list)
{
//body of the function
}
 Each part has a specific role:
 Return type: Specifies what type of value the function returns. Use void if
there is no return value.
 Function name: The name you will use to call the function.
 Parameter list: Inputs that the function accepts. It can be empty if no
inputs are needed.
 Function body: The block of code that runs when the function is called.
Function Declaration vs Definition
 Function Declaration introduces the function to the compiler.
 It tells the compiler the return type, name, and parameters but does not
include the body.
 It ends with a semicolon.
// Declaration
int add(int, int);
 Function Definition provides the actual implementation of the function.
int add(int a, int b) {
return a + b;
}
Calling a Function
 Once a function is defined, you can use it by simply calling its name followed by
parentheses.
 This tells the program to execute the code inside that function.
 If the function takes parameters, you pass the required values inside the parentheses.
 If it doesn’t take any parameters, you just use empty parentheses.
void greet() {
cout << "Welcome to C++ Programming!" << endl; }
int multiply(int a, int b) {
return a * b; }
int main() {
greet();
int result = multiply(4, 5);
cout << "Multiplication result: " << result << endl;
return 0;
}
Types of Functions in C++
 In C++, functions can be broadly categorized based on two
criteria:
1. Based on origin:
 Library Functions: These are built-in functions provided
by C++ standard libraries, such as cout, sqrt(), abs(), and
getline(). You can use them by including appropriate
headers like <iostream>, <cmath>, or <string>.
 User-Defined Functions: These are functions created by
the programmer to perform specific tasks in the program.
2. Based on input and return type:
 User-defined functions can be further classified based on whether
they accept parameters or return a value:
1. No parameters, no return value: The function performs a task
but does not take input or return anything.
2. Parameters, no return value: The function takes input but does
not return a result.
3. No parameters, return value: The function returns a result but
does not take any input.
4. Parameters and return value: The function takes input and
returns a result.
C++ Arrays
C++ Arrays
 An array is a collection of elements of the same type
placed in contiguous memory locations.
 It allows you to store multiple values under a single name
and access them using an index.
 Arrays are one of the most basic and commonly used data
structures in C++ programming
Create an Array
 We can create/declare an array by simply specifying the
data type first and then the name of the array with its
size inside [] square brackets(better known as array
subscript operator).
 Syntax:
data_type array_name [size];
 Example:
int arr[5];
This will create an array with name arr that
can store 5 integers.
Initialize the Array
 Initialization means assigning initial values to array elements. We can
initialize the array with values enclosed in curly braces '{}' are assigned to
the array.
 For example: int arr[5] = {2, 4, 8, 12, 16};
int arr[5] = {2, 4, 8};
int arr[] = {2, 4, 8, 12, 16};
int arr[5] = {0};
Access Array Elements
 Elements of an array can be accessed by their position (called index) in the
sequence.
 In C++, indexes of an array starts from 0 instead of 1.
 We just have to pass this index inside the [] square brackets with the array
name as shown:
array_name[index];
It is important to note that index cannot be negative or greater than size of the
array minus 1. (0 ≤ index ≤ size - 1).
Update Array Elements
 To change the element at a particular index in an array, just use the “=”
assignment operator with new value as right hand expression while accessing
the array element.
array_name[index] = value;
 Example:
int arr[] = {2, 4, 8, 12, 16};
arr[0] = 90;
Traverse Array
 Traversing means visiting each element one by one.
 The advantage of array is that it can be easily traversed by using a
loop with loop variable that runs from 0 to size - 1.
 We use this loop variable as index of the array and access each
element one by one sequentially.
int arr[5] = {2, 4, 8, 12, 16};
// Traversing and printing arr
for (int i = 0; i < 5; i++)
cout << arr[i] << " ";
Size of Array
 The size of the array refers to the number of elements that can be stored in
the array.
 The array does not contain the information about its size but we can extract
the size using sizeof() operator.
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
Multi-Dimensional Arrays
 A multi-dimensional array is an array of arrays.
 To declare a multi-dimensional array, define the variable
type, specify the name of the array followed by square
brackets which specify how many elements the main array
has, followed by another set of square brackets which
indicates how many elements the sub-arrays have.
 string letters[2][4];
 string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
Types of Multidimensional Arrays
 We can have any number of dimensions in an array as per requirement, but
the complexity of handling them also increases exponentially.
 That is why, the most widely used multidimensional arrays are:
1. Two-Dimensional Array (2D Array)
2. Three-Dimensional Array (3D Array)
2D Array:
 A two-dimensional array in C++ is a collection of elements organized the
form of rows and columns. It can be visualized as a table or a grid.
3D Array:
 A three-dimensional array in C++ is a collection of elements organized in a 3D
cuboid-like structure. It can be visualized as a series of two-dimensional
arrays stacked on top of each other.
3-D Array:
Pointers and
References in C++
Overview of Pointers
Pointer Declaration
Pointer Assignment
Pointer Arithmetic
Pointer Arithmetic (Cont.)
Pointer Arithmetic (Cont.)
What is a Reference?
 A reference is an alias for an already existing
variable.
 Declared using the ampersand (&) operator (e.g.,
int& ref;)
 Must be initialized when declared
 Cannot be nullptr
 Cannot be reassigned to another variable
 Dereferenced implicitly
 Arithmetic operations not supported
Reference - More Explanation
 References provide safer, simpler access to
variables.
 Commonly used in function parameters and return
types
 Ideal for avoiding copying of large data
 Often used in operator overloading
int b = 20;
int& ref = b;
Key Differences
Conclusion
 Pointers: Use when dynamic memory allocation or
pointer arithmetic is needed.
 References: Use when you need a simple alias for
passing parameters or returning values without
copying.
 Prefer references over pointers when null values
and reassignment are not needed.
Function Objects
Function Objects (Functors)
 These are objects of a class that overload the
function call operator (operator()), allowing them
to be called like functions.
 Definition: A class is created with a public
operator() member function.
 Usage: Instances of this class can then be "called"
with arguments, just like regular functions.
 Benefits: Functors can maintain state (data
members) between calls, unlike plain
functions. They are widely used in the C++
Standard Library, particularly with algorithms and
containers for custom operations (e.g., custom
sorting criteria).
Classes & Structures
Classes & Structures
 In C++, both classes and structures are
user-defined data types that allow
grouping data members and member
functions into a single unit.
 They serve as blueprints for creating
objects, which are instances of these
types.
Classes
 Defined using the class Keyword.
 By default, members (data and functions) within a
class are private.
 This means they can only be accessed from within
the class itself or by its friend functions/classes.
 Classes are fundamental to Object-Oriented
Programming (OOP) in C++ and are commonly used
to encapsulate data and behavior, providing
controlled access through public interfaces.
 Support advanced OOP concepts like inheritance
and polymorphism.
Structures:
 Defined using the struct keyword.
 By default, members within a structure are
public. This means they can be accessed directly
from outside the structure.
 Historically, structures in C were primarily used to
group related data. In C++, structures have been
extended to also include member functions,
constructors, destructors, and support
inheritance, making them almost identical to
classes in functionality.
 Often used for simple data structures where
public access to members is acceptable or when
interfacing with C code that uses structures.
FRIEND FUNCTIONS
FRIEND FUNCTIONS
 A friend function is a function which is declared
within a class and is defined outside the class.
 It does not require any scope resolution operator
for defining.
 It can access private members of a class. It is
declared by using keyword “friend”.
 The scope resolution operator :: allows us to
define a member function of a class outside
the class definition.
How to declare Friend Function :
 Friend function declaration should be inside the
class using the Friend key word.
 Syntax:
friend ret_type
func_name(arguments);
 Definition of friend function is specified outside
the class.
 Function definition must not use keyword friend.
Friend function characterstics:
 It is not in scope of class.
 It cannot be called using object of that class.
 It can be invoked like a normal function.
 It has objects as arguments.
 Friend Functions are majorly used in operator
overlading.
 Friendship is not inherited by derived classes.
Inline Functions
Inline Functions:
 C++ inline function is powerful concept that is
commonly used with classes.
 If a function is inline, the compiler places a copy
of the code of that function at each point where
the function is called at compile time.
 Any change to an inline function could require all
clients of the function to be recompiled because
compiler would need to replace all the code once
again otherwise it will continue with old
functionality.
Defining an Inline Function
 To define an inline function, place the keyword
inline before the function name and define the
function before any calls are made to the
function.
 The compiler can ignore the inline qualifier in
case defined function is more than a line.
 inline int Max(int x, int y)
{
return (x > y)? x : y;
}
Passing Objects to
functions
Passing an Object as argument
 To pass an object as an argument we write the
object name as the argument while calling the
function the same way we do it for other
variables.
 Syntax:
function_name(object_name);
Returning objects from functions
 In C++, a function can return an object of a class.
 This helps send complete data (like multiple
values) from the function back to the main
program.
 The returned object can be used to call its
methods or access its data.
 This is useful in object-oriented programming for
better data handling.
Output:
THANK YOU

functions, arrays, friend function,.pptx

  • 1.
  • 2.
    Functions in C++ A Function is a reusable block of code designed to perform a specific task.  It helps break large programs into smaller, logical parts.  Functions make code cleaner, easier to understand, and more maintainable.  Just like in other languages, C++ functions can take inputs (called parameters), execute a block of statements, and optionally return a result.  C++ also supports advanced features like function overloading, default arguments, and inline functions, which give more flexibility compared to C.
  • 4.
    Function Structure andUsage Function Syntax in C++: Return_type function_name(parameter_list) { //body of the function }  Each part has a specific role:  Return type: Specifies what type of value the function returns. Use void if there is no return value.  Function name: The name you will use to call the function.  Parameter list: Inputs that the function accepts. It can be empty if no inputs are needed.  Function body: The block of code that runs when the function is called.
  • 5.
    Function Declaration vsDefinition  Function Declaration introduces the function to the compiler.  It tells the compiler the return type, name, and parameters but does not include the body.  It ends with a semicolon. // Declaration int add(int, int);  Function Definition provides the actual implementation of the function. int add(int a, int b) { return a + b; }
  • 6.
    Calling a Function Once a function is defined, you can use it by simply calling its name followed by parentheses.  This tells the program to execute the code inside that function.  If the function takes parameters, you pass the required values inside the parentheses.  If it doesn’t take any parameters, you just use empty parentheses. void greet() { cout << "Welcome to C++ Programming!" << endl; } int multiply(int a, int b) { return a * b; } int main() { greet(); int result = multiply(4, 5); cout << "Multiplication result: " << result << endl; return 0; }
  • 7.
    Types of Functionsin C++  In C++, functions can be broadly categorized based on two criteria: 1. Based on origin:  Library Functions: These are built-in functions provided by C++ standard libraries, such as cout, sqrt(), abs(), and getline(). You can use them by including appropriate headers like <iostream>, <cmath>, or <string>.  User-Defined Functions: These are functions created by the programmer to perform specific tasks in the program.
  • 8.
    2. Based oninput and return type:  User-defined functions can be further classified based on whether they accept parameters or return a value: 1. No parameters, no return value: The function performs a task but does not take input or return anything. 2. Parameters, no return value: The function takes input but does not return a result. 3. No parameters, return value: The function returns a result but does not take any input. 4. Parameters and return value: The function takes input and returns a result.
  • 9.
  • 10.
    C++ Arrays  Anarray is a collection of elements of the same type placed in contiguous memory locations.  It allows you to store multiple values under a single name and access them using an index.  Arrays are one of the most basic and commonly used data structures in C++ programming
  • 11.
    Create an Array We can create/declare an array by simply specifying the data type first and then the name of the array with its size inside [] square brackets(better known as array subscript operator).  Syntax: data_type array_name [size];  Example: int arr[5]; This will create an array with name arr that can store 5 integers.
  • 12.
    Initialize the Array Initialization means assigning initial values to array elements. We can initialize the array with values enclosed in curly braces '{}' are assigned to the array.  For example: int arr[5] = {2, 4, 8, 12, 16}; int arr[5] = {2, 4, 8}; int arr[] = {2, 4, 8, 12, 16}; int arr[5] = {0};
  • 13.
    Access Array Elements Elements of an array can be accessed by their position (called index) in the sequence.  In C++, indexes of an array starts from 0 instead of 1.  We just have to pass this index inside the [] square brackets with the array name as shown: array_name[index]; It is important to note that index cannot be negative or greater than size of the array minus 1. (0 ≤ index ≤ size - 1).
  • 14.
    Update Array Elements To change the element at a particular index in an array, just use the “=” assignment operator with new value as right hand expression while accessing the array element. array_name[index] = value;  Example: int arr[] = {2, 4, 8, 12, 16}; arr[0] = 90;
  • 15.
    Traverse Array  Traversingmeans visiting each element one by one.  The advantage of array is that it can be easily traversed by using a loop with loop variable that runs from 0 to size - 1.  We use this loop variable as index of the array and access each element one by one sequentially. int arr[5] = {2, 4, 8, 12, 16}; // Traversing and printing arr for (int i = 0; i < 5; i++) cout << arr[i] << " ";
  • 16.
    Size of Array The size of the array refers to the number of elements that can be stored in the array.  The array does not contain the information about its size but we can extract the size using sizeof() operator.
  • 17.
    string letters[2][2][2] ={ { { "A", "B" }, { "C", "D" } }, { { "E", "F" }, { "G", "H" } } }; Multi-Dimensional Arrays  A multi-dimensional array is an array of arrays.  To declare a multi-dimensional array, define the variable type, specify the name of the array followed by square brackets which specify how many elements the main array has, followed by another set of square brackets which indicates how many elements the sub-arrays have.  string letters[2][4];  string letters[2][4] = { { "A", "B", "C", "D" }, { "E", "F", "G", "H" } };
  • 18.
    Types of MultidimensionalArrays  We can have any number of dimensions in an array as per requirement, but the complexity of handling them also increases exponentially.  That is why, the most widely used multidimensional arrays are: 1. Two-Dimensional Array (2D Array) 2. Three-Dimensional Array (3D Array) 2D Array:  A two-dimensional array in C++ is a collection of elements organized the form of rows and columns. It can be visualized as a table or a grid. 3D Array:  A three-dimensional array in C++ is a collection of elements organized in a 3D cuboid-like structure. It can be visualized as a series of two-dimensional arrays stacked on top of each other.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 28.
    What is aReference?  A reference is an alias for an already existing variable.  Declared using the ampersand (&) operator (e.g., int& ref;)  Must be initialized when declared  Cannot be nullptr  Cannot be reassigned to another variable  Dereferenced implicitly  Arithmetic operations not supported
  • 29.
    Reference - MoreExplanation  References provide safer, simpler access to variables.  Commonly used in function parameters and return types  Ideal for avoiding copying of large data  Often used in operator overloading int b = 20; int& ref = b;
  • 31.
  • 32.
    Conclusion  Pointers: Usewhen dynamic memory allocation or pointer arithmetic is needed.  References: Use when you need a simple alias for passing parameters or returning values without copying.  Prefer references over pointers when null values and reassignment are not needed.
  • 33.
  • 34.
    Function Objects (Functors) These are objects of a class that overload the function call operator (operator()), allowing them to be called like functions.  Definition: A class is created with a public operator() member function.  Usage: Instances of this class can then be "called" with arguments, just like regular functions.  Benefits: Functors can maintain state (data members) between calls, unlike plain functions. They are widely used in the C++ Standard Library, particularly with algorithms and containers for custom operations (e.g., custom sorting criteria).
  • 36.
  • 37.
    Classes & Structures In C++, both classes and structures are user-defined data types that allow grouping data members and member functions into a single unit.  They serve as blueprints for creating objects, which are instances of these types.
  • 38.
    Classes  Defined usingthe class Keyword.  By default, members (data and functions) within a class are private.  This means they can only be accessed from within the class itself or by its friend functions/classes.  Classes are fundamental to Object-Oriented Programming (OOP) in C++ and are commonly used to encapsulate data and behavior, providing controlled access through public interfaces.  Support advanced OOP concepts like inheritance and polymorphism.
  • 40.
    Structures:  Defined usingthe struct keyword.  By default, members within a structure are public. This means they can be accessed directly from outside the structure.  Historically, structures in C were primarily used to group related data. In C++, structures have been extended to also include member functions, constructors, destructors, and support inheritance, making them almost identical to classes in functionality.  Often used for simple data structures where public access to members is acceptable or when interfacing with C code that uses structures.
  • 42.
  • 43.
    FRIEND FUNCTIONS  Afriend function is a function which is declared within a class and is defined outside the class.  It does not require any scope resolution operator for defining.  It can access private members of a class. It is declared by using keyword “friend”.  The scope resolution operator :: allows us to define a member function of a class outside the class definition.
  • 44.
    How to declareFriend Function :  Friend function declaration should be inside the class using the Friend key word.  Syntax: friend ret_type func_name(arguments);  Definition of friend function is specified outside the class.  Function definition must not use keyword friend.
  • 45.
    Friend function characterstics: It is not in scope of class.  It cannot be called using object of that class.  It can be invoked like a normal function.  It has objects as arguments.  Friend Functions are majorly used in operator overlading.  Friendship is not inherited by derived classes.
  • 47.
  • 48.
    Inline Functions:  C++inline function is powerful concept that is commonly used with classes.  If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.  Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality.
  • 49.
    Defining an InlineFunction  To define an inline function, place the keyword inline before the function name and define the function before any calls are made to the function.  The compiler can ignore the inline qualifier in case defined function is more than a line.  inline int Max(int x, int y) { return (x > y)? x : y; }
  • 51.
  • 52.
    Passing an Objectas argument  To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables.  Syntax: function_name(object_name);
  • 54.
    Returning objects fromfunctions  In C++, a function can return an object of a class.  This helps send complete data (like multiple values) from the function back to the main program.  The returned object can be used to call its methods or access its data.  This is useful in object-oriented programming for better data handling.
  • 55.
  • 56.