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

Ch02 Functions

Chapter Two discusses the concept of functions in C++, including their types, declaration, definition, and usage. It emphasizes the importance of functions for modular programming, code reuse, and clarity. Key topics include user-defined functions, function arguments, return values, variable scope, and examples of function implementation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Ch02 Functions

Chapter Two discusses the concept of functions in C++, including their types, declaration, definition, and usage. It emphasizes the importance of functions for modular programming, code reuse, and clarity. Key topics include user-defined functions, function arguments, return values, variable scope, and examples of function implementation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Chapter Two - Functions in C++

Kibret Z, Mayet G., Belayneh M., Getaneh T.

Department of Computer Science


College of Informatics
University of Gondar

November 2024

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 1 / 45


Outline
1 Basic Concepts and Need of Function
2 Function Call
3 User Defined Functions
Function Declaration
Function Definition
4 Function Arguments
5 Return a Value
6 Scope of Variables
Local Scope
Global Scope
7 Functions with Default Parameters
8 Parameter Passing
Call by Value
Call by Reference
9 Recursive Functions
10 Function Overloading
Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 2 / 45
Basic Concepts and Need of Function
A programming task can be divided into smaller subtasks such as:
▶ obtaining the input data,
▶ calculating the output data, and
▶ displaying the output data.
In C++, these subparts are called functions.
Functions are building blocks of the programs.
Advantages of Function
▶ the program becomes easier to understand, test, debug, and maintain.
▶ makes the programs more modular and easy to read and manage.
▶ allows different people to work on the different subtasks.
▶ Code reuse

All C++ programs must contain the function main().


The execution of the program starts from the function main().

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 3 / 45


Basic Concepts and Need of Function

Functions in C++ come in two varieties:


1 User-defined - defined and maintained by programmer
This chapter is more about this
2 Built-in - Provided by C++ libraries.
E.g pow (), sqrt(), cin, . . .

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 4 / 45


Using Predefined Functions

C++ comes with libraries of predefined functions that you can use in
your programs.
The value the function starts out with is called its argument.
The value it computes is called the value returned.
Functions may have more than one argument, but no function has
more than one value returned.

Using predefined sqrt function


To set a variable named theRoot equal to the square root of 9.0, you can
use the following assignment statement:

theRoot = sqrt(9.0);

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 5 / 45


Using Predefined Functions - Continue..

The expression sqrt(9.0) is called a function call/invocation


An argument in a function call can be a constant, such as 9.0, or a
variable, or a more complicated expression.
A function call is an expression that can be used like any other
expression.
You can use a function call wherever it is legal to use an expression of
the type specified for the value returned by the function.

Example:
The value returned by sqrt is of type double.

bonus = sqrt(sales)/10;
//sales and bonus are variables that would normally be of type double.
cout << "The side of a square with area " << area << " is " << sqrt(area);

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 6 / 45


Predefined functions

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 7 / 45


Predefined functions
Exercise-Using Predefined Functions

1 Convert each of the following mathematical expressions to a C++


arithmetic expression:

1 x +y

−b+ b 2 −4ac
2
2a
y +3
3 x

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 8 / 45


Function Call

Function call is an expression consisting of the function name


followed by arguments enclosed in parentheses.
If there is more than one argument, the arguments are separated by
commas.

SYNTAX
Function Name(Argument List)

where the Argument List is a comma separated list of arguments:


Argument 1, Argument 2, ...
For Example:
side = sqrt(area);
cout << "2.5 to the power 3.0 is " << pow(2.5, 3.0);

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 9 / 45


User Defined Function

also commonly used as programmer defined functions.


User-defined functions in C++ are classified into two categories:
1 Value-returning functions
⋆ have a return type.
⋆ return a value of a specific data type using the return statement, which
we will explain shortly.
⋆ returns only a single value.
2 Void functions
⋆ These functions do not have a return type.
⋆ they do not use a return statement to return a value.
⋆ use void as a return type.

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 10 / 45


