0% found this document useful (0 votes)
3 views

Chapter 7 - Functions

Chapter 7 of the document introduces functions in C++, explaining their components such as function name, return type, parameters, and function body. It covers how to define and call functions, including examples of void functions, functions with return values, and recursive functions. Additionally, it discusses inline functions and the concept of passing by reference, emphasizing the importance of functions for code organization and reusability.

Uploaded by

ihpaa1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 7 - Functions

Chapter 7 of the document introduces functions in C++, explaining their components such as function name, return type, parameters, and function body. It covers how to define and call functions, including examples of void functions, functions with return values, and recursive functions. Additionally, it discusses inline functions and the concept of passing by reference, emphasizing the importance of functions for code organization and reusability.

Uploaded by

ihpaa1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

BIT1C013

INTRODUCTION TO PROGRAMMING

Chapter 7
Functions
Learning Objectives
At the end of the session, student should be able to:

▪ Gain the ability to execute different code blocks selectively,


making the programs more dynamic and responsive.

▪ Execute loping constructs, like for loops and while loop and show
the efficiently handle repetitive operations in the programs.

▪ Use the control structures effectively that can implement


algorithms and logical solutions to various computational
problems.

▪ Use the control structures and looping that provide with flexible
and can adjust the flow of the programs based on changing
conditions.
Introduction
▪ In C++, a function is a named block of code that performs a
specific task. It is a reusable unit that helps in organizing code,
improving readability, and promoting code reusability.
▪ In C++, every program must have at least one function, which is
the main() function. It serves as the entry point for the program's
execution.
▪ The main() function is where the program starts its execution, and
it is the first function to be called.

int main()
{
// Statements and code to be executed
// ...
return 0; // Optional return statement
}
Introduction
Breakdown of the main() function based on the previous slide:

▪ The return type of main() is int, indicating that the function should
return an integer value.
▪ The function body contains the code that defines the program's
behavior. It consists of various statements and actions that the
program performs.
▪ The return 0; statement is optional but commonly used to indicate
a successful execution of the program.
▪ A return value of 0 conventionally signifies that the program
terminated without any errors.
▪ However, you can also return different integer values to indicate
specific error conditions or program statuses.
Introduction
▪ Functions in C++ have the following components:

Function Name
▪ It is the identifier used to call the function and distinguish it from
other functions.

Return Type
▪ It specifies the type of value that the function will return to the
caller.
▪ If the function does not return a value, the return type is declared
as void.
Introduction
Parameters
▪ They are optional and represent the input values that the function
can receive.
▪ Parameters allow the function to work with different data values
each time it is called.

Function Body
▪ It contains a set of statements enclosed within curly braces {}.
These statements define the actions to be performed when the
function is executed.
Introduction
▪ The general syntax for defining a function in C++ is as follows:

return_type function_name(parameter_list)
{
// Function body with statements
// ...
// Optional return statement (if return_type is not void)
return value;
}
Introduction
▪ Example of a function that calculates the sum of two integers:

int sum(int a, int b)


{
int result = a + b;
return result;
}
Explanation:

▪ The function is named sum.


▪ It takes two parameters of type int named a and b.
▪ The return type is int.
▪ The function body calculates the sum of a and b and stores it in the
result variable.
▪ Finally, the result is returned using the return statement.
Introduction
▪ Once a function is defined, it can be called from other parts of
the program by using its name and passing appropriate
arguments.
Example:
▪ Once a function is defined, it can be called from other parts of
the program by using its name and passing appropriate
arguments.

// Create a function
void myFunction()
{
cout << “Welcome to Functions";
}

int main()
{
myFunction(); // call the function
return 0;
}
Example:
▪ Apart from the main() function, you can define additional
functions in your C++ program to break down complex tasks into
smaller, manageable units.
▪ These functions can be called from within main() or from other
functions
#include <iostream>
using namespace std;
int sum(int a, int b)
{
return a + b;
}

int main() {
int result = sum(5, 3);
cout << "The sum is: " << result << endl;
return 0;
}
Calling Functions
▪ When calling functions in C++, you use the function's name
followed by parentheses.
▪ Inside the parentheses, you can provide arguments if the function
expects any.
▪ Here's the general syntax for calling a function:

function_name(argument1, argument2, ...);


Calling Functions
Examples to understand how to call functions in C++:

1. Calling a function with no arguments and no return value (void


function)

void greet()
{
cout << "Hello, world!" <<endl;
}

int main()
{
greet(); // Call the greet() function
return 0;
}
Calling Functions
2. Calling a function with arguments and a return value.

