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

Functions for programming

Notes from Babcock university Dr. Adekola Cos 101

Uploaded by

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

Functions for programming

Notes from Babcock university Dr. Adekola Cos 101

Uploaded by

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

User-Defined Functions

(Prepared By: ADEKOLA, Olubukola)

• A function or subroutine or program module is a chunk of code/


fragment/ segment (or lines, or set of lines of code) logically packed and
designed to perform a single well-defined task or some units of tasks.

• For example, if you have factorial of a number and square of a number


to find, the best practice is to make them into separate
functions/program modules that you can call them separately anytime
you need them. No matter how simple these operations appear, they are
two different tasks (refereed to as separate responsibilities in Object
Oriented Programming). The best practice is that a function should do
one task and do it well (i.e. it should support single responsibility).
Cramming these together in one module or just main() function is a poor
programming practice which leads to a lot of difficulties e.g. debugging,
maintenance, reuse problems. A good software engineering practice
such as modularising your code lends itself to the rich benefits in these
two attributes (maintainable and reusable programs) and even more.
Basic Things To Know:

(1) Function Definition -How to write a function within a


program
(2) Function Declaration –How to make the function
known to the program
(3) Function call - How to call a function from any part
of the program
(4) Ways of passing Parameter(s) - How to send
information/data to a function
(5) Returning result from function and functions that
return nothing
(6) Scope of variables
The Concept of Procedure Oriented Programming(POP)
(Modular Programming)

Words like module, subroutine, function are synonymously used to imply the
same concept originating from the idea called structured programming
concept where programs are written following some sets of procedures well
organised to make programming experience easy. Benefits include program
readability, write-ability, reusability, maintainability and so on.

A complete program may contain a number of different tasks/responsibilities


that is logical enough to make into different functions such that these
functions are only called when they are needed. Take for example a calculator
program to perform four basic operation for a pupil should include addition,
subtraction, multiplication and division. As simple as these operations are,
each is unique in its own respect. Therefore, we can create four subroutines
or module or functions called at needed times to accomplish this.
The following is a structure of modular concept:
Structure of Modular Concept
main()

f1() f2() f3()

There are 4 functions here, the main() function, f1(), f2() and f3(). main() calls
f1 and f2(), while f2() can also call f3() as the case may require. We do not
want to cram all these tasks into main() alone anymore as we used to do in
the elementary coding class.
A scenario of how f2() may need f3() is this: If function main() calls f2() to
action where f2() needs f3() before it can carry out its entire duty. It simply
means that part of f2() duty is delegated to f3(). And this sub-task is
delegated to f3() so that f2() is not also crammed up with many things. For
instance, if f2() is to fetch students with CGPA of 4.0 and above but should
present the result sorted. f3() could be the sort function doing the sorting
after f2() has fetched the list. You do not have to write a sorting routine inside
Declaring and Defining a function :

• One solid advantage of creating a function is that you can always


re-use it by just calling it instead of writing the entire code again
when it is needed somewhere else within or outside the immediate
program.
• Once you know the specific task a function should carry out, the
first is to name it. Just the way we name variables but with a
bracket after the name. A function can be given any name like
adekolaDan() but it makes sense and makes a good programming
practice to give a name that reflects what in particular the function
or module is to do. Therefore, I will prefer displayInfo() as a name
for the following function.

• Note, generally, a function has return type and form(format to


follow). We shall explain these better with time.
Declaring and Defining a function :

1. void displayInfo()
2. {
3. printf(”\n Welcome to the Input Segment”);
4. printf(”\n Please Enter Your Input Value”);
5. printf(”\n Note That Input is within 0-10”);
6. }

• The first line which declared the function is called function header; comprising
2 words, function return type (void) and function name (displayInfo()).

• displayInfo() is a function having 3 lines of executable codes that are just


displaying some messages on the screen for the user. The advantage here is
that if you need to display the same message anywhere or as many times as
you want in the program, you do not need to rewrite line 3 to 5 instructions
but only make a call to the function displayInfo(), the all the 3 messages are
done in one go.
Declaring and Defining a function :
• Void:
When a function terminates and does not send back or return some
information/ value but only display a message on the screen or does only
the task assigned, it means such does not return any information/value. So
we say the return type of that function is void. But if has a value to send
back to the caller (e.g. main()) , we say the function has a return type.
Therefore, in such a situation we don’t put void but rather the keyword for
the type of the value it is returning. Example is float or double for a floating
point value or int for integer and so on; instead of void.

