0% found this document useful (0 votes)
7 views18 pages

WEEK 9 Functions & Inroduction To Recursion

The document provides an overview of functions in C++, including standard library functions and user-defined functions, emphasizing their importance for code reusability, readability, and organization. It explains the structure of function declarations, definitions, and calls, along with the concept of function arguments and default parameter values. Additionally, it discusses storage classes, scope, and the use of the goto statement within functions.

Uploaded by

Amir ali
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)
7 views18 pages

WEEK 9 Functions & Inroduction To Recursion

The document provides an overview of functions in C++, including standard library functions and user-defined functions, emphasizing their importance for code reusability, readability, and organization. It explains the structure of function declarations, definitions, and calls, along with the concept of function arguments and default parameter values. Additionally, it discusses storage classes, scope, and the use of the goto statement within functions.

Uploaded by

Amir ali
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

WEEK-10

FUNCTIONS & INTRODUCTION TO


RECURSION

C++ programs are typically written by combining new functions and classes the
programmer writes with "prepackaged" functions and classes available in the C++
Standard Library.

The C++ Standard Library provides a rich collection of functions for performing common
mathematical calculations, string manipulations, character manipulations, input/output,
error checking and many other useful operations. This makes the programmer's job
easier, because these functions provide many of the capabilities programmers need.
The C++ Standard Library functions are provided as part of the C++ programming
environment.

There are two types of function:

1.​ Standard Library Functions: Predefined in C++


2.​ User-defined Function: Created by users

// function declaration
void greet() {
cout << "Hello World";
}

Here,

●​ the name of the function is greet()


●​ the return type of the function is void
●​ the empty parentheses mean it doesn't have any parameters
●​ the function body is written inside {}
Benefits of Using User-Defined Functions
●​ Functions make the code reusable. We can declare them once and use
them multiple times.
●​ Functions make the program easier as each small task is divided into a
function.
●​ Functions increase readability.

C++ Library Functions


Library functions are the built-in functions in C++ programming.

Programmers can use library functions by invoking the functions directly; they
don't need to write the functions themselves.

Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
In order to use library functions, we usually need to include the header file in
which these library functions are defined.

For instance, in order to use mathematical functions such as sqrt() and abs(),
we need to include the header file cmath.

Another is software reusability using existing functions as building blocks to create new
programs. For example, in earlier programs, we did not have to define how to read a
line of text from the keyboard C++ provides this capability via the getline function of
the <string> header file. A third motivation is to avoid repeating code. Also, dividing a
program into meaningful functions makes the program easier to debug and maintain.

A function is a group of statements that together perform a task. Every C++ program
has at least one function, which is main(), and all the most trivial programs can define
additional functions.
You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division usually is such that
each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.

There are three main attributes of a function


1.​ Function Declaration
2.​ Function Definition
3.​ Function Calling
The C++ standard library provides numerous built-in functions that your program can
call. For example, function strcat() to concatenate two strings, function memcpy() to
copy one memory location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure
etc.

Defining a Function
The general form of a C++ function definition is as follows −
return_type function_name( parameter list )
char addition void
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all
the parts of a function −
●​ Return Type − A function may return a value. The return_type is the data type of the value
the function returns. Some functions perform the desired operations without returning a
value. In this case, the return_type is the keyword void.
●​ 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, you pass a
value to the parameter. This value is referred to as actual parameter or argument. 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.

Example
Following is the source code for a function called max(). This function takes two
parameters num1 and num2 and return the biggest of both −
// function returning the max between two numbers

int max(int num1, int num2) {


// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

Function Declarations
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required,
so following is also valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the top
of the file calling the function.

Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To
use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function.
A called function performs defined task and when it’s return statement is executed or
when its function-ending closing brace is reached, it returns program control back to
the main program.
To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value. For example −
#include <iostream>
using namespace std;

// function declaration
int max(int num1, int num2);

int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;

// calling a function to get max value.


ret = max(a, b);
cout << "Max value is : " << ret << endl;

return 0;
}

// function returning the max between two numbers


int max(int num1, int num2) {
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;

return result;
}

