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

Chapter one Function

Uploaded by

abuy3832
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Chapter one Function

Uploaded by

abuy3832
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Function

 A function is a block of code that performs a specific task

• only runs when it is called

Why function is needed?

 To improve the readability of code

 Decrease the complexity of a program

 Simplifies testing and debugging

 Reduction in the size of the program due to code reusability

 Functions can be accessed repeatedly without redevelopment, which in turn promotes


reuse of code
Cont…

 Every C++ program has at least one function, main(), where program
execution begins

 Functions in C++ come in two varieties:


• User-defined function: created by the user/programmer
• Built-in function: pre-written functions
 pow(x,y), sqrt(x), abs(x), ceil(x), floor(x)
Functions Declaration
 Functions must be declared before use
• Any names apart from keywords must be declared, i.e. introduced to the compiler,
before they are used

 The declaration tells the compiler the name, return type, and parameters of
the function

 The declaration of a function is called its prototype


• It is a statement - it ends with a semicolon
 The statement just above the main is the function declaration
4
Cont…

 Many of the built-in functions have their function prototypes already written in
the header files you include in your program by using #include

 Syntax:
return_type function_name(parameter_type1 parameter_name1,
parameter_type2 parameter_name2, ...);

 Parameter names are optional in the prototype (only types are required)