• displayInfo():
This is the name you chose to give the function, followed by a pair of empty
brackets. If there is a need to send information or pass value into a function,
then the pair of brackets will not be empty but will contain the information.
This is the input avenue or medium to the function. Information passed to it
are referred to as parameters during function definition/declaration. These
information or values must also be declared using their data types. For
example, a function to receive a value for factorial is expecting an integer so
it could be defined as follows: int factorial(int n){….}
Declaring a function in C
C language demands that functions may be declared before use especially if you
intend to write the function anywhere in the program. It may not be necessary if the
functions are defined and seen ahead by the program before use. The culture of
declaring a function is simple to follow. Just the same way you declare a variable
before use, you also declare a function before use. The simple way to declare a
function is to copy the function definition header only and add a semicolon as follows:
void displayInfo(); // function now declared

• The general format is as follows:


return-type functionName(optional parameter list);
Note: As a variable is declared in the function where it is used, function declaration
is placed or done in the function where it would be used or called. E.g. if you placed
a declaration inside the main() function, it means the function would be used or
called by only the main() function. But if you want the function to be called or used
by another function other than main(), then you need to place its declaration before
or outside the main() function, hence a function declared this way in no longer local
to main() but a global function. That is, it can be seen and used by other functions in
addition to main. The function f3() can be declared this way in the earlier graphical
illustration.
Declaring a function in C
A) Declaring a function as local to main()
#include <stdio.h>

int main()
{
void displayInfo(); // function now declared inside main, seen by main alone
int I, j, count; // other variables local to main() function
----
----
return 0;
}

B) Declaring a function as global (External function)

#include <stdio.h>
void displayInfo(); /* function declared outside main(); now global function
accessible by other functions as well as main() function*/
int main()
{
int I, j, count; // other variables local to main() function
----
----
return 0;
}
Calling a function:

• Getting a written function to perform its task is a


process described as calling the function .
• When a function is called, we are actually doing
the instruction(s) inside it.
• We were used to only one function called main()
in our earlier programs; where you write
everything inside main(). The new functions we
are making/creating/defining by ourselves can be
called by the main() and can even call each other.
Calling a function:

• After declaration and definition, you get a function to perform


its task by calling the function. To call, use its name followed by
empty brackets when there is no information/parameter to
pass into it.
• e.g. displayInfo():
• This function is defined separately outside (not inside) the main
function. It stands alone. It means a function is a self-contained
unit written to perform a specific but well-defined task.
• The following example will demonstrate what we are saying
better. Also note that the order of arrangement of these
functions within the program has no effect / does not matter.
But very importantly only know that execution starts with the
main().
Program Example:

• void main()
• {
• …
• displayInfo(); /* function is called here. The benefit is that you
• need not re-write the 3 lines of code executed by this function
• anytime you want to achieve the same task, just call the function.
*/

• scanf(“%d”, &hour);
• …
• }// end of function main()

• //function is declared and defined below

• void displayInfo()
• {
• printf(”\n Welcome to the Input Segment”);
• printf(”\n Please Enter Your Input Value”);
• printf(”\n Note That Input is within 0-10”);
• }// end of function displayInfo()
Program Example:

• Evidently there are two functions in the code example above,


the first main() and the second displayInfo(). The second is
called inside the main(). The “ … “in the main function
preceding the calling indicates that the main function has been
executing some series of instruction before getting to the line
where the function displayInfo() is called. As this function is
called in the function(main() ), program control flow jumps out
of main() from that very point to where the called function is
defined (void displayInfo(){…} ), carries out the instructions in
the called function and comes back to the point where the
calling took place to proceed execution. A stack activation
record is internally required for the program to be able to
know where to return.
Calculator Programme Written as Functions
main()
The caller of other
functions

addition(a, b) subtraction(a, b) multiplication(a, b) division(a, b)

• The functions are declared inside main function -


meaning that they are local to main and therefore can
only be called by main. If we need to call them from
other parts of the program(i.e. if another function needs
to call them), then we must declared them outside of
main function(i.e. make them global functions).
Calculator: Implementation
1) //Program to implement simple calculator with functions
2) #include <stdio.h>
3) int main()
4) {
5) int a, b; // local variables (to main function) declared
6) int addition(int a, int b); // function declared in main
7) int subtraction(int a, int b); //a and b are formal parameters here
8) int multiplication(int a, int b);
9) float division(int a, int b);
Calculator: Implementation..contd..
10) printf("\n Enter the two values:");
11) scanf("%d %d", &a, &b);
12) // function called, a and b are actual arguments
13) //sending copies of values to the functions outside of main function
14) // a new variable is declared to store the value returned
15) int addResult = addition(a, b);
16) printf("\n The addition = %d ",addResult);
17) int subResult = subtraction(a, b);
18) printf("\n The subtraction = %d ",subResult);
19) int mulResult = multiplication(a, b);
20) printf("\n The multiplication = %d ",mulResult);
21) float divResult = division(a, b);
22) //Answer rounded off to 2 decimal places
23) printf("\n The division = %.2f ",divResult);

