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

Chapter 6 Functions

Uploaded by

dambukidan06
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)
13 views

Chapter 6 Functions

Uploaded by

dambukidan06
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/ 8

School of Computing and Informatics

BCS 111 – Fundamentals of Programming


Chapter 6: Functions

R
1 Introduction
Function

LU
A function is a named block of code that perform some specific task

Defining a function

To define a function, the programmer has to do the following


U
• Specify the function header

• Define the function (actual statements that perform what exactly the function is expected to
do)
G
The general syntax of a function is
returnType functionName(optional−parameters)
N

1
2 {
3 function−body
4 −−−−−−−−−−−−
.A

5 −−−−−−−−−−−−
6 }

Listing 1: General Syntax of a function definition

The syntax shown in Listing 1 is explained as


1. Line 1: Function header/Function prototype - This specifies the function return type, name of
R

the function and list of zero (0) or more parameters


• Return type - This can be any of the primitive data types (int, float, double, char, bool etc)
D

or void. This specifies the type of data the function will return when it finishes executing. If its
declared as void, it means the function does not return any data and hence it will not have a
return statement
• Function name - This is the name that identifies the function in a program. Should obey rules
of variable names
• Parameters - These are memory locations (variables) that will hold data needed by the function
to accomplish its task. Not all functions should have parameters, so the parameter list could have
zero or more variable declarations
NB: A function signature consist of function name and parameter list (remember parameter
list could be empty)

Dr. Raphael Angulu, BCS 111 SCI, MMUST, 2020: Functions Notes 1
2. Line 2-6 Function body - This is a collection of lines of code enclosed in curl brackets. These lines
of code perform the task the function is expected to accomplish
Consider the function below
1 int summation()
2 {
3 int sum = 0;
4 for ( int i = 0; i < 5; i++)
5 {
6 sum += i;
7 }
8 return sum;
9 }

Listing 2: Function that calculates and returns sum of numbers between 0 and 5

The code in Listing 2 calculates and returns the sum of numbers between 0 and 5. In this code

R
1. Line 1 - Declares a function called summation which does not have any parameters and returns an
int after executing
2. Line 2-9 is the body of the function-lines of code that does exactly what the function is expected to

LU
do
3. Line 8 is a return statement. It returns the value stored in the variable sum to the piece of code
that calls (invokes) the function. Note that, the data type of the data returned MUST MATCH the
return type declared in the function header, for this case its int
However, assume you want a function that will return the sum of integers between two intervals. Now, such
U
a function must have parameters, one parameter to specify the start of the interval, and the other to specify
where to stop. Below is a function that returns the sum of integers between two intervals
1 int summation(int start, int stop)
G
2 {
3 int sum = 0;
4 for ( int i = start; i < stop; i++)
{
N

5
6 sum += i;
7 }
8 return sum;
.A

9 }

Listing 3: Function that calculates and returns sum of numbers between two intervals

Notice two parameters in the function header of the code in Listing 3.

This function will work properly only and only if start < stop. To make it robust such that it can work in
R

any situation (when start > stop) you need to swap start and stop when start > stop, before calculating
the sum as shown in the code below
int summation(int start, int stop){
D

1
2 int sum = 0;
3 if ( start > stop){
4 int temp = start;
5 start = stop;
6 stop = temp;
7 }
8 for ( int i = start; i < stop; i++)
9 sum += i;
10 return sum;
11 }

Listing 4: Function that calculates and returns sum of numbers between two intervals

Dr. Raphael Angulu, BCS 111 SCI, MMUST, 2020: Functions Notes 2
A function that returns void is a function that does not return any data to the code that called (invoked)
it. The return type of such a function is declared as void and the function does not have return return
statement. Consider the function in Listing 5 which displays the integer passed to it
1 void display( int x)
2 {
3 printf (”%d\n”, x);
4 }

Listing 5: Function that returns nothing

Note that, in line 1 of Listing 5, the return type is declared as void, and inside the body of the function,
there is no a return statement.

1.0.1 Calling/invoking a function


Calling or invoking a function is to transfer the flow of program execution to the function header.

R
• Calling a function that returns a value - There are two ways we can call a function that returns a value

– Assign the value returned to a variable. For instance, the summation function in Listing 2 could

LU
be called as
1 int s = summation();

In this case, the value returned is placed on the right side of the assignment (=) operator.
– Display the value returned as
U
1 printf (”%d”, summation());

If a function has parameters as the function defined in Listing 3 or Listing 4, you must pass
arguments to the function during a function call as
G
1 int s = summation(0, 5);

OR
N

1 printf (”%d”, summation(3, 12));

Arguments - Are actual values passed to function for further processing.


.A

• Calling a void function - This function returns nothing therefore you cannot assign its call to a variable.
For instance, the function display in Listing 5 can be called as
1 display(9) ;

You can call a function from anywhere in you program, provided that the function is already declared and
R

