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

C++ Ch4 (1)

Chapter Four discusses functions in C++, including predefined and user-defined functions, their declarations, definitions, and how to call them. It covers important concepts such as parameter passing methods (call by value and call by reference), variable scope, default parameter values, and recursive functions. Additionally, it introduces function overloading and provides examples to illustrate these concepts.

Uploaded by

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

C++ Ch4 (1)

Chapter Four discusses functions in C++, including predefined and user-defined functions, their declarations, definitions, and how to call them. It covers important concepts such as parameter passing methods (call by value and call by reference), variable scope, default parameter values, and recursive functions. Additionally, it introduces function overloading and provides examples to illustrate these concepts.

Uploaded by

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

Chapter Four

Function
eh E .
el ayn
By B
Learning Objectives
• Pre-defined functions
• User-defined functions
– Defining, declaring and calling
– Default parameters
– recursive functions
– Scope of variables
Introduction
 A function is a group of statement that is executed when it is called
 Functions are building blocks of the programs.
 Named differently in other languages. Ex: procedures,
subprograms, methods
 They make the programs more modular and easy to read and
manage. All C++ programs must contain the function main( ).
 The execution of the program starts from the function main( ) and
ends in main() function
Reasons for Function
 To make the program development more manageable
 To remove repetition of codes
 For software reusability purpose
 For maintainability
 For readability
C++ Functions
• C++ Libraries are full of functions for our use
• Two types of functions:
• That return a value (int, float, char,…)
• That do not return a value (void)
• In algebra, a function is defined as a rule or correspondence
between values, called the function’s arguments, and the unique
value of the function associated with the arguments
• Example: f(x) = 2x+5, f(1) = 7, f(2) = 9, and f(3) = 11
– 1, 2, and 3 are arguments
– 7, 9, and 11 are the corresponding values
Predefined/Standard Functions
• Predefined functions
Make sure to use the required
– Part of the C++ language
– Provided in function libraries #include file

• Examples:
abs(x), sin(x), log(x), pow( x, n)
• These functions will return a value
– To be printed cout << sin (x);
– To be assigned y = pow (3, 4.5);
– To be used in an expression 3.14 * sqr(r)
Predefined/Standard Functions
Predefined/Standard Functions
User-defined Functions
• Although C++ is shipped with a lot of standard functions, these functions are
not enough for all users
• Therefore , C++ provides its users with a way to define their own functions
(or user-defined function)
• User-defined functions in C++ are classified into two categories:

• Value-returning functions

– Functions that have a return type.

– Functions return a value of a specific data type using the return statement,
which we will explain shortly.
• Void functions

– Functions that do not have a return type.

– These functions do not use a return statement to return a value.


User- defined Functions
• Three pieces to define your own functions:
1. Function declaration (prototype)
 Information for compiler
 To properly interpret calls
2. Function definition
 Actual implementation of C++ code
 For what function does
 Job descriptions
3. Calling a Function
– Transfer control to the function
Function Declaration (Prototype)

Syntax:
<return_type>FunctionName(<parameter-list>);
• The prototype above yields the following information to the
compiler:
– func is the function name
– The function is called with two arguments: the first
argument is of type int, the second of type double
– The return value of the function is of type long
Function Declaration (Prototype)
• A function declaration is simply the function's header, followed by a
semicolon
• A function declaration is like a variable declaration;
• its purpose is simply to provide the compiler with all the information
it needs to compile the rest of the file
• The compiler does not need to know how the function works (its
body).
• It only needs to know the function's name, the number and types of
its parameters, and its return type
• This is precisely the information contained in the function's header.
Function Definition
 A function that includes the body of the function
 A function definition is the complete function: header and body
• Parameter list
– Comma separated list of arguments
– Data type needed for each argument

• The argument names in the function