I kept max() function along with main() function and compiled the source code. While
running final executable, it would produce the following result −
Max value is : 200

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 three ways that arguments can be passed to a
function –

[Link] Call Type & Description

1 Call by Value

This method 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.

2 Call by Pointer (Out of Scope of FOP Course Outline)


This method copies the address of an argument into the formal parameter. Inside the function,
the address is used to access the actual argument used in the call. This means that changes
made to the parameter affect the argument.

3 Call by Reference

This method 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 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 and above
mentioned example while calling max() function used the same method.

Default Values for Parameters


When you define a function, you can specify a default value for each of the last
parameters. This value will be used if the corresponding argument is left blank when
calling to the function.
This is done by using the assignment operator and assigning values for the arguments
in the function definition. If a value for that parameter is not passed when the function
is called, the default given value is used, but if a value is specified, this default value is
ignored and the passed value is used instead. Consider the following example –

#include <iostream>
using namespace std;

int sum(int a, int b = 20) {


int result;
result = a + b;

return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;

// calling a function to add the values.


result = sum(a, b);
cout << "Total value is :" << result << endl;

// calling a function again as follows.


result = sum(a);
cout << "Total value is :" << result << endl;
return 0;
}

When the above code is compiled and executed, it produces the following result −
Total value is :300
Total value is :120

Storage Classes
The programs you have seen so far use identifiers for variable names. The attributes of variables
include name, type, size and value. This chapter also uses identifiers as names for user-defined
functions. Actually, each identifier in a program has other attributes, including storage class,
scope and linkage.

C++ provides five storage-class specifiers: auto, register, extern, mutable and static. This
section discusses storage-class specifiers auto, register, extern and static. Storage-class
specifier mutable (discussed in detail in Chapter 24) is used exclusively with classes.

Storage Class, Scope and Linkage

An identifier's storage class determines the period during which that identifier exists in memory.
Some identifiers exist briefly, some are repeatedly created and destroyed and others exist for the
entire execution of a program. This section discusses two storage classes: static and automatic.

An identifier's scope is where the identifier can be referenced in a program. Some identifiers can
be referenced throughout a program; others can be referenced from only limited portions of a
program. Section 6.10 discusses the scope of identifiers.

[Page 263]

An identifier's linkage determines whether an identifier is known only in the source file where it
is declared or across multiple files that are compiled, then linked together. An identifier's
storage-class specifier helps determine its storage class and linkage.
Storage Class Categories

The storage-class specifiers can be split into two storage classes: automatic storage class and
static storage class. Keywords auto and register are used to declare variables of the automatic
storage class. Such variables are created when program execution enters the block in which they
are defined, they exist while the block is active and they are destroyed when the program exits
the block.

Local Variables

Only local variables of a function can be of automatic storage class. A function's local variables
and parameters normally are of automatic storage class. The storage class specifier auto
explicitly declares variables of automatic storage class. For example, the following declaration
indicates that double variables x and y are local variables of automatic storage class they exist
only in the nearest enclosing pair of curly braces within the body of the function in which the
definition appears:

auto double x, y;

Local variables are of automatic storage class by default, so keyword auto rarely is used. For the
remainder of the text, we refer to variables of automatic storage class simply as automatic
variables.

Register Variables

Data in the machine-language version of a program is normally loaded into registers for
calculations and other processing.

The storage-class specifier register can be placed before an automatic variable declaration to
suggest that the compiler maintain the variable in one of the computer's high-speed hardware
registers rather than in memory. If intensely used variables such as counters or totals are
maintained in hardware registers, the overhead of repeatedly loading the variables from
memory into the registers and storing the results back into memory is eliminated.

Using multiple storage-class specifiers for an identifier is a syntax error. Only one storage class
specifier can be applied to an identifier. For example, if you include register, do not also
include auto.
The compiler might ignore register declarations. For example, there might not be a sufficient
number of registers available for the compiler to use. The following definition suggests that the
integer variable counter be placed in one of the computer's registers; regardless of whether the
compiler does this, counter is initialized to 1:

register int counter = 1;

The register keyword can be used only with local variables and function parameters.