or defined.

1.1 Local and global variables


D

Local and global variables

• Local variable - These are variables that are declared within a function or a block of code and
can only be accessed within that block or function. For instance, in Listing 4, the variables
start, stop and i are local variables (i is declared within a for loop, its local)

• Global variables - These are variables that are declared outside all functions or blocks of code
and can be accessed from anywhere within the program. Consider the code below that declares
pi (π) as a global variable

Dr. Raphael Angulu, BCS 111 SCI, MMUST, 2020: Functions Notes 3
1 #include<stdio.h>
2 float pi = 3.142;
3 float area(int radius)
4 {
5 return pi ∗ radius ∗ radius ;
6 }
7 float perimeter(int radius)
8 {
9 return 2 ∗ pi ∗ radius
10 }
11 int main()
12 {
13 int rad;
14 printf (”Enter Radius: ”);
15 scanf(”%d”, &rad);
16 printf (”Area = %f\n”, area(rad));
17 float p = perimeter(rad);

R
18 printf (”Perimeter = %f\n”, p);
19
20 return 0;
21 }

LU
Notice that pi is a global variable declared and assigned a value on line 2 (outside all functions,
all blocks of code) and can be accessed from both perimeter and area functions

1.2 Pass by value and pass by reference


U
When calling a function that has parameters, we have to pass arguments to it. We can pass arguments to
a function in two ways
G
• Pass by value - copies of the value being passed to the function are copied into the arguments. Any
changes done by the function does not affect the original values passed to it

• Pass by reference - The reference of the values to be processed are passed to the function. Any
N

modifications done by the function also affects the original values

Consider the code below


.A

1 #include<stdio.h>
2 void square(int x)
3 {
4 x = x ∗ x;
5 }
6 void squared(int ∗x)
R

7 {
8 ∗x = ∗x ∗ ∗x;
9 }
10 int main()
D

11 {
12 int a = 3;
13 square(a);
14 printf (”Pass by value a = %d\n”, a);
15 //pass by reference
16 squared(&a);
17 printf (”Pass by reference a = %d\n”, a);
18 }

The output of this code is


From the output, you can see pass by value does not square the argument 3 while pass by reference the
value in memory location called a is changed after the function squared(...) defined between line 6-9 is

Dr. Raphael Angulu, BCS 111 SCI, MMUST, 2020: Functions Notes 4
invoked in line 16.

Examples of various functions

1. A function that receives an integer, calculates and returns factorial of that integer
1 int factorial ( int x){
2 int fact = 1;
3 for ( int i = x; i > 0; i−−)

R
4 {
5 fact ∗= i;
6 }
7 return fact ;
8 }

LU
Listing 6: Factorial of an integer

2. A function that receives two integers, calculates and return the Greatest Common Divisor (GCD) of
the two integers
1 int gcd(int x, int y){
U
2 int g = 1;
3 int min = x;
4 if ( x < y)
5 min = y;
G
6 for ( int i = 1; i <= min; i++) {
7 if ( x % i == 0 && y % i == 0)
8 g = i;
9 }
N

10 return g;
11 }

Listing 7: GCD of 2 integers


.A

3. Write a function that receives a positive integer x and displays x Fibonacci numbers where the nth
Fibonacci number is found by
Fn = Fn−1 + Fn−2 for F0 = 0 and F1 = 1
R

1 void fibonacci ( int x){


2 int f0 = 0; // first number in the sequence
int f1 = 1; //second number in the sequence
D

3
4 int i = 0;
5 printf (”%d\t%d”, f0, f1);
6 while( i <= x){
7 int next = f0 + f1;
8 printf (”\t%d”, next);
9 f0 = f1;
10 f1 = next;
11 i++;
12 }
13 }

Listing 8: Fibonacci Sequence

Dr. Raphael Angulu, BCS 111 SCI, MMUST, 2020: Functions Notes 5
4. You can approximate e using the series
1 1 1 1 1
e=1+ + + + ··· +
1! 2! 3! 4! i!
where i is the number of times you approximate e. Write a function that returns e after approximating
it x times, where x is a parameter passed to the function.
Hint: Because i! = i × (i − 1) × (i − 2) · · · × 2 × 1, therefore,
1 1
=
i! i(i − 1)!

1 double approximateE(int x){


2 double e = 2.0;
3 int facti = 1;
4 for ( int i = 2; i <= x; i++){

R
5 facti = i ∗ facti ;
6 e += 1.0 / facti ;
7 }
8 return e;
9 }

LU
Listing 9: Approximate e X number of times

1.3 Recursive Functions


Recursive function
U
A recursive function is a function that calls itself, within its body
G
Anything we can do with a loop can also be achieved using a recursive function.

Consider calculating factorial of a positive integer, we can do this with a loop as shown earlier, or using a
N

recursive function defined as