int sum(int a, int b)


{
return a + b;
}

int main()
{
int result = sum(5, 3); // Call the sum() function with arguments 5 and 3
cout << "The sum is: " << result << endl;
return 0;
}
Calling Functions
3. Calling a function within another function
int square(int num)
{
return num * num;
}

int main() {
int number = 5;
int squared = square(number); // Call the square() function within main()
cout << "The square of " << number << " is: " << squared << endl;
return 0;
}
#include <iostream>
Calling Functions using namespace std;

int max(int num1, int num2)


▪ Example calling
{
function by int result;
value if(num1>num2)
result=num1;
else
result=num2;
return result;
}
Output:
int main ()
{ // local variable declaration:
int a = 100;
int b = 200;
int get;
// calling a function to get max value.
get = max(a, b);
cout << "Max value is : " << get << endl;
return 0;
}
Calling Functions #include <iostream>
using namespace std;
▪ Example calling
function by void increment(int num)
{
value num++; // Modifying the parameter
cout << "Inside the function: " << num << endl;
}

int main()
Output: {
int number = 5;
Before function call: 5 cout << "Before function call: " << number << endl;
Inside the function: 6 increment(number); // Calling the increment() function
After function call: 5 cout << "After function call: " << number << endl;
return 0;
}
Calling Functions
▪ When passing by reference, changes made to the function parameters
will affect the original variables in the calling code.

▪ To pass arguments by reference, you need to declare the function


parameters using the ampersand (&) symbol.
#include <iostream>
Calling Functions using namespace std;

▪ Example calling // Function now takes the parameter by reference


function by void increment(int &num)
reference {
num++; // Modifying the parameter
cout << "Inside the function: " << num << endl;
}

int main()
{
int number = 5;
Output: cout << "Before function call: " << number << endl;
Before function call: 5 increment(number); // Calling the increment() function
Inside the function: 6 cout << "After function call: " << number << endl;
return 0;
After function call: 6 }
Inline Functions
▪ In C++, an inline function is a function that is expanded inline at the
point of its invocation instead of being called as a separate
function.
▪ It is a compiler optimization technique that can improve
performance by avoiding the overhead of function calls.

▪ To define an inline function in C++, you typically use the inline


keyword.

▪ Here's the general syntax:


inline return_type function_name(parameter_list)
{
// Function body
// ...
}
Inline Functions #include <iostream>
using namespace std;
▪ Example
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
// Main function for the program
int main()
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;

Output: return 0;
Max (20,10): 20 }
Max (0,200): 200
Max (100,1010): 1010
Inline Functions
#include <iostream>
▪ Example using namespace std;

inline int add(int a, int b)


{
return a + b;
}

int main()
Output: {
The sum is: 8 int result = add(5, 3);
cout << "The sum is: " << result << endl;
return 0;
}
Recursive Functions
▪ In C++, a recursive function is a function that calls itself during its
execution.
▪ Recursive functions provide a way to solve complex problems by
breaking them down into smaller, more manageable subproblems.
▪ Each recursive call works on a smaller portion of the problem until a
base case is reached, which defines the terminating condition for
the recursion.

▪ To implement a recursive function in C++, you need to define the


base case(s) and the recursive case(s).
▪ The base case(s) specify when the recursion should stop, while the
recursive case(s) define how the function calls itself with a smaller
problem.
#include <iostream>
Recursive Functions using namespace std;

int factorial(int n)
▪ Here's an example {
of a recursive // Base case: factorial of 0 or 1 is 1
function that if (n == 0 || n == 1)
calculates the {
return 1;
factorial of a }
number: // Recursive case: multiply n with factorial of (n-1)
return n * factorial(n - 1);
}

int main()
{
Output: int number = 5;
The factorial of 5 is: 120 int result = factorial(number);
cout << "The factorial of " << number << " is: " << result << endl;
return 0;
}
#include<iostream>
using namespace std;
Recursive Functions int main()
{
▪ Example int factorial(int);
int fact, value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
return 0;
}
int factorial(int n)
{
Output: if(n<0)
Enter any number: 5 return(-1); /*Wrong value*/
Factorial of a number is: 120 if(n==0)
return(1); /*Terminating condition*/ else
{
return(n*factorial(n-1));
}
}
Recursive Functions
n*(n-1)! = n! Find Value for 5!
n=5
5*(5-1)!=5*4!

n=4
4*(4-1)!=4*3!

n=3
3*(3-1)!=3*2!

n=2
2*(2-1)!=2*1!

n=1
1*(1-1)!=1*0!
*** The End ***

You might also like