E.g. double calculateArea(double length, double width);` Or

double calculateArea(int, int);


5
Defining a Function

 The function prototype and the function definition must agree exactly about the

return type, the name, and the parameter list

 Function definition consists of a function header and a function body

 The header is exactly like the function prototype, except that the parameters

must be named, and there is no terminating semicolon

 The body of the function is a set of statements enclosed in braces


Cont…
 The general form of a C++ function definition is as follows:

return_type function_name (parameter_type1 parameter_name1, parameter_type2


parameter_name2, ...)

body of the function

 If function definition is done before the main function, then there is no need to put the
prototype

 Return Type: the data type of the value the function returns

• If the function doesn’t returns , the return_type keyword is void


Cont…

 Both void functions and functions that return a value can have return statements

 In the case of a function that returns a value, the return statement specifies the
value returned

 In the case of a void function, the return statement simply ends the function
execution and exit it immediately

 Every function that returns a value must end by executing a return statement

 A void function does not require a return statement


• It will end after executing the code in the function body
Cont…
 Function Name: This is the actual name of the function

• The function name and the parameter list together constitute the function signature

 Parameters: A parameter is like a placeholder

• When a function is invoked, a value is passed to the parameter

 The parameter list refers to the type, order, and number of the parameters of a function

• Parameters are optional; that is, a function may contain no parameters

 Function Body: The function body contains a collection of statements that define what the

function does
Cont…
 The following function named calculateMax() takes two parameters num1 and num2 and
returns the maximum
int calculateMax (int num1, int num2) int calculateMax (int num1, int num2)
{ {
int result; or int result=max(num1,num2);//built-in
if (num1 > num2)
return result;
result = num1;
else }
result = num2;
return result;
}
 C++ does not allow nested functions
• The definition of one function cannot be included in the body of another function
Function Call
 For a function to perform the specified task and return output, it must be
called/invoked

 Calling a function means making the instruction of the function to be executed

 To call a function, pass the required parameters along with function name, and if
function returns a value, then you can store returned value
• If the function takes no parameters, don’t pass any value during the call

 To call the previous calculateMax() function:


double area=calculateMax(3,7);
or
cout<<”Max=“<<calculateMax (3,7);
Execution of Functions
 Each function has its own name

 When a program calls a function, program control is transferred to the


called function

 When the function returns, execution resumes on the next line of the
calling function

 Functions can also call other functions and can even call themselves
Cont…
#include <iostream>
using namespace std;
double calculateArea (double l, double w); // function declaration
int main ()
{
double length= 5; //local variable declaration
double width= 10;
double result= calculateArea (length, width); // calling a function
cout << "Area of a rectangle is : " <<result<< endl; //50
}
double calculateArea (double l, double w) //function header
{
return l*w;
}
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 kind:
• Local variable - variables declared within a function (or block)
• Global variable – variables declared outside of every function definition

14
Local Variables

 Local variables can be used only by statements that are inside that function
or block of code

 The lifetime of the local variable is within the function

 When the function returns, the local 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

15
Global Variable
 Global variables are defined outside of all the functions, usually on top of the
program.

 A global variable can be accessed by any function

 Variables defined outside of any function have global scope

 The lifetime is within the program

 A local variable with the same name as a global variable hides the global
variable - when used within the function
• Scope resolution operator (::) can be used to access hidden global variable
16
Cont…
#include <iostream>
using namespace std;
int number=10; // Global variable
int main ()
{
int number=20; // Local variable
cout << number; //20
cout << ::number; //10
return 0;
}

17
Functions with default parameters
 In C++, it is possible to define default values for all or some parameters of a function

 When defining a function with default parameters, you assign default values in the
function declaration

 Syntax:

return_type function_name(parameter_type parameter_name = default_value);

 When the function is called without passing arguments, then the default parameters
are used
• However, if arguments are passed while calling the function, the default values are
ignored
18
Cont…
#include<iostream>
using namespace std;

int sum(int num1=5,int num2=10, int num3=15)


{
return (num1+num2+num3);
}

int main()
{
cout << sum() << endl; //30
cout << sum(20) << endl; //45
cout << sum(20,30) << endl; //65
cout << sum(20,30,40) << endl; //90
return 0;
} 18
Cont…
 Order of Parameters: any parameter that has a default value must be
declared after any parameters that do not have default values

 Once we provide a default value for a parameter, all subsequent parameters


must also have default values. For example,
int sum(int num1=5,int num2=10, int num3);// Invalid
int sum(int num1=5,int num2, int num3=15); // Invalid
int sum(int num1,int num2=10, int num3=15); // Valid
 If we are defining the default parameters in the function definition instead of
the function prototype, then the function must be defined before the function
call
19
Passing Arguments
 In C++, functions can pass arguments to parameters using two
primary methods: call by value and call by reference

 Actual Parameters (aka. Arguments): these are the values or


expressions passed to the function when it is called

 Formal Parameters (aka. Parameters): these are the variables defined


in the function's signature (or declaration)
• act as placeholders for the values that will be passed into the function
• are local to the function definition
21
Call by Value

 In call by value, a copy of the argument’s value is passed to the function

• any modifications made to the parameter inside the function do not affect

the original argument in the calling code

 The function cannot access the original variable in the calling


program, only the copy it created

 Passing arguments by value is useful when the function does not


need to modify the original variable in the calling program
22
Call by Reference
 In call by reference, the function receives a reference to the original variable

• Any changes made to the parameter inside the function are applied to the original
argument as well

 Call by reference is implemented using the ampersand (&) symbol

• placed before a parameter in the function declaration/definition

 The called function can access the actual variables in the calling program

 If a formal parameter is a reference parameter


• It receives the address of the corresponding actual parameter

• A reference parameter stores the address of the corresponding actual parameter


23
#include <iostream>
using namespace std;
void SwapByReference(int &num1,int &num2);
void SwapByValue(int num1,int num2);
int main() {
int x=5,y=7;
SwapByValue(x,y);
cout<<"X is "<<x<<" , "<<"Y is "<<y<<endl; Output:
SwapByReference(x, y);
cout<<"X is "<<x<<" , "<<"Y is "<<y<<endl;
}
void SwapByValue(int num1,int num2){
int temp;
temp=num1;
num1=num2;
num2=temp;
}
void SwapByReference(int &num1,int &num2){
int temp;
temp=num1;
num1=num2;
num2=temp;
} 24
Function Recursion
 A function which calls itself is said to be recursive

 A recursive function must have at least one termination condition which can be
satisfied
• Otherwise, the function will call itself indefinitely until the runtime stack overflows

 The three necessary components in a recursive method are:


• A test to stop or continue the recursion
• An end case that terminates the recursion
• A recursive call(s) that continues the recursion

25
Factorial using function recursion:
#include <iostream>
using namespace std;
int factorial(int n) {
if (n <= 1)
return 1; Output:
else
return n * factorial(n - 1);
}
int main() {
int number;
cout << "Enter a positive integer:";
cin >> number;
if (number < 0) {
cout << "Invalid input " << endl;
} else {
cout << "Factorial of " << number << " is: " << factorial(number) << endl;
}
26
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy