0% found this document useful (0 votes)
8 views54 pages

Programming CPP Chapter Four 4

Uploaded by

hayuasamad2
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)
8 views54 pages

Programming CPP Chapter Four 4

Uploaded by

hayuasamad2
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

1

Chapter Four: Functions


(Modular Programming )
COMPUTER PROGRAMMING
Modularity 2

 Modular programming
 Breakingdown the design of a program into individual components (modules) that
can be programmed and tested independently.
 Usingfunctions, a program is divided into smaller parts, making it easier to understand,
control, test, and maintain.
A program divided into several smaller parts which can interact or work together
 Modules
 Can be written and tested separately
 Testing is easier (smaller)
 Doesn't need to be retested
 Reduces length of program
 Hides details (data abstraction)
Functions in C++ 3

A function is a code module that performs a single task.


 A function is an independent block of code that has a name. When it
is called its code is executed and when it terminates it may return a
value.
 Function is essentially a small program with its own variables and
statements. So far, we’ve written only one function, the main(). In this
chapter, you’ll learn how to write and use your own functions within
your programs.
 A C++ program might contain more than one function.
1. user-defined
2. built-in E.g pow(), sqrt(), getch(), etc
Why Do We Need Functions? 4

 Functions
help us in reducing code redundancy. If functionality is
performed at multiple places in software, then rather than writing the
same code, again and again, we create a function and call it
everywhere.
 Functions make code modular. Consider a big file having many lines of
code. It becomes really simple to read and use the code if the code is
divided into functions.
 Functions
provide abstraction. For example, we can use library functions
without worrying about their internal work.
User Defined Functions 5

 As the name suggests these functions are defined and created by users / programmers.
 A function is a set of statements that take inputs, do some specific computation, and
produce output.
 Functions in C++ agree with the notion of functions in mathematics.
 For example, they allow functional composition such as f(f(p),q,f(f)). However, C++ functions either return
one value or no value.

1. Declaration
2. Definition
3. Calling
Declaration of Functions 6

A function declaration tells the compiler about the number of


parameters function takes data-types of parameters, and returns the
type of function.
 The general form of a function declaration is:
return_type function_name(parameter_list);
 Three ways
1. Write your 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.
Declaration of Functions 7

 The return_type specifies the type of value that the function returns.
 The function_name is the name of the function.
 The parameter_list is a list of variables that are passed to the function.

 The body of the function is a block of code that is executed when the function is called.
The body of the function can contain any valid C++ code.
Declaration of Functions - Prototypes 8

Isa statement - it ends with a semicolon


E.g. long int Area(int, int); long int Area(int length, int width);
A function may return one value at most. The return_type
specifies the type of the returned value. A function may return
any data type, such as char, double, struct, … or a pointer to
some type.
Declaration of Functions – Return 9

Value
 The return statement is used to terminate immediately the execution of a
function.
 All functions have a return type – default is int
 If the function doesn’t have a return type void will be used
void is a reserved word
 The function prototype usually placed at the beginning of the program
 The definition of the prototype must be given
 Many of the built-in functions have their function prototypes already
written in the header files you include in your program by using #include
Declaration of Functions 10

Function Parameters
 A function may take a list of parameters, separated by commas. Each parameter is
preceded by its type.

 If the function has no parameters we use empty parentheses ().

 Note that we can omit the names of the parameters, the type is enough. For example,
we could write:
 double show(char, int, float);
Function Parameters 11

 However, it is better to use names, so that someone who just reads the
prototype or intends to use the function gets an idea about the
information being passed to it, in what order and the purpose of each
parameter.
void show(int x, int y); instead of void show(int, int);
 Thetype of each parameter must be specified, even if several
parameters have the same type. For example, it is illegal to write:
void test(int a, b, c); instead of void test(int a, int b, int c);
Parameters 12

 Function parameters are placeholders for values passed to the function. They act as
variables inside a function.
 Here, x is a parameter that holds a value of 10 when it’s called.
Example 13
Defining a Function 14

 Thedefinition tells the compiler how the function works.


The function header :
 Like the function prototype except that the parameters must be named
 There is no terminating semicolon
Its body is the task of the function

return_type function_name(parameter declarations)


{
function owned variable declarations;
statements;
}
Defining a Function 15

As it will be explained later, the


program outputs In.
Defining a Function 16

 E.g.
long Area(long l, long w)
{
return l * w;
}
 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
Defining a Function 17

Ifthe function returns a value, it’s definition should end with a


return statement
The body of the function is always enclosed in braces, even
when it consists of only one statement
 return keyword
 Returns data, and control goes to function’s caller
 If no data to return, use return;
 Function ends when reaches right brace
 Control goes to caller