Function Declaration

A function declaration tells the compiler


1 return type of the function,
2 name of the function, and
3 data types of the parameters of the function.
also called function prototype and it is always terminated by
semicolon.
Three ways to declare a function:
1 Write the prototype into a file, and then use the #include directive to
include it in your program.
2 Write the prototype into the file in which your function is used.
3 Define the function before it is called by any other function.

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 11 / 45


Function Declaration

The declaration of a function is called its prototype


Is a statement - it ends with a semicolon
SYNTAX
return type function name(parameter list);

where the Parameter List is a comma-separated list of parameters:


Type 1 Formal Parameter 1, Type 2 Formal Parameter 2,. . . . . .,
Type LastFormal Parameter Last
The return type specifies the type of the data the function returns.
The parameter list could be empty.
The parameter list should contain both data type and
name of the variable.

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 12 / 45


Function Declaration

For Example:
double totalCost(int numberPar, double pricePar);

From the given example


▶ the identifiers numberPar and pricePar are called formal parameters.
A formal parameter is used as a kind of blank, or place holder, to stand in for the
argument.
A function declaration is required to appear in your code prior to a call to a function
whose definition has not yet appeared.
Function declarations are normally placed before the main part of your program
Function declarations need to occur before invocations.

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 13 / 45


Function Declaration
Argument names don’t matter.

For Example:
1 int square(int); //This is a function signature / prototype / declarati
2

3 int cube(int x) //Function definition for cube


4 {
5 return x * square(x);
6 }
7 int square(int x) //Function definition for square
8 {
9 return x * x;
10 }

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 14 / 45


Function Declaration

All functions have a return type - the default is int


If the function doesn’t have a return type void will be used
The function prototype usually placed at the beginning of the program
The definition of the prototype must be given

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 15 / 45


Function Definition

A function definition describes how the function computes the value


it returns.
Remember that a function as a small program within your program.
then the function definition is like the code for this small program.
The syntax for the definition of a function is very much like the
syntax for the main part of a program.
A function definition consists of a function header followed by a
function body.
The function header is written the same way as the function
declaration, except that the parameters must be named and the
header does not have a semicolon at the end.

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 16 / 45


Function Definition
SYNTAX
return type function name(data type 1 par 1, data type 2 par 2, . . . ) {
//Declarations;
//statements;
}

Example
//The following function computes and returns the area of
double area(double radius){
const double PI = 3.14;
return (PI * radius * radius);
}

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 17 / 45


Function Definition

The return statement without any value is typically used to exit the
function early
C++ does not allow nested functions
The definition of one function cannot be included in the body of
another function
A function definition must agree in return type and parameter list
with its prototype
The body of the function is always enclosed in braces, even when it
consists of only one statement

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 18 / 45


Function Arguments

Function arguments do not have to all be of the same type.


Arguments contain the actual value which is to be passed to the
function when it is called.
Any valid C++ expression can be a function argument, including
constants, mathematical and logical expressions, and other functions
that return a value.
Every argument position has a specified type and the argument used
in a function call should be of that type.
The sequence of the arguments in the call of the function should be
same as the sequence of the parameters in the parameter list of the
declaration of the function.
In function call, arguments replace the parameters of the function.
Argument order matters.

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 19 / 45


Return a Value

When a return statement is executed, the function call ends.


A return statement is used to exit from the function.
A return statement consists of the keyword return followed by an
expression.
SYNTAX
return expression;

Example
return (subtotal + subtotal * TAX_RATE);

When return statement is executed, the value of the expression is returned as the value of
the function call.

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 20 / 45


Return a Value

Up to one value may be returned; it must be the same type as the


return type.
If no values are returned, give the function a void return type.

For Example:
1 void printNumber(int num) {
2 cout << "number is " << num << endl;
3 }
4 int main() {
5 printNumber(4); // number is 4
6 return 0;
7 }

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 21 / 45


Return a Value
Return statements don’t necessarily need to be at the end.
Function returns as soon as a return statement is executed.
In the following example, return statement returns the function if
the condition x > y is true.

For Example:
1 void printLarger(int x, int y) {
2 if (x > y)
3 {
4 cout << "The larger number is " << x << endl;
5 return ;
6 }
7 cout << "The larger number is " << y << endl;
8 }
9
10 int main() {
11 printLarger(35, 29); // outputs: The larger number is 35
12 return 0;
13 }

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 22 / 45


Complete Program: Value Returning Functions

1 # include <iostream>
2 using namespace std;
3 double Celsius_to_Fahr(double); //Function Prototype
4 int main()
5 {
6 double temp,result;
7 cout<<"Enter the temperature"<<endl;
8 cin>>temp;
9 result= Celsius_to_Fahr(temp);
10 cout<<"The corresponding Fahrenheit is "<<result<<endl;
11 }
12 double Celsius_to_Fahr(double Celsius)
13 {
14 double temp; // Declare variable
15 temp = (9.0/5.0)*Celsius + 32; // Convert
16 return temp;
17 }

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 23 / 45


Scope of Variables

Refers to where in the program a variable is accessible.


Determines how long it is available to your program and where it can
be accessed
Two kinds
1 Local scope - variable declared within a function (or block)
2 Global scope - variable declared outside of every function definition

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 24 / 45


Local Scope

Variables declared within the body of the function are local variables
When the function returns, the underlinelocal variables are no longer
available.
Variables declared within a block are scoped to that block - Local to
that block
▶ they can be accessed only within that block
▶ ”go out of existence” when that block ends.

for(int i=1; i<=10;i++)


cout<<i<<", ";
i+=5; //Compilation error. 'i' is in accessible

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 25 / 45


Global Scope

Variables defined outside of any function have global scope


Available from any function in the program, including main()
A local variable with the same name as a global variable hides the
global variable - when used within the function

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 26 / 45


Scope of Variables - Complete Program

1 # include <iostream>
2 using namespace std;
3 void myFunction(); // prototype
4 int x = 5, y = 7; // global variables
5 int main()
6 {
7 cout << "x from main: " << x << "\n";
8 cout << "y from main: " << y << "\n\n";
9 myFunction();
10 cout << "Back from myFunction!\n\n";
11 cout << "x from main: " << x << "\n";
12 cout << "y from main: " << y << "\n";
13 return 0;
14 }
15
16 void myFunction()
17 {
18 int y = 10;
19 cout << "x from myFunction: " << x << "\n";
20 cout << "y from myFunction: " << y << "\n\n";
21 }

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 27 / 45


Scope of Variables - Complete Program

1 # include <iostream>
2 using namespace std;
3 void myFunction(); // prototype
4 int x = 5, y = 7; // global variables Output
5 int main()
6 {
7 cout << "x from main: " << x << "\n";
8 cout << "y from main: " << y << "\n\n";
9 myFunction();
10 cout << "Back from myFunction!\n\n";
11 cout << "x from main: " << x << "\n";
12 cout << "y from main: " << y << "\n";
13 return 0;
14 }
15
16 void myFunction()
17 {
18 int y = 10;
19 cout << "x from myFunction: " << x << "\n";
20 cout << "y from myFunction: " << y << "\n\n";
21 }

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 28 / 45


Unary Scope Resolution Operator ::

Using ::, you can access a global variable if it is over-shadowed by a


local variable of the same name.
Example:
1 # include <iostream>
2 using namespace std;
3 float price = 10.25;
4 int main(){
5 float price= 9.66;
6 cout<<"The value of price is:<<::price<<endl;
7 return 0;
8 }

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 29 / 45


Functions with Default Parameters

When a function is called, the number of actual and formal


parameters must be the same
C++ relaxes this condition for functions with default parameters.
we can specify the value of a default parameter when the function
name appears for the first time, such as in the prototype
If you do not specify the value of a default parameter, the default
value is used
All of the default parameters must be the rightmost parameters of the
function

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 30 / 45