24) return 0;
25) }
Calculator: Implementation..contd..
26) // defining the function
27) // values in a and b are sent to x and y as inputs
28) int addition(int x, int y)
29) {
30) int add;
31) add = x+y; //the 3 lines could be summarised
32) return add; //to a line as: return x+y;
33) }

34) int subtraction(int x, int y)


35) {
36) int sub;
37) sub = x-y;
38) return sub;
39) }
Calculator: Implementation..contd..
40) int multiplication(int x, int y)
41) {
42) int mul;
43) mul = x*y;
44) return mul;
45) }

46) float division(int x, int y)


47) {
48) float div;
49) // type cast the integer division into float
50) div = (float)x/y;
51) return div;
52) }
Another Example Splitting into functions:

• void main()
• {
• float price, tax, result;
• Scanf(“%f”; &price);
• Scanf(“%f”; &tax);
• result = price * ( 1 + tax /100);
• pintln(“Cost After Tax = %f “, result);
• }

• The program illustrate a program comprising only a main() function


calculating a cost after tax. The same program can be re-written to use
two functions where tasks are delegated to different functions.
functions:

• We can create a function to perform the same calculation to enable us to call the
function at various points in the program where the calculation could be done using
different values passed to the function per each call. This gives the advantage of
code reusability. See below:
• float addTax(float price, float tax)
• {
• float answer;
• answer = price * ( 1 + tax /100);
• return answer;
• }
• The above function is named addTax and it is of type float (return type)
• The variables(price and tax) declared as float within the bracket are called formal
parameters.
• Formal Parameters: are variables created exclusively to hold values sent in from the
calling function(caller). They hold the values of data sent in the order with which
there are arranged in the function parameter declaration. i.e. price first, then tax
second.
PARAMETERS AND PARAMETER PASSING:

This arrangement must be the same with where the function is called. That is,
same order, same variable types and same quantity(number of parameters
passed). Formal parameter variables can answer any name apart from the one
used at where the function is called. What is important is the order of
arrangement and type. The parameter names at the function declaration does
not depend on the name you give the function parameters where it is called. It
means being “formal”, they can receive any value passed as far as the order and
type are not compromised. For now, parameter are said to be passed by value.
In the code above, variable answer is declared float inside the function addTax.
This is called a local variable as far as its scope is concerned. When a variable is
local to a function, it means it is known or valid within that function. For
example, answer is not known to main function in the example below. Similarly,
variable result is local to the main function and is not equally known to function
addTax.
The keyword return ends the function. The function terminates as soon as the
program reaches this point. The keyword return is used to send the result of
computation back to the caller. The control jumps back to the calling function
sending back a value i.e. the result of the computation. Any code written after it
becomes unreachable and that gives a compilation error.
MAKING YOUR OWN FUNCTIONS(USER-DEFINED FUNCTIONS)
1) #include <stdio.h>

2) int main()
3) {
4) float price, tax, result; //variable declarations
5) float addTax(float vprice, float vtax); // function declared
Actual Augment
6) printf("\n Enter the value of Price:");
7) Scanf(“%f”; &price); Line 10 represents a call to addTax()
8) printf("\n Enter the value of Tax:"); function. Here, parameters are passed
9) Scanf(“%f”; &tax); by values, the value of price and tax are
10) result = addTax(price, tax); // call; sent to the function. At line 10, these
11) printf(“Cost After Tax = %f “, result); are called actual argument because a
12) return 0; copy of what is read into price and tax
13) } are passed (to be used by the function
14) // vprice = price = 10.5 outside main()).
15) float addTax(float vprice , float vtax)
16) {
17) float answer; Formal parameter
18) answer = vprice * ( 1 + vtax/100);
19) return answer;
20) }
// SOLVING FOR FACTORIAL USING ONLY MAIN FUNCTION
1) //A C code using iterative procedure to find n! //5! = 5*4*3*2*1 or 1*2*3*4*5
2) #include <stdio.h>

3) int main()
4) {

5) int i, n, mult = 1; //variable declarations; set mult to 1 for multiplication

6) printf("\nEnter the value of n for the factorial:");


7) scanf("%d", &n);

8) // logic using iteration to do 1*2*3*4*5


9) for(i=1;i<=n;++i)
10) {
11) mult = mult*i;
12) }
13) printf("\nFactorial of %d = %d",n, mult);
14) return 0;
15) }
// SOLVING FOR FACTORIAL, BREAKING THE FUNCTIONALITY INTO
//ANOTHER USER-DEFINED FUNCTION APART FROM MAIN FUNCTION
1) //A C code using iterative procedure to find n! //5! = 5*4*3*2*1 or 1*2*3*4*5
2) #include <stdio.h>
3) int main()
4) {
5) int n; //variable declarations
6) int factorial(int n); //factorial function declared