// Creating and using a programmer-defined function.
#include <iostream.h>
Function prototype: specifies data types
int square( int ); // function prototype of arguments and return values. 18
square expects an int, and returns
int main() an int.
{
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call

cout << endl;


Parentheses () cause function to be called.
When done, it returns the result.
return 0; // indicates successful termination

} // end main

// square function definition returns square of an integer


int square( int y ) // y is a copy of argument to function
{
return y * y; // returns square of y as an int
Definition of square. y is a
copy of the argument passed.
} // end function square Returns y * y, or y squared.

1 4 9 16 25 36 49 64 81 100
Example 19

#include <iostream.h>
double Celsius_to_Fahr(double); //Function Prototype
int main()
{
double temp,result;
cout<<“enter the temperature”<<endl;
cin>>temp;
result= Celsius_to_Fahr(temp);
cout<<“the corresponding Fahrenheit is”<<result<<endl;

double Celsius_to_Fahr(double Celsius)


{
double temp; // Declare variables
temp = (9.0/5.0)*Celsius + 32; // Convert
return temp;
}
Calling Function - Execution of 20

Function
 Each function has its own name
 When that name is encountered, called function call, the execution of
the program branches to the body of that function – 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 –
recursive functions
A function can be called as many times as needed.
 When a function is called, the execution of the program continues with the execution of the
function’s code.
 In particular, the compiler allocates memory to store the function’s parameters and the
variables that are declared within its body.
Exercises 21

 Write two functions that take an integer parameter and return the square and the cube
of this number, respectively.
 The restriction is that the body of the second function consists of a single statement and calls the first.
 Write a program that reads an integer and uses the functions to display the sum of the
number’s square and cube.
Scope of identifier 22

 The scope of a variable in C++ is the part of the program where the variable can be
accessed.
 The scope of a variable is the part of the program in which the variable is accessible, or
else, it is visible from the other parts of the program.
 Refers to where in the program an identifier is accessible
 Determines how long it is available to your program and where it can be accessed
 Two kind
 Local identifier - identifiers declared within a function (or block)
 Global identifier – identifiers declared outside of every function definition
Scope of identifier 23

// Global variable The variable global_var can be


accessed from anywhere in the
int global_var = 10;
program.

// Function variable
void foo() { The variable function_var can only be
int function_var = 20; accessed from within the function foo().
}

// Block variable
The variable block_var can only be
{ accessed from within the block of code
int block_var = 30; where it is declared.
}
Examples 24

#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
// Global variable declaration:
int main () {
int g;
// Local variable declaration:
int main () {
int a, b;
// Local variable declaration:
int c;
int a, b;
// actual initialization
// actual initialization
a = 10;
a = 10;
b = 20;
b = 20;
c = a + b;
g = a + b;
cout << c;
cout << g;
return 0;
return 0;
}
}
The same name for global and 25

local variables
A program can have same name for local and global variables but value of local variable
inside a function will take preference.
#include <iostream>
using namespace std;
// Global variable declaration: When the above code is compiled and executed, it
int g = 20; produces the following result −

int main () { 10
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
Local scope 26

 You can declare variables within the body of the function


 local variables
 When the function returns, the local variables are no longer available
 Local variables are declared inside a block or function and have local scope, meaning
they can only be accessed within that block or function.
 Variables declared within a block are scoped to that block – Local to that block – or to
a function only
 they can be accessed only within that block and "go out of existence" when that block ends
 E.g.
for(int i = 0;i<5; i++)
cout<<i;
i=+10; // compilation error i is inaccessible
Example 27
Declare Variables within Block 28
Global Scope 29

 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
A variable that is declared outside of any function and types with block
scope, such as enumeration, class, or namespace, is called global.
30
#include <iostream.h>
void myFunction(); // prototype
31
int x = 5, y = 7;
int main()
{
cout << "x from main: " << x << "\n"; Output:
cout << "y from main: " << y << "\n\n";
x from main: 5
myFunction();
y from main: 7
cout << "Back from myFunction!\n\n";
x from myFunction: 5
cout << "x from main: " << x << "\n";
y from myFunction: 10
cout << "y from main: " << y << "\n";
return 0;
Back from myFunction!
}
x from main: 5
void myFunction()
{ y from main: 7
int y = 10;
cout << "x from myFunction: " << x << "\n";
cout << "y from myFunction: " << y << "\n\n";
}
Unary Scope Resolution Operator 32

::
One can access an global variable even if it is over-shadowed by a local
variable of the same name.
Using :: operator
#include <iostream.h>
float num=10.8;
int main(){
float num= 9.66;
cout<<“the value of num is:”<<::num<<endl;
return 0;
}
Static and Automatic Variables 33

(continued)
 Static variable - memory remains allocated as long as the program
executes
 The syntax for declaring a static variable is:
static dataType identifier;
static int x; // Declares x to be a static variable of the type int
 Static variables declared within a block are local to the block
 Their scope is the same as any other local identifier of that block
 A static variable in C++ is a variable that is declared using the keyword static. The space
for the static variable is allocated only once and this is used for the entirety of the
program. Once this variable is declared, it exists till the program executes. So, the
lifetime of a static variable is the lifetime of the program.
#include <iostream> float getavg(float newdata)
34
{
float getavg(float);
static float total = 0;
int main() static int count = 0;
{ count++;
total += newdata;
float data=1, avg; return total / count;
while( data != 0 ) }
{
cout << “Enter a number: “;
Variables declared outside of any block are static
cin >> data; variables
avg = getavg(data); By default, variables declared within a block are
cout << “New average is “ << avg << endl; automatic variables
} Declare a static variable within a block by using the
return 0; reserved word static
}
Functions Parameters 35

 The parameters that are defined in the function definition are called Formal Parameters.

 The parameters in the function call which are the actual values are called Actual
Parameters.

 We have already seen the concept of actual and formal parameters.

 We also know that actual parameters pass values to a function which is received by the
format parameters.

 This is called the passing of parameters.


Functions with Default Parameters 36

 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
 You
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 for a parameter : The default value is used
 All of the default parameters must be the rightmost parameters of the function
 Ina function call where the function has more than one default
parameter and a value to a default parameter is not specified
 You must omit all of the arguments to its right
Functions with Default Parameters 37

 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
 In C++, default arguments can be added to function declarations so that it is possible to
call the function without including those arguments.

 If those arguments are included the default value is overwritten. Function parameters
are read from left to right, so default parameters should be placed from right to left.
Functions with Default Parameters 38

 InC++, default parameters for functions can be specified by using the


equals sign ("=") after the parameter declaration in the function
declaration or definition.
 DO remember that function parameters act as local variables within the function.
 DON'T try to create a default value for a first parameter if there is no default value for
the second.
 DON'T forget that changes to a global variable in one function change that variable
for all functions.
 If default parameter is with in function definition if and only if the definition is before
the caller function.
Example 39

In the example above, param1 is a required


parameter, but param2 has a default value of 0.
void myFunction(int param1, int
This means that the function can be called with just
param2 = 0) { one argument (myFunction(5)), and param2 will be
// Function body goes here automatically set to 0.
} Alternatively, it can be called with two arguments
(myFunction(5, 10)), and param2 will take on the
value of the second argument passed in.

it's generally a good practice to avoid using too many default parameters,
as functions with too many optional parameters can become difficult to use
and maintain.
Parameter Passing 40

 In C++, there are two ways to pass arguments to a function: pass by value and pass by
reference.
1. Pass by value means that a copy of the argument is passed to the function. Any changes made to the
argument inside the function will not affect the original argument.
2. Pass by reference means that a reference to the argument is passed to the function. Any changes made
to the argument inside the function will affect the original argument.
 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

 Call by Reference
 Address of the function argument passed to the formal parameter of the function
Pass/Call by Value 41

void foo(int x) { In this example, the variable y is passed to the


function foo() by value.
x = 10;
} This means that a copy of the value of y is made and
passed to foo().

int main() { When foo() changes the value of x, it is only


changing the value of the copy of y. The original
int y = 5;
value of y is not affected.
foo(y);
std::cout << y << std::endl; // Prints 5
}
Example 2 42

/* Incorrect function to switch two void swap(int a, int b)


values */ {
int hold;
void swap(int , int );
int main() hold = a;
a = b;
{ b = hold;
int x=5,y=6; cout<<“after swapping from SWAP” <<a <<“ ”<<b;
}
swap(x,y);
cout<<“after swapping from MAIN ”<<x<<y;
}
Pass/Call by Reference 43

 In C++, call by reference is a method of


passing arguments to a function where
the reference of an argument is copied
into the formal parameter of the function.
 Reference parameters are useful in
three situations:
 Returning more than one value
 Changing the actual parameter
 When passing the address would save
memory space and time
Pass/Call by Reference 44

void foo(int &x) {


In this example, the variable y is passed to the
x = 10; function foo() by reference.
}
This means that a reference to the variable y is
passed to foo().
int main() {
When foo() changes the value of x, it is actually
int y = 5;
changing the value of the original variable y.
foo(y);
std::cout << y << std::endl; // Prints 10
}
Example 2 45

#include <stdio.h>
void swapnum(int &i, int &j) {
When the function swapnum() is called, the values of
int temp = i; the variables a and b are exchanged because they
i = j; are passed by reference.
j = temp; The output is:
}
int main(void) { A is 20 and B is 10

int a = 10;
int b = 20;
swapnum(a, b);
printf("A is %d and B is %d\n", a, b);
return 0;
}
Inline Function 46

 Inline functions in C++ are a feature that allows the function call to be replaced by the
actual function code at the point of function call.

 This can provide a performance benefit by reducing the overhead associated with
function calls.

 o declare an inline function in C++, the inline keyword is used before the function
declaration
inline int square(int x) {
return x * x;
}
Recursive function in C++ 47

 A recursive function is a function that calls itself directly or indirectly. This technique
provides a way to break complicated problems down into simple problems which are
easier to solve.
 Recursion may be a bit difficult to understand.
 The best way to figure out how it works is to experiment with it.
int factorial(int n) {
This function calculates the factorial of a number.
if (n == 0) { The base case is when n is 0. In this case, the function
return 1; returns 1.

} else { The recursive case is when n is greater than 0. In this


return n * factorial(n - 1); case, the function returns the product of n and the
factorial of n - 1.
}
}
Built in Functions (Math Library) 48

 abs(): The abs() function returns the absolute value of a number. For example, abs(-5) returns 5.
 acos(): The acos() function returns the arc cosine of a number. For example, acos(0.5) returns
1.0471975512.
 asin(): The asin() function returns the arc sine of a number. For example, asin(0.5) returns
0.5235987756.
 atan(): The atan() function returns the arc tangent of a number. For example, atan(1) returns
0.7853981634.
 atan2(): The atan2() function returns the arc tangent of two numbers. For example, atan2(1, 1)
returns 0.7853981634.
 ceil(): The ceil() function returns the smallest integer value greater than or equal to a number. For
example, ceil(3.1) returns 4.
 cos(): The cos() function returns the cosine of a number. For example, cos(0) returns 1.
Built in Functions (Math Library) 49

 exp(): The exp() function returns the exponential of a number. For example, exp(1)
returns 2.7182818284.
 fabs(): The fabs() function returns the absolute value of a floating-point number. For
example, fabs(-5.0) returns 5.0.
 floor(): The floor() function returns the largest integer value less than or equal to a
number. For example, floor(3.1) returns 3.
 log(): The log() function returns the logarithm of a number. For example, log(100) returns
2.
 log10(): The log10() function returns the logarithm of a number to the base 10. For
example, log10(100) returns 2.
Built in Functions (Math Library) 50

 pow(): The pow() function returns the power of a number to a given exponent. For
example, pow(2, 3) returns 8.
 sin(): The sin() function returns the sine of a number. For example, sin(0) returns 0.
 sqrt(): The sqrt() function returns the square root of a number. For example, sqrt(16)
returns 4.
 tan(): The tan() function returns the tangent of a number. For example, tan(0) returns 0.
Summary 51

 In real programs, we most often don’t want to look at a function body. Why would we

want to look at the body of the standard library sqrt() function?

 We define a function when we want a separate computation with a name because

doing so:-

 Makes the computation logically separate

 Makes the program text clearer (by naming the computation)

 Makes it possible to use the function in more than one place in our program

 Eases testing
Example Summary 52

#include <iostream>
In this example, we're defining a function
// function declaration
called add that takes two integer
int add(int a, int b); arguments and returns their sum.

int main() { We then declare the function in the main


function (this step is optional if you define
int x = 5, y = 10;
the function before main).
int z = add(x, y);
std::cout << "The sum of " << x << " and " << y << " is " When we call the add function in main, we
<< z << std::endl; pass the variables x and y as arguments,
and store the result in a new variable z.
return 0;
} We then print the result of the function call
// function definition using std::cout.
int add(int a, int b) {
return a + b;
}
Assignment I 53
Write a report that describes built-in functions in
C++ and provides examples of how to use them.
The report should be approximately 5 pages long
and should be written in a clear and concise
style.

REPORT OUTLINE
1. INTRODUCTION: PROVIDE AN OVERVIEW OF BUILT-IN FUNCTIONS IN C++.
2. TYPES OF BUILT-IN FUNCTIONS: DESCRIBE THE DIFFERENT TYPES OF BUILT-IN FUNCTIONS
IN C++.
3. EXAMPLES OF BUILT-IN FUNCTIONS: PROVIDE EXAMPLES OF HOW TO USE BUILT-IN
FUNCTIONS IN C++.
4. CONCLUSION: SUMMARIZE THE KEY POINTS OF THE REPORT.
54

}
End of Chapter 4
COMPUTER OF PROGRAMMING

You might also like