header are referred to as formal
Syntax parameters/arguments
return-value-type function-name( parameter-list )
{ int FindMax(int x, int y)
declarations and statements {
int maximum;
}
if(x>=y)
maximum = x;
else
maximum = y;
return maximum;
}
Calling a Function
• A function is called by specifying its name followed by its
arguments
• Before a function is called in your program, the compiler must
previously process either the function’s prototype, or the
function’s definition (heading and body)
• The argument list is a way for functions to communicate with
each other by passing information
• The argument list can contain 1 or more arguments, separated by
commas, depending on the function

Syntax: FunctionName ( Argument List );


Example
#include<iostream>
using namespace std;
void show();
int main() {
show();
show();
return 0; }
void show() {
cout<<"Hello world\n";
}
Example
#include <iostream>
using namespace std;
float p=3.14;
float area(float);
int main() {
int r;
cin>>r;
area(r);
return 0; }
float area(float x) {
float A= p*x*x;
cout<<A<<endl;
}
Example
#include <iostream>
using namespace std;
int Max(int, int);
int main() {
int a, b;
cin>>a>>b;
int Z=Max(a,b);
cout << Z<< endl;
return 0; }
int Max(int x, int y) {
int result;
if(x>y)
result=x;
else
result=y;
return (result);
}
Example
#include <iostream>
using namespace std;
int sum(int, int);
int main()
{
int a,b;
cout<<"enter the value"<<endl;
cin>>a>>b;
sum(a, b);
return 0;
}
int sum(int x, int y)
{
int add =x+y;
cout<<add;
}
• A C++ program to add two
integers. Make a function
add() to add integers and
display sum in main()
function.
• A C++ program to get a
maximum value of two
numbers using function.
20
Parameters
• Function Definition Syntax:
FunctionType functionName (formal parameter list)
{
statements Parameters in the
declaration : formal
}
parameters

• Call (Invocation of the Function)


cout << "Enter radius for circle area -> ";
cin >> radius;
area = circleArea (radius);
Parameters in the
call: actual
parameters
Syntax: Formal Parameter List

Syntax: Function Call

Syntax: Actual Parameter List


The return Statement
• A value returning statement must have a return statement
– Else a warning from the compiler
– Also the function will actually return a "garbage" value
• Syntax:
return expression;
• Expression is a variable, constant value, or expression
The return Statement

Here return statement value is a variable called max


Exercises
• Consider the following function definition:
double func(double x, int y, string name)
{
//function body
}
• Which of the following is the correct function prototype of the
function func?
I. double func();
II. double func(double, int, string);
III. double func(double x, int y, string name)
IV. func(double x, int y, string name);
Function Arguments
• If a function is to use arguments, it must declare variables that
accept the values of the arguments
• These variables are called the formal parameters of the
function
• The formal parameters behave like other local variables inside
the function and are created upon entry into the function and
destroyed upon exit
• While calling a function, there are two ways that arguments can
be passed to a function:
Call by Value
• The call by value method of passing arguments to a function
copies the actual value of an argument into the formal
parameter of the function
• In this case, changes made to the parameter inside the function
have no effect on the argument
• By default, C++ uses call by value to pass arguments
• In general, this means that code within a function cannot alter
the arguments used to call the function
Call by Value
• Allocate a temporary memory location for each formal
parameter (when a function is called)
• Copy the value of the corresponding actual parameter in to that
location
• Called function has no access to the actual parameter, just to a
copy of its value
Call by Value
#include <iostream>
using namespace std;
int Pass(int);
int main()
{
int x=100;
cout<<x<<endl;
Pass(x);
cout<<x<<endl;
return 0;
}
int Pass(int y)
{
int x=10;
cout<<x<<endl;
}
Call by Reference
• A method of passing arguments to a function copies the
reference of an argument into the formal parameter
• Inside the function, the reference is used to access the actual
argument used in the call
• This means that changes made to the parameter affect the passed
argument
• To pass the value by reference, argument reference is passed to
the functions just like any other value
• In a call by reference, the user allows the value of the calling
variable to be modified by the called function
• C++ simulates a call be reference by passing an address operator
which points to the address of the calling argument
Call by Reference
#include <iostream>
using namespace std;
int Pass(int &);
int main()
{
int x=100;
cout<<x<<endl;
Pass(x);
cout<<x<<endl;
return 0;
}
int Pass(int &y)
{
y=10;
cout<<y<<endl;
}
Difference between call by value and call by reference

Call by value Call by reference

• This method copy address of


• This method copy original value
arguments into function as a
into function as a arguments.
arguments.

• Changes made to the parameter • Changes made to the parameter affect


inside the function have no effect the argument. Because address is used
on the argument. to access the actual argument.

• Actual and formal arguments will


• Actual and formal arguments will be
be created in different memory
created in same memory location
location
Scope of Variables
• Scope: A section of program where identifier is valid (known or
visible): Local and Global variables
• Local Variables
– A function that we can pass and declare variables within the
body of the function
– They exist only locally within the function itself
– When the function returns, the local variables are no longer
available
– Variables declared within the function are said to have "local
scope
Scope of Variables
• Global Variables
– Variables defined outside of any function have global scope
– Available from any function in the program, including main()
• Local variables with the same name as global variables do not
change the global variables
• A local variable with the same name as a global variable hides
the global variable
Default values for parameters
• When you define a function, you can specify a default values for
each the last parameters.
• This value will be used if the corresponding argument is left
blank when calling the function.
• This is done by using the assignment operators and assigning
values for the arguments in the function definition.
• If values for that parameter is not passed when the function is
called the default given values is used.
• But if a value is specified this default value is ignored and the
passed value is used instead.
Default values for parameters
#include <iostream>
using namespace std; #include <iostream>
int sum(int a, int b=20) { using namespace std;
int result= a+b; int sum(int a, int b=50, int c=60);
return (result); } int main() {
int x=10,y=20,z=30;
int main() {
sum(x,y,z);
int a=100,b=200, result; sum(x,y);
result = sum(a, b); sum(x);
cout<< result<<endl;; return 0; }
result= sum(a); int sum(int a, int b, int c) {
cout<< result<<endl; int result= a+b+c;
cout<<result<<endl; }
return 0;
}
Recursive functions
• Is simply a function that calls itself somewhere in the function
body and that terminates when a base case is met.
• A recursive function has two parts.
 Base case – stopping condition
 Recursive step- (like ++ & - -)an expression of the completion or definition
in terms of itself
#include <iostream>
#include <iostream> using namespace std;
using namespace std; int num( int);
int num( int); int main() {
int main() {
int n;
int n;
cout<<"enter the value"<<endl; cout<<"enter the value"<<endl;
cin>>n; cin>>n;
num(n); num(n);
return 0; } return 0; }
int num(int x) { int num(int x) {
if(x>=1) if(x<=10)
cout<<x<<endl; cout<<x<<endl;
num(x-1); }
num(x+1); }
Recursive functions
#include <iostream> unsigned long factorial(unsigned long
n)
using namespace std; {
int factorial(int); if ( n <= 1) //the base case
int main() { return 1;
else
int num;
return n * factorial (n - 1);
cin>>num; }
int x=factorial(num);
cout<<x<<endl; int Fibonacci(int n)
return 0; } {
int factorial(int n) { if (n == 0 || n == 1)
{return 1;}
if(n<=1) else {
return 1; return fibonacci(n-2) + fibonacci(n-1);
else }
}
return (n*factorial(n-1)); }
Function overloading
• Functions with the same name and different parameters.
• Should perform similar tasks i.e. function to square int and
function to square floats.
• A call time c++ compiler selects the proper function by
examining the number, type, and order of the parameters.

#include <iostream>
using namespace std;
int add( int, int);
int square(int x)
int add( int, int, int);
int main() { {
int a, b,c; return (x*x);
cin>>a>>b>>c; }
add(a,b,c);
add(a,b); float square (float x)
return 0; } {
int add( int x, int y) { return (x*x);
int result= x+y;
}
cout<<result<<endl; }
int add( int x, int y, int z) {
int sum= x+y+z;
cout<<sum<<endl; }

You might also like