2. F1001 PROGRAMMING FUNDAMENTALS
INTRODUCTION
So far, in the previous unit, students only use one function in their program which is the main function
main(). But, when writing larger programs, we have to divide the program into smaller units which are
called functions whereby this units will solve only a particular problem in the program. This will make the
coding and the error correction process more easier.
In this unit, students will be given detailed explanation on functions, where and how the series of execution
can be controlled in the functions.
/*
Using functions in programs
*/
#include <stdio.h>
#include<conio.h>
Function
Prototype float kira_cal(int);
main()
{
clrscr(); Constant argument
int j;
float luas_area1;
float luas_area2; Calling a Function
luas_area1 = kira_cal(5);
printf("Luas bulatan / Circle area : %.fn", luas_area1);
printf("Masukkan nilai jejari / Enter radius : ");
scanf("%d", &j); Variable argument
luas_area2 = kira_cal(j);
printf("Luas bulatan / Circle area : %.fn", luas_area2);
}
Called Function
float kira_cal(int jejari_radius)
{
float luas_area;
luas_area = 3.142 * jejari_radius * jejari_radius;
return luas_area;
}
• The above program shows how a function is called to do a specific task..
• In the program the function kira_cal(int) is used to calculate the area of a circle.
• The program shows two ways of passing the value to the function which is, using constant argument
and variable parameter.
• Function kira_cal(int) will receive this value and do the mathematical operation and find the area of a
circle. This value will then be returned to main() function to be displayed.
106
3. F1001 PROGRAMMING FUNDAMENTALS
Introduction To Functions
Functions
• It is also known as program block
• A function is a self-contained program segment that carries out specific, well-defined task such as
calculations or displaying records..
• Some functions are built-in routines similar to library function that manipulates number, strings and
output such as scanf(), printf(), putchar() and so on.
• User-defined functions are the functions that the user writes.
Example of functions
Main function main()
Library Function stdio.h stdlib.h math.h conio.h string.h
User-defined function void print() char *process() int calculate (float a, int b)
Function basics
• A function definition has two principle components:
Example:
main() head
{
body
}
Head
• function name and a set of parentheses [ ( ) ].
• The parentheses may or may not contain parameters.
Body
• starts immediately after the closing parentheses of function name must be enclosed by braces
[ { } ].
• Contains one or more statement.
• Every function must have a name.
• Function name is created and assigned by the user based on similar rule that is used for naming
variables.
• All function names have one set of parentheses immediately after the function name. This helps you
differentiate them from variables. The parentheses may or may not contain any parameters.
107
4. F1001 PROGRAMMING FUNDAMENTALS
• Braces must enclose the body of each function, starting immediately after the closing parentheses of
the function name.
User Defined Functions:
Defining User Defined Functions
• Is a function that is created by the user.
Syntax: ReturnDataType functionName(ParameterList)
{
/*Any C statements/
}
Where:
FunctionName the function’s name
it is
Similar rules for naming the variable will be used for
naming functions.
returnDataType type of the item returned by the function.
data
ParameterList • represents the data type and variable name of the
parameters.
1. Function that does not receive or return any values
• The void keyword is optional for user-defined function, which does not returnDataType and
parameterList.
Syntax :
FunctionName()
{
/*function body*/
}
Example :
void message () void message (void)
{ OR {
printf(“WELCOME”); printf(“WELCOME”);
} }
2. Function that does not receive a value but returns a value.
108
5. F1001 PROGRAMMING FUNDAMENTALS
Syntax :
ReturnDataType functionName( )
{
/*function body*/
return value;
}
Example :
int count ()
{
int a, b, total;
printf(“Enter first number : ”);
scanf(“%d”, &a);
printf(“Enter second number : ”);
scanf(“%d”, &b);
total = a +b;
return total;
}
3. Function that receives values but returns nothing.
Syntax :
FunctionName(parameterList)
{
/*function body*/
}
Example :
void print (int age)
{
printf(“My age is %d years old”, age);
}
4. Function that receives and returns values.
109
6. F1001 PROGRAMMING FUNDAMENTALS
Syntax :
ReturnDataType functionName(parameterList)
{
/*Function body*/
return value;
}
Example :
int count (int a, int b)
{
int total;
total = a + b;
return total;
}
Function Prototype
• Sometimes the word prototype is refered to as a model.
• Function prototypes are used to define the user-defined functions before it can be used.
Syntax : ReturnDataType functionName(ParameterList);
• The simplest way is to rewrite your head of user-defined functions place it before the main() dunction
and end it with a semicolon ( ; ).
Example : /*function prototype*/
#include <stdio.h>
void message (); /*function
prototype*/
main ()
{
/*main function body*/
}
void message ()
{
/*function body*/
}
• All functions must match their prototype.
• Prototype can avoid programming errors.
• It will be more structured and therefore easier for us to read the code.
110
7. F1001 PROGRAMMING FUNDAMENTALS
• It allows the C compiler to check the syntax of function calls.
• If you break any prototyping rules, the compiler will show you the syntax errors and you can correct
it.
• You should prototype every function in your program except main(). It is done in order to define
which function that will be executed, their return types and their parameter types.
• If you write a user defined functions after function main(), you have to declare the function prototype
before function main().
• If you write a user defined functions before function main(), the function prototype is not needed.
Example :
/*Usage of functions without function prototype*/
#include <stdio.h>
void message ()
{
/*badan fungsi*/
}
main ()
{
/*badan fungsi main*/
}
Calling function and called function
• The name of your user-defined function must be called following the order of the statements inside the
body that will be executed first.
• Generally the primary function that controls functions order calls is named as a calling function.
• The functions controlled by the calling function is named as the called function.
Example:
#include <stdio.h>
void message (); /*function prototype*/
main ()
{
message (); /*calling function*/
}
void message () /*called function*/
{
/*function body*/
}
111
8. F1001 PROGRAMMING FUNDAMENTALS
• We can also call function from another function.
Example :
#include <stdio.h>
void call(); /*function prototype*/
void message ();
main ()
{
call(); /*calling function*/
message();
}
void call() /*called function*/
{
message(); /*calling function*/
}
void message () /* called function*/
{
/*function body*/
}
Passing Values
• Needed when the value of a local variable need to be transferred to another function.
• When a local variable is passed from one function to another, this means that you pass an argument
from the first function to the next.
• The called function receives a parameter from the function that sends it.
Function that sends one or VALUES: Function that
more arguments (local Local variables receives the
variables) to the receiving or constants parameters from the
function
calling function
Calling Function Called Function
Send : Argument (Receiving Function)
Receive : Parameter
112
9. F1001 PROGRAMMING FUNDAMENTALS
Passing by Value (by copy)
• Describes how the arguments are passed to receiving function.
• When an argument (local variable) is passed by value, the data item is copied to the function.
• Any alteration made to the data item within the function, will not give any changes to the calling
function.
Example :
/*Passing by values*/
#include <stdio.h>
void addition (int, int); /*function prototype consists by return parameter
List*/
main() /*calling function*/
{
int A = 3, B = 2;
addition (A, B); /*calling function with argument*/
}
void addition (int first, int second) /*called function with parameter*/
{
int product;
product = first + second;
printf(“%d + %d = %d”, first, second, product);
}
Output :
• In the above example value A and B are arguments that are sent too the called function (void addition).
The called function (void addition) will receive int first and int second as parameter.
• The number of arguments used to call a function must be similar to the number of parameters listed in
the function prototype.
• The order of arguments in the list shows the correspondence. The first argument corresponds to the
first parameter; the second argument corresponds to the second parameter, and so on.
• Each argument must be of data type that of the parameter that corresponds to it.
• The argument data type (calling function) must be the same as the parameters’ data type ( called
function ).
113
10. F1001 PROGRAMMING FUNDAMENTALS
Examples of Passing By Value
Passing by value is a method of passing an argument in which the original value is left unaltered no matter
how it is changed inside the function.
From the example below, note that passing by value method will not change the original value of A and B,
after the swap function is executed.
#include <stdio.h>
void swap(int x, int y)
{
int temp = x;
x = y;
y = temp;
}
int main()
{
int A, B;
printf("nA ? :");
scanf("%d",&A);
printf("nB ? :");
scanf("%d", &B);
printf("The value of A before calling swap() : %dn", A);
printf("The value of B before calling swap() : %dn", B);
swap(A, B);
printf("The value of A after calling swap() : %dn", A);
printf("The value of B after calling swap() : %dn", B);
return 0;
}
We declare the variables A and B. Therefore in memory we have space to retain two pieces of information.
A B
We take input from the keyboard.
A 2 B 3
When A and B are passed to the swap() function copies are made for x and y.
A 2 B 3
x 2 y 3
We then perform the statements in the body, swapping the copies.
A 2 B 3 Note that after the swap has
occurred, the original values of A
x 3 2 and B are retained.
y
114
11. F1001 PROGRAMMING FUNDAMENTALS
Passing by Address (by reference)
• When an argument (local variable) is passed by address, the address of a data item is passed to the
called function.
• The contents of that address can be accessed freely.
• Any change made to the data item will be recognized in both the called function and the calling
function. This means that the user have an ability to change the value in the called function and keep
those changes in effect in the calling function.
Example :
/*Penghantaran dengan alamat*/
#include <stdio.h>
void change (int *);
void main ()
{ Must be declared
int local = 3; with an asterisk
change (&local);
}
void change (int *p)
{
printf (“The value that you send is %d”, *p);
}
Output :
115
12. F1001 PROGRAMMING FUNDAMENTALS
Example of Passing By Reference
Passing by reference is a method of passing an argument that allows the called function to refer to the
memory holding the original value of the argument. This means that values changed in the called function
will alter the original value in the calling function.
#include <stdio.h>
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int A, B;
printf("nA ? :");
scanf("%d",&A);
printf("nB ? :");
scanf("%d", &B);
printf("The value of A before calling swap() : %dn", A);
printf("The value of B before calling swap() : %dn", B);
swap(&A, &B);
printf("The value of A after calling swap() : %dn", A);
printf("The value of B after calling swap() : %dn", B);
return 0;
}
With this example we see that the actual values are swapped within the function. Note how we indicate
that we want to pass by reference: we do so with the ampersand (&) between the data type and the variable
name. We declare the variables A and B. Therefore in memory we have space to retain two pieces of
information just as before.
A B
We take input from the keyboard.
A 2 B 3
When A and B are passed to the swap() function x and y point to the same space in memory.
x y
A 2 B 3
We then perform the statements in the body, swapping the originals.
x y
A 3 B 2
After we return from the function, we are left with:
The result is that the values are
A 3 B 2
swapped appropriately.
116
13. F1001 PROGRAMMING FUNDAMENTALS
Return Values
• Returns data from a receiving function (called function) to its calling function by putting the return
value after the return statement.
Syntax : return value;
Returns Value
Calling Called
Example :
#include <stdio.h>
Value which is float cal (int, int);
returned from
void main()
the called
{
function is int s, t;
assigned to a float a;
printf(“Please Enter Two Number ”);
scanf(“%d %d”, &s, &t);
a = cal(s, t);
printf(“Average of two numbers is : %.2f”, a);
}
Return Data float cal (int num1, int num2)
{
Type
float avg;
avg = (float)(num1 + num2) / 2;
return avg; Returns a value
}
Output :
117
14. F1001 PROGRAMMING FUNDAMENTALS
#include <stdio.h>
char* change ();
void main ()
NOTES {
char *a;
Return value is assigned
a = change ();
1. Do not a
to return global variables because their values are already known through the code.
printf("The word is : %s ", a);
}
Even though a function can receive more than one parameter, it can return one single value to the
calling function. IfType want to return more than a ()
Return Data you char* change value, you must pass the value by address.
{
Example : char *word = "Love";
Returns the
return (word); value“Love”
}
Output :
118