Functions with Default Parameters

In a function call where the function has more than one default
parameter and a value to a default parameter is not specified, you
have to omit all of the arguments to its right
Default values can be constants, global variables, or function calls
The caller has the option of specifying a value other than the default
for any default parameter
You cannot assign a constant value as a default value to a reference
parameter

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 31 / 45


Example: Functions with Default Parameters

1 # include <iostream>
2 using namespace std;
3 int AreaCube(int length, int width = 25, int height = 1);
4
5 int main()
6 {
7 int length = 100;
8 int width = 50;
9 int height = 2;
10 int area;
11 area = AreaCube(length, width, height);
12 cout << "First area equals: " << area << "\n";
13 area = AreaCube(length, width);
14 cout << "Second time area equals: " << area << "\n";
15 area = AreaCube(length);
16 cout << "Third time area equals: " << area << "\n";
17 return 0;
18 }
19
20 int AreaCube(int length, int width, int height)
21 {
22 return (length * width * height);
23 }
Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 32 / 45
Example: Functions with Default Parameters
1 # include <iostream>
2 using namespace std;
3 int AreaCube(int length, int width = 25, int height = 1);
4
5 int main()
6 {
7 int length = 100;
8 int width = 50;
9 int height = 2;
10 int area;
11 area = AreaCube(length, width, height);
12 cout << "First area equals: " << area << "\n";
13 area = AreaCube(length, width);
14 cout << "Second time area equals: " << area << "\n";
15 area = AreaCube(length);
16 cout << "Third time area equals: " << area << "\n";
17 return 0;
18 }
19
20 int AreaCube(int length, int width, int height)
21 {
22 return (length * width * height);
23 }
Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 33 / 45
Parameter Passing

Two types of Parameter Passing:


1 Pass/Call by Value
⋆ Value of the function argument passed to the formal parameter of the
function
⋆ Copy of data passed to function
⋆ Changes to copy do not change original arguments.
2 Pass/Call by Reference
⋆ Address of the function argument passed to the formal parameter of
the function

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 34 / 45


Example: Call by Value

1 # include <iostream>
2 using namespace std;
3 void swap(int x, int y);
4
5 int main()
6 {
7 int x = 5, y = 10;
8
9 cout << "Main. Before swap, x: " << x << " y: " <<y<< "\n";
10 swap(x,y);
11 cout << "Main. After swap, x: " << x << " y: " <<y << "\n";
12 return 0;
13 }
14
15 void swap (int x, int y)
16 {
17 cout << "Swap. Before swap, x: " << x << " y: " <<y<< "\n";
18 int temp = x;
19 x = y;
20 y = temp;
21 cout << "Swap. After swap, x: " << x << " y: " << y << "\n";
22 }

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 35 / 45


Example: Call by Value

# include <iostream>
using namespace std;
void swap(int x, int y);

int main()
{
int x = 5, y = 10;

cout << "Main. Before swap, x: " << x << " y: " <<y<< "\n";
swap(x,y);
cout << "Main. After swap, x: " << x << " y: " <<y << "\n";
return 0;
}

void swap (int x, int y)


{
cout << "Swap. Before swap, x: " << x << " y: " <<y<< "\n";
int temp = x;
x = y;
y = temp;
cout << "Swap. After swap, x: " << x << " y: " << y << "\n";
}
Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 36 / 45
Call by Reference

If a formal parameter is a reference parameter, then reference


parameter stores the address of the corresponding actual parameter
During program execution to manipulate the data
▶ The address stored in the reference parameter directs it to the memory
space of the corresponding actual parameter
Reference parameters are useful in three situations:
1 Returning more than one value from the function.
2 Change the value of the actual parameter.
3 When passing the address would save memory space and time.

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 37 / 45


Example: Call by Reference