7) printf("\nEnter the value of n for the factorial:");


8) scanf("%d", &n);
9) int result = factorial(n);
10) printf("\nFactorial of %d = %d",n, result );
11)
12) return 0;
13) }
14) //function definition
15) int factorial(int n)
16) {
17) int i, mult = 1;
18) for(i=1;i<=n;++i)
19) {
20) mult = mult*i;
21) }
22) return mult;
23) }
// MAKING MORE THAN ONE USER-DEFINED FUNCTIONS
//FINDING FACTORIAL AND SQUARE OF A NUMBER
1) //A C code using iterative procedure to find n! //5! = 5*4*3*2*1 or 1*2*3*4*5
2) #include <stdio.h>
3) int main()
4) {
5) int n; //variable declarations
6) int factorial(int n); //factorial function declared
7) int square(int n); // square function also declared in main

8) printf("\nEnter the value of n for the factorial:");


9) scanf("%d", &n);
10) int result = factorial(n);
11) printf("\nFactorial of %d = %d",n, result );
26) //lines of code continue…
12) int result2 = square(n); 27) int square(int n)
13) printf("\nSqaure of %d = %d", n, result2 ); 28) { int s; // s is local to square fn
14) return 0;
15) }
29) s = n*n;
16) //function definition 30) return s;
17) int factorial(int n) 31) }
18) {
19) int i, mult = 1;
20) for(i=1;i<=n;++i)
21) {
22) mult = mult*i;
23) }
24) return mult;
25) }
// USING SWITCH CONSTROL CONSTRUCT TO CALL DIFFERENT
USER-//DEFINED FUNCTIONS ( FACTORIAL AND SQUARE OF A NUMBER)
1) //A C code using iterative procedure to find n! //5! = 5*4*3*2*1 or 1*2*3*4*5
2) #include <stdio.h>
3) int square(int n); // square function can be declared outside the main() becoming a global function

4) int main()
5) {
6) int n, option; //variable declarations
7) int factorial(int n); //factorial function declared inside main function

8) printf("\nEnter 1 for factorial: \n2 for Square:"); 23) }//factorial function definition
9) scanf("%d", &option); 24) int factorial(int n)
10) printf("\nEnter the value of n:"); 25) {
11) scanf("%d", &n); 26) int i, mult = 1;
12) //selection structure used for user’s choice 27) for(i=1;i<=n;++i)
13) switch(option)
28) {
14) {
15) case 1: printf("\nFactorial of %d = %d",n, factorial(n)); 29) mult = mult*i;
16) break; 30) }
17) case 2: printf("\n Square of %d = %d",n, square(n)); 31) return mult;
18) break; 32) }
19) default: printf("\nValue out of range:"); 33) //square function definition
20) } 34) int square(int n)
21) return 0;
35) {
22) }
36) //operation reduced to a line
37) return n*n;
38) }
/* PROGRAM TO SHOW HOW TO REUSE ALREADY WRITTEN USER-
DEFINED FUNCTIONS ( E.G. FACTORIAL AND SQUARE OF A NUMBER )*/

The following program is written and saved as functionPark.cpp. This shall be


included in another program where the function defined here will be used. Note
that only the functions are written here and there is no main() function. The goal of
this is to achieve program abstraction and reuse. Abstraction in that some this code
details are now hidden or not visible in the other program, and reuse in that, any
program you include this can use the functions/ functionality.

1) //Program named and saved as functionPark.cpp; comprising of functions to be reused


2) //function definition
3) //factorial function
4) int factorial(int n)
5) {
6) int i, mult = 1;
7) for(i=1;i<=n;++i)
8) {
9) mult = mult*i;
10) }
11) return mult;
12) }
13) // square function
14) int square(int n)
15) {
16) return n*n;
17) }
/* PROGRAM TO SHOW HOW TO REUSE ALREADY WRITTEN USER-
DEFINED FUNCTIONS ( E.G. FACTORIAL AND SQUARE OF A NUMBER )*/

The following is the second program which reused the functionPack.cpp.


Note that the include is done with a double quote to indicate to the
compiler that the function named functionPack.cpp is a user defined.
1) //program named Reuse.cpp
2) // A program to compute f(x,n) = xn!
3) #include <stdio.h>
4) #include "functionPack.cpp" //code abstraction

5) int main()
6) {
7) int x, n;
8) printf("\nEnter the value of x:");
9) scanf("%d", &x);

10) printf("\nEnter the value of x:");


11) scanf("%d", &n);

12) int fxn = x*factorial(n);


13) printf("\nThe Output of f(x,n) = %d", fxn);
14) return 0;
15) }

You might also like