1 int factorials ( int x){
2 if ( x == 0 || x == 1)
.A

3 return 1;
4 else
5 return x ∗ factorials (x−1); //this function is calling itself here
6 }

Listing 10: Factorial of non-negative integer using recursive function


R

Consider also below a recursive function that calculates GCD of two integers
1 int gcds(int x, int y){
2 if (y == 0)
D

3 return x;
4 else
5 return gcds(y, x % y);
6 }

Listing 11: Using recursive function to calculate GCD of two integers

Write a recursive function that returns xth Fibonacci number (Fibonacci number at index x) where the
nth Fibonacci number is found by

Fn = Fn−1 + Fn−2 for F0 = 0 and F1 = 1

Dr. Raphael Angulu, BCS 111 SCI, MMUST, 2020: Functions Notes 6
1 int fibonaccis ( int x){
2 if (x == 0)
3 return 0;
4 else if (x == 1)
5 return 1;
6 else
7 return fibonaccis (x−1) + fibonaccis(x−2);
8 }

Listing 12: Using recursive function to get xth number in the Fibonacci sequence

1.4 Passing an array to a function


We can pass an array to a function in two ways

• Declare two parameters, one a pointer and the other as an integer to specify the size of the array

R
• Declare two parameters, one an empty array (no size specified) and the other as an integer to specify
the size of the array

Consider the code below that passes an array to a function. The function searches and returns the minimum

LU
number in the array
1 #include<stdio.h>
2 int minimum(int data[], int size ){
3 int min = data[0]; //lets assume the first element if the minimum
4 for ( int i = 1; i < size ; i++)
5 {
U
6 if (data[ i ] < min)
7 min = data[i];
8 }
G
9 return min;
10 }
11 int main()
12 {
N

13 int marks[5] = {45, 67, 23, 78, 65};


14 printf (”Minimun = %d ”, minimum(marks, 5));
15 }
.A

Note that, on line 14, while calling the function, we only specify the name of the array we are passing to
the function, for this case its marks.

We could achieve the same results by declaring the first parameter in the function as a pointer as shown
below
R

1 #include<stdio.h>
2 int minimum(int ∗data, int size){
3 int min = data[0]; //lets assume the first element if the minimum
4 for ( int i = 1; i < size ; i++)
D

5 {
6 if (data[ i ] < min)
7 min = data[i];
8 }
9 return min;
10 }
11 int main()
12 {
13 int marks[5] = {45, 67, 23, 78, 65};
14 printf (”Minimun = %d ”, minimum(marks, 5));
15 }

Dr. Raphael Angulu, BCS 111 SCI, MMUST, 2020: Functions Notes 7
1.5 Mathematical functions
C has a math.h library that defines various mathematical function commonly used. The table below shows
some of these functions Assume you are asked

Function Description Example


double abs(double x) This function returns the absolute abs(-9) returns 9
value of an integer. The absolute value
of a number is always positive. Only
integer values are supported in C.
double acos(double x) Returns the arc cosine of x in radians.
double asin(double x) Returns the arc sine of x in radians.
double atan(double x) Returns the arc tangent of x in radians.
double cos(double x) Returns the cosine of a radian angle x
double sin(double x) Returns the sine of a radian angle x

R
double sinh(double x) Returns the hyperbolic sine of x
double tanh(double x) Returns the hyperbolic tangent of x
double exp(double x) Returns the value of ex
double log(double x) Returns the natural logarithm (base-e

LU
logarithm) of x
double log10(double x) Returns the common logarithm (base-
10 logarithm) of x
double pow(double x, Returns x raised to the power of y pow(3.0, 2.0) returns 9
double y) pow(25.0, 0.5) returns 5
U
double sqrt(double x) Returns the square root of x sqrt(81) returns 9
double ceil(double x) Returns the smallest integer value ceil(8.76) returns 9
greater than or equal to x
G
double floor(double x) Returns the largest integer value less floor(2.5) returns 2
than or equal to x
N

Write a function that calculates the surface area of a right circular cone using the formulae
 p 
.A

A = πr r + h2 + r2

You could easily do this by using pow(..., ....) and sqrt(...) functions of the math.h library as
1 #include<stdio.h>
2 #include<math.h>
3 double surfaceArea(double r, double h)
R

4 {
5 double root = pow(h, 2) + pow(r, 2); //lets do h squared plus r squared
6 root = sqrt(root); //or you could use root = pow(root, 0.5)
D

7 root += r; // whole of expression in brackets is now done


8 double sa = 3.14159 ∗ r ∗ root;
9 return sa;
10 }
11 int main() //main function just to test our function
12 {
13 int rad = 7;
14 int height = 10;
15 double sa = surfaceArea(rad, height);
16 printf (”Surface area = %lf”, sa) ;
17 }

Dr. Raphael Angulu, BCS 111 SCI, MMUST, 2020: Functions Notes 8

You might also like