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

Week 9 - 10 Functions

The document discusses C++ functions including user-defined functions, function parameters, return statements, function prototypes, and library functions. It provides examples of different types of functions such as those with and without parameters or return values.

Uploaded by

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

Week 9 - 10 Functions

The document discusses C++ functions including user-defined functions, function parameters, return statements, function prototypes, and library functions. It provides examples of different types of functions such as those with and without parameters or return values.

Uploaded by

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

CSC1100: Computer Programming I

Presented By:
Dr. Abdalla Moustafa

[Week 9-10]

1
Students Learning Objectives (Weeks Nine & Ten)

 Introduction to functions
 Function declaration and definition
 Function parameters (pass by value)
 Function calling
 Function overloading
 C++ storage class
 C++ Recursion

2
C++ Functions

• A function is a block of code that performs a specific task.


• Suppose we need to create a program to create a circle and color it. We can create two
functions to solve this problem:
• a function to draw the circle
• a function to color the circle
• Dividing a complex problem into smaller chunks makes our program easy to
understand and reusable.
• There are two types of function:
1.Standard Library Functions: Predefined in C++
2.User-defined Function: Created by users
• In this class, we will focus mostly on user-defined functions.

3/27
User-defined Function

• C++ allows the programmer to define their own function.


• A user-defined function groups code to perform a specific task and that group of code is
given a name (identifier).
• When the function is invoked from any part of the program, it all executes the codes
defined in the body of the function.

4/27
C++ Function Declaration

The syntax to declare a function is:

Here's an example of a function declaration.

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 {}

5/27
Calling a Function

• In the above program, we have declared a function named greet(). To use


the greet() function, we need to call it.

• Here's how we can call the above greet() function.

6/27
Example 1: Display a Text

7/27
Function Parameters

• As mentioned above, a function can be declared with parameters (arguments).


• A parameter is a value that is passed when declaring a function.
• For example, let us consider the function below:

• Here, the int variable num is the function parameter.


• We pass a value to the function parameter while calling the function.

8/27
Example 2: Function with Parameters

• In the above program, we have used a


function that has one int parameter
and one double parameter.

• We then pass num1 and num2 as


arguments. These values are stored
by the function
parameters n1 and n2 respectively.

9/27
Function with Parameters

Note: The type of the arguments passed while calling the function must match with
the corresponding parameters defined in the function declaration.
10/27
Return Statement

In the above programs, we have used void in the function declaration. For example,

• This means the function is not returning any value.


• It's also possible to return a value from a function. For this, we need to specify
the returnType of the function during function declaration.
• Then, the return statement can be used to return a value from a function.
For example,

11/27
Return Statement

• Here, we have the data type int instead of void. This means that the function returns
an int value.
• The code return (a + b); returns the sum of the two parameters as the function value.
• The return statement denotes that the function has ended. Any code
after return inside the function is not executed.

12/27
Example 3: Add Two Numbers

• In the above program,


the add() function is used to find the
sum of two numbers.
• We pass two int literals 100 and 78
while calling the function.
• We store the returned value of the
function in the variable sum, and
then we print it.

13/27
Example 3: Add Two Numbers

Notice that sum is a variable of int type. This is because the return value of add() is
of int type.

14/27
Function Prototype

• In C++, the code of function declaration should be before the function call.
• However, if we want to define a function after the function call, we need to use the function
prototype. For example,
In this code, the function prototype is:

• This provides the compiler with


information about the function
name and its parameters.
• That's why we can use the code to
call a function before the function
has been defined.

The syntax of a function prototype is:


15/27
Example 4: C++ Function Prototype

• The above program is nearly


identical to Example 3.
• The only difference is that here,
the function is defined after the
function call.
• That's why we have used a
function prototype in this
example.

16/27
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.

17/27
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.

18/27
C++ User-defined Function Types

For better understanding of arguments and return in functions, user-defined functions can
be categorized as:
•Function with no argument and no return value
•Function with no argument but return value
•Function with argument but no return value
•Function with argument and return value