1 # include <iostream>
2 using namespace std;
3 void swap(int &x, int &y);
4
5 int main()
6 {
7 int x = 250, y = 750;
8
9 cout << "Main. Before swap, x: " << x << " y: " <<y<< "\n";
10 swap(x,y);
11 cout << "Main. After swap, x: " << x << " y: " <<y << "\n";
12 return 0;
13 }
14
15 void swap (int &i, int &j)
16 {
17 cout << "Swap. Before swap, i: " << i << " j: " <<j<< "\n";
18 int temp = i;
19 i = j;
20 j = temp;
21 cout << "Swap. After swap, i: " << i << " j: " << j << "\n";
22 }

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 38 / 45


Example: Call by Reference
# include <iostream>
using namespace std;
void swap(int &x, int &y);

int main()
{
int x = 250, y = 750;
cout << "Main. Before swap, x: " << x << " y: " <<y<< "\n";
swap(x,y);
cout << "Main. After swap, x: " << x << " y: " <<y << "\n";
return 0;
}

void swap (int &i, int &j)


{
cout << "Swap. Before swap, i: " << i << " j: " <<j<< "\n";
int temp = i;
i = j;
j = temp;
cout << "Swap. After swap, i: " << i << " j: " << j << "\n";
}

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 39 / 45


Recursive Functions

In C++, a function definition may contain a call to the function


being defined. In such cases, the function is said to be recursive.
A recursive function is a function that call itself.
To avoid infinite recursion, one must have a terminating condition in
the function.
▶ One or more cases without any recursive calls are called base cases or
stopping cases

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 40 / 45


Example: Finding Factorial Recursively

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 41 / 45


Example: Finding Factorial Iteratively

1 # include <iostream>
2 using namespace std;
3 unsigned long factorial(unsigned long); //prototype
4 int main()
5 {
6 int num;
7 cout<<"Enter a positive integer:";
8 cin>>num;
9 cout<<"Factorial of "<<num<<" is "<<factorial(num);
10 return 0;
11 }
12
13 //Function definition for factorial
14 unsigned long factorial(unsigned long n)
15 {
16 unsigned long fact = 1;
17 For( int i = 1; i <= n; i++)
18 fact*=i;
19 }

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 42 / 45


Example: Finding Factorial Recursively

1 # include <iostream>
2 using namespace std;
3 unsigned long factorial(unsigned long); //prototype
4 int main()
5 {
6 int num;
7 cout<<"Enter a positive integer:";
8 cin>>num;
9 cout<<"Factorial of "<<num<<" is "<<factorial(num);
10 return 0;
11 }
12
13 //Function definition for factorial
14 unsigned long factorial(unsigned long n)
15 {
16 if ( n <= 1) //the base case
17 return 1;
18 else
19 return n * factorial (n - 1);
20
21 }

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 43 / 45


Function Overloading
Two or more function definitions for the same function name, that is
called overloading.
When you overload a function name,
▶ function definitions must have different numbers of formal parameters
or
▶ some formal parameters of different types.
the
When there is a function call, the compiler uses the function
definition whose number of formal parameters and types of formal
parameters match the arguments in the function call.
used for functions that performs similar tasks
Example: function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 44 / 45


Example: Overloading Function Name

1 # include <iostream>
2 using namespace std;
3 double average(double, double); //prototype
4 //Returns the average of the two numbers
5
6 double average(double, double, double); //prototype
7 //Returns the average of the three numbers
8 int main()
9 {
10 cout<<"The average of 2.0, 2.5, and 3.0 is "<< ave(2.0, 2.5, 3.0) <<endl;
11
12 cout<<"The average of 4.5 and 5.5 is "<< ave(4.5, 5.5) <<endl;
13 return 0;
14 }
15 double average(double x, double y)
16 {
17 return (x + y) / 2.0;
18 }
19 double average(double a, double b, double c)
20 {
21 return (a + b + c) / 3.0;
22 }

Kibret Z, Mayet G., Belayneh M. Chapter 01 - Functions in C++ November 2024 45 / 45

You might also like