Static Storage Class


Keywords extern and static declare identifiers for variables of the static storage class and for
functions. Static-storage-class variables exist from the point at which the program begins
execution and last for the duration of the program. A static-storage-class variable's storage is
allocated when the program begins execution. Such a variable is initialized once when its
declaration is encountered. For functions, the name of the function exists when the program
begins execution, just as for all other functions. However, even though the variables and the
function names exist from the start of program execution, this does not mean that these
identifiers can be used throughout the program. Storage class and scope (where a name can be
used) are separate issues, as we will see in Section 6.10.

Identifiers with Static Storage Class

There are two types of identifiers with static storage class external identifiers (such as global
variables and global function names) and local variables declared with the storage class specifier
static. Global variables are created by placing variable declarations outside any class or
function definition. Global variables retain their values throughout the execution of the program.
Global variables and global functions can be referenced by any function that follows their
declarations or definitions in the source file.

NOTE: Variables used only in a particular function should be declared as local variables in
that function rather than as global variables

[Page 265]

Local variables declared with the keyword static are still known only in the function in which
they are declared, but, unlike automatic variables, static local variables retain their values
when the function returns to its caller. The next time the function is called, the static local
variables contain the values they had when the function last completed execution. The following
statement declares local variable count to be static and to be initialized to 1:

static int count = 1;

All numeric variables of the static storage class are initialized to zero if they are not explicitly
initialized by the programmer, but it is nevertheless a good practice to explicitly initialize all
variables.

Storage-class specifiers extern and static have special meaning when they are applied
explicitly to external identifiers such as global variables and global function names

Scope Rules
The portion of the program where an identifier can be used is known as its scope. For example,
when we declare a local variable in a block, it can be referenced only in that block and in blocks
nested within that block. This section discusses four scopes for an identifier function scope, file
scope, block scope and function-prototype scope.
An identifier declared outside any function or class has file scope. Such an identifier is "known"
in all functions from the point at which it is declared until the end of the file. Global variables,
function definitions and function prototypes placed outside a function all have file scope.

Labels (identifiers followed by a colon such as start:) are the only identifiers with function
scope. Labels can be used anywhere in the function in which they appear, but cannot be
referenced outside the function body. Labels are used in goto statements. Labels are
implementation details that functions hide from one another.

Labels Using goto statement in C/C++


The goto statement is a jump statement which is sometimes also referred to as unconditional
jump statement. The goto statement can be used to jump from anywhere to anywhere within a
function.​
Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a
label. Here label is a user-defined identifier which indicates the target statement. The statement
immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear
before the ‘goto label;’ statement in the above syntax.​

Below are some examples on how to use goto statement:​

Examples:
Type 1: In this case, we will see a situation similar to as shown in Syntax1 above. Suppose
we need to write a program where we need to check if a number is even or not and print
accordingly using the goto statement. Below program explains how to do this:

// C program to check if a number is


// even or not using goto statement
#include <stdio.h>

// function to check even or not


void checkEvenOrNot(int num)
{
​ if (num % 2 == 0)
​ ​ // jump to even
​ ​ goto even;
​ else
​ ​ // jump to odd
​ ​ goto odd;

even:
​ printf("%d is even", num);
​ // return if even
​ return;
odd:
​ printf("%d is odd", num);
}

int main() {
​ int num = 26;
​ checkEvenOrNot(num);
​ return 0;
}

Output:

26 is even

●​ Type 2:: In this case, we will see a situation similar to as shown in Syntax1 above.
Suppose we need to write a program which prints numbers from 1 to 10 using the goto
statement. Below program explains how to do this.
●​ // C program to print numbers
●​ // from 1 to 10 using goto statement
●​ #include <stdio.h>
●​
●​ // function to print numbers from 1 to 10
●​ void printNumbers()
●​ {
●​ int n = 1;
●​ label:
●​ printf("%d ",n);
●​ n++;
●​ if (n <= 10)
●​ goto label;
●​ }
●​
●​ // Driver program to test above function
●​ int main() {
●​ printNumbers();
●​ return 0;
●​ }
Output:
1 2 3 4 5 6 7 8 9 10

Identifiers declared inside a block have block scope. Block scope begins at the identifier's
declaration and ends at the terminating right brace (}) of the block in which the identifier is
declared. Local variables have block scope, as do function parameters, which are also local
variables of the function. Any block can contain variable declarations. When blocks are nested
and an identifier in an outer block has the same name as an identifier in an inner block, the
identifier in the outer block is "hidden" until the inner block terminates. While executing in the
inner block, the inner block sees the value of its own local identifier and not the value of the
identically named identifier in the enclosing block. Local variables declared static still have
block scope, even though they exist from the time the program begins execution. Storage
duration does not affect the scope of an identifier.

The only identifiers with function prototype scope are those used in the parameter list of a
function prototype. As mentioned previously, function prototypes do not require names in the
parameter list only types are required. Names appearing in the parameter list of a function
prototype are ignored by the compiler. Identifiers used in a function prototype can be reused
elsewhere in the program without ambiguity. In a single prototype, a particular identifier can be
used only once.

Passing Arguments by Value and by Reference


Figure 6.19 compares pass-by-value and pass-by-reference with reference parameters. The
"styles" of the arguments in the calls to function squareByValue and function
squareByReference are identical both variables are simply mentioned by name in the function
calls. Without checking the function prototypes or function definitions, it is not possible to tell
from the calls alone whether either function can modify its arguments. Because function
prototypes are mandatory, however, the compiler has no trouble resolving the ambiguity.

Figure 6.19. Passing arguments by value and by reference.

(This item is displayed on pages 276 - 277 in the print version)


1 // Fig. 6.19: fig06_19.cpp
2 // Comparing pass-by-value and pass-by-reference with references.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int squareByValue( int ); // function prototype (value pass)
8 void squareByReference( int & ); // function prototype (reference
pass)
9
10 int main()
11 {
12 int x = 2; // value to square using squareByValue
13 int z = 4; // value to square using squareByReference
14
15 // demonstrate squareByValue
16 cout << "x = " << x << " before squareByValue\n";
17 cout << "Value returned by squareByValue: "
18 << squareByValue( x ) << endl;
19 cout << "x = " << x << " after squareByValue\n" << endl;
20
21 // demonstrate squareByReference
22 cout << "z = " << z << " before squareByReference" << endl;
23 squareByReference( z );
24 cout << "z = " << z << " after squareByReference" << endl;
25 return 0; // indicates successful termination
26 } // end main
27
28 // squareByValue multiplies number by itself, stores the
29 // result in number and returns the new value of number
30 int squareByValue( int number )
31 {
32 return number *= number; // caller's argument not modified
33 } // end function squareByValue
34
35 // squareByReference multiplies numberRef by itself and stores the
result
36 // in the variable to which numberRef refers in function main
37 void squareByReference( int &numberRef )
38 {
39 numberRef *= numberRef; // caller's argument modified
40 } // end function squareByReference

x = 2 before squareByValue
Value returned by squareByValue: 4
x = 2 after squareByValue

z = 4 before squareByReference
z = 16 after squareByReference

[Page 277]
IMPORTANT NOTES:
●​ If a function is defined before it is invoked, then the function's definition also serves as
the function's prototype, so a separate prototype is unnecessary. If a function is invoked
before it is defined, and that function does not have a function prototype, a compilation
error occurs.
●​ Only local variables of a function can be of automatic storage class. A function's local
variables and parameters normally are of automatic storage class. The storage class
specifier auto explicitly declares variables of automatic storage class. For example, the
following declaration indicates that double variables x and y are local variables of
automatic storage classthey exist only in the nearest enclosing pair of curly braces within
the body of the function in which the definition appears:
▪​ auto double x, y;
●​ Local variables declared with the keyword static are still known only in the function in
which they are declared, but, unlike automatic variables, static local variables retain
their values when the function returns to its caller. The next time the function is called,
the static local variables contain the values they had when the function last completed
execution. The following statement declares local variable count to be static and to be
initialized to 1:
▪​ static int count = 1;

You might also like