Consider a situation in which you have to check prime number. This problem is solved
below by making user-defined function in 4 different ways as mentioned above.

19/27
Example 1: No arguments passed and no return value
• In the above program, prime() is
called from the main() with no
arguments.
• prime() takes the positive number
from the user and checks whether the
number is a prime number or not.
• Since, return type of prime() is void,
no value is returned from the
function.

20/27
Example 2: No arguments passed but a return value

• In the above
program, prime() function is called
from the main() with no arguments.
• prime() takes a positive integer from
the user. Since, return type of the
function is an int, it returns the
inputted number from the user back
to the calling main() function.
• Then, whether the number is prime
or not is checked in the main() itself
and printed onto the screen.

21/27
Example 3: Arguments passed but no return value

• In the above program, positive


number is first asked from the user
which is stored in the variable num.
• Then, num is passed to
the prime() function where, whether
the number is prime or not is
checked and printed.
• Since, the return type of prime() is
a void, no value is returned from the
function.

22/27
Example 4: Arguments passed and a return value.

• In the above program, a positive


integer is asked from the user and
stored in the variable num.
• Then, num is passed to the
function prime() where, whether the
number is prime or not is checked.
• Since, the return type of prime() is
an int, 1 or 0 is returned to
the main() calling function. If the
number is a prime number, 1 is
returned. If not, 0 is returned.
• Back in the main() function, the
returned 1 or 0 is stored in the
variable flag, and the corresponding
text is printed onto the screen.

23/27
Which method is better?

• All four programs above gives the same output and all are technically correct program.
• There is no hard and fast rule on which method should be chosen.
• The particular method is chosen depending upon the situation and how you want to
solve a problem.

24/27
C++ Function Overloading
• In C++, two functions can have the same name if the number and/or type of arguments passed is
different.
• These functions having the same name but different arguments are known as overloaded functions.
For example:

• Here, all 4 functions are overloaded functions.


• Notice that the return types of all these 4 functions are not the same. Overloaded functions may or
may not have different return types but they must have different arguments. For example,

• Here, both functions have the same name, the same type, and the same number of arguments.
Hence, the compiler will throw an error.

25/27
Example 1: Overloading Using Different Types of Parameter

• In this program, we overload


the absolute() function.
• Based on the type of parameter
passed during the function call,
the corresponding function is
called.

26/27
Example 1: Overloading Using Different Types of Parameter

27/27
Example 2: Overloading Using Different Number of Parameters

• Here, the display() function is


called three times with different
arguments.
• Depending on the number and type
of arguments passed, the
corresponding display() function is
called.

28/27
Example 2: Overloading Using Different Number of Parameters

• The return type of all


these functions is the
same but that need not
be the case for function
overloading.

Note:
• In C++, many standard
library functions are
overloaded. For
example,
the sqrt() function can
take double, float, int, etc. as
parameters.
• This is possible
because
the sqrt() function is
overloaded in C++.
C++ Programming Default Arguments (Parameters)

• In C++ programming, we can provide default values for function parameters.


• If a function with default arguments is called without passing arguments, then the default parameters
are used.
• However, if arguments are passed while calling the function, the default arguments are ignored.

Working of default arguments

30/27
C++ Programming Default Arguments (Parameters)

We can understand the working of default


arguments from the image above:
1. When temp() is called, both the default parameters
are used by the function.
2. When temp(6) is called, the first argument
becomes 6 while the default value is used for the
second parameter.
3. When temp(6, -2.3) is called, both the default
parameters are overridden, resulting in i = 6 and f =
-2.3.
4. When temp(3.4) is passed, the function behaves in
an undesired way because the second argument
cannot be passed without passing the first
argument.

Therefore, 3.4 is passed as the first argument.


Since the first argument has been defined as int,
the value that is actually passed is 3.
31/27
Example: Default Argument

Here is how this program works:


1. display() is called without passing any
arguments. In this case, display() uses both
the default parameters c = '*' and n = 1.
2. display('#') is called with only one argument.
In this case, the first becomes '#'. The
second default parameter n = 1 is retained.
3. display('#', count) is called with both
arguments. In this case, default arguments
are not used.

32/27
Example: Default Argument
We can also define the default parameters in the function definition itself. The program below is equivalent
to the pervious one.

33/27
Things to Remember
1. Once we provide a default value for a parameter, all subsequent parameters must also have default
values. For example,

2. If we are defining the default arguments in the function definition instead of the function prototype, then
the function must be defined before the function call.

34/27
C++ Storage Class

• Every variable in C++ has two features: type and storage class.
• Type specifies the type of data that can be stored in a variable. For
example: int, float, char etc.
• And, storage class controls two different properties of a variable: lifetime (determines how
long a variable can exist) and scope (determines which part of the program can access it).

Depending upon the storage class of a variable, it can be divided into 3 major types:
•Local variable
•Global variable
•Static local variable

35/27
Local Variable

• A variable defined inside a function (defined inside function body between braces) is called a local
variable or automatic variable.
• Its scope is only limited to the function where it is defined. In simple terms, local variable exists and
can be accessed only inside a function.
• The life of a local variable ends (It is destroyed) when the function exits.

36/27
Example 1: Local variable

• The variable var cannot be used


inside test() and var1 cannot be
used inside main() function.
• Keyword auto was also used for
defining local variables before
as: auto int var;
• But, after C++11 auto has a different
meaning and should not be used for
defining local variables.

37/27
Global Variable

• If a variable is defined outside all functions, then it is called a global variable.


• The scope of a global variable is the whole program. This means, It can be used and changed at any
part of the program after its declaration.
• Likewise, its life ends only when the program ends.

38/27
Example 2: Global variable

• In the above program, c is a global


variable.
• This variable is visible to both
functions main() and test() in the
above program.

39/27
Static Local variable
Keyword static is used for specifying a static variable. For example:

• A static local variable exists only inside a function where it is declared (similar to a local
variable) but its lifetime starts when the function is called and ends only when the program
ends.
• The main difference between local variable and static variable is that, the value of static
variable persists the end of the program.

40/27
Example 3: Static local variable

• In the above program, test() function is invoked 2 times.


• During the first call, variable var is declared as static
variable and initialized to 0. Then 1 is added to var which
is displayed in the screen.
• When the function test() returns, variable var still exists
because it is a static variable.
• During second function call, no new variable var is
created. The same var is increased by 1 and then
displayed to the screen.
C++ Recursion
A function that calls itself is known as a recursive function. And, this technique is known as recursion.

Working of Recursion in C++

• The recursion continues until some condition is met.


• To prevent infinite recursion, if...else statement (or similar approach) can
be used where one branch makes the recursive call and the other
doesn't.
Example 1: Factorial of a Number Using Recursion
Working of Factorial Program

• As we can see,
the factorial() function is
calling itself. However, during
each call, we have decreased
the value of n by 1.
• When n is less than 1,
the factorial() function
ultimately returns the output.
Example 3: Static local variable

• In the above program, test() function is invoked 2 times.


• During the first call, variable var is declared as static
variable and initialized to 0. Then 1 is added to var which
is displayed in the screen.
• When the function test() returns, variable var still exists
because it is a static variable.
• During second function call, no new variable var is
created. The same var is increased by 1 and then
displayed to the screen.
Advantages and Disadvantages of Recursion

Advantages of C++ Recursion


•It makes our code shorter and cleaner.
•Recursion is required in problems concerning data structures and advanced
algorithms, such as Graph and Tree Traversal.

Disadvantages of C++ Recursion


•It takes a lot of stack space compared to an iterative program.
•It uses more processor time.
•It can be more difficult to debug compared to an equivalent iterative program.
Thank You…

47

You might also like