Basic Programming Handouts
Basic Programming Handouts
Handout #5
Functions
What is a function?
Before we answer that question, first imagine for example the following scenario. Let us assume that you were a
programmer and you were asked to write a program that will be used to handle Automated Teller Machine
transactions. Such transactions include: (1) balance inquiry, (2) deposit and say (3) withdrawal. Aside from these,
the user should be presented a menu showing these transactions as possible options. For a non-trivial program like
these, it is not advisable to write the codes under one main() program.
It is better to subdivide the program into smaller portions – which we will call functions. Each function should be
able to solve part of the bigger problem. In the scenario above, one function will handle the generation of the
menu, another function will be in-charge of handling the balance inquiry, another function will be used for deposit
transaction and a function will handle withdrawal transactions. Notice that each function does a specific job
independent of other functions.
In a more concrete term, a function is basically a program by itself – it may have input(s), output(s) and will perform
some kind of processing steps.
In computer programming, functions are also called subprograms. An aspiring computer programmer should be
able to determine based from the problem statement, what functions are needed and how to related these functions in
order to solve the problem.
Our objective here is to learn how to write our own (i.e. user-defined) functions!
[<statement>]
[<return value>]
}
C Programming Handout #5: Functions 2
Example:
We have been writing functions for quite some time, the main() function, for example
#include <stdio.h>
void main(void)
{
int x;
x = 1;
printf(“%d\n”, n);
}
In this case:
▪ void is the <data type> of the value returned by the function – void denotes that fact that the function
does not return anything
▪ main is the <function name>
▪ void is the <parameter list> – void denotes the fact that it does not have any parameter
▪ int x is the <local variable declaration> and
▪ x = 1; printf(“%d\n”, n); are the [<statements>]
Example:
The following shows a program with two functions, one is main(), the other one is hello().
#include <stdio.h>
void hello(void)
{
printf(“Hello\n”);
}
void main(void)
{
hello(); // call (invoke) the function
}
A function that has been defined by the user is invoked/executed by giving its name and its parameters. In the
example above, the hello() function is invoked inside the main().
We will also use the phrase “call the function hello()” to mean invoke/execute the statements inside the function.
C Programming Handout #5: Functions 3
A function can be called inside the main() function several times. For example, if we want to print the word
“Hello” three times, the main() function can be written as:
void main(void)
{
hello(); // call the function the 1st time
hello(); // call the function the 2nd time
hello(); // call the function the 3rd time
}
However, if we want to call the hello() function 500 times, it is better to write it as:
void main(void)
{
int i;
Exercise:
▪ Notice that we wrote the implementation of the function hello() is written before main(). What will
happen if the function hello() was written after the implementation of main()? That is, what will happen
if we have written the codes as follows:
#include <stdio.h>
void main(void)
{
hello(); // call (invoke) the function
}
void hello(void)
{
printf(“Hello\n”);
}
▪ Add another function that will simply print the word “Goodbye”. Use the name goodbye for the function.
Call it inside main().
C Programming Handout #5: Functions 4
Example:
#include <stdio.h>
void hello(void)
{
printf(“Hello”);
}
void space(void)
{
printf(“ ”);
}
void world(void)
{
printf(“world\n”);
}
void AllTogetherNow(void)
{
hello();
space();
world();
}
void main(void)
{
hello();
space();
world();
AllTogetherNow();
}
Notes:
▪ As shown in the example above, the functions hello(), space() and world() are called inside the
main() function.
▪ They are also called inside another function called Altogether() now proving the fact that functions can be
called inside other functions beside main().
Exercise:
▪ Move the implementation of the function hello() after the function world() and before the function
AllTogetherNow(). Does it differ from the results of the original program?
C Programming Handout #5: Functions 5
Example:
#include <stdio.h>
void main(void)
{
int x;
x = 100;
OneParam(x); // this is how OneParam() function is called
}
Exercise:
Do the following in sequence.
▪ Insert the statement OneParam(50). What can you conclude? That is, is it possible to use a constant value
as a parameter when the function is called?
▪ Declare another integer variable as follows: int y. Initialize the value of y to 25. Thereafter, write another
statement OneParam(y). What can you conclude? That is, is it possible to use a variable name that is not
the same with that used in the function definition?
▪ Insert the satement OneParam(x + y). What can you conclude? That is, is it possible to use an expression
(that will evaluate to an integer value) as a parameter when the function is called?
▪ Insert the statement OneParam(void). What can you conclude? That is, can you use void when the
function requires a parameter?
▪ Remove the word void from the previous exercise. What can you conclude?
C Programming Handout #5: Functions 6
Example:
#include <stdio.h>
void main(void)
{
int x;
int y;
int a;
int b;
x = 5;
y = 12;
TwoParams(x, y); // use variables as parameters
a = -3;
b = 22;
TwoParams(a, b); // use other variable names
}
Exercise:
▪ Insert the statement TwoParams(y, x). What can you conclude? Is the result the same as that of
TwoParams(x, y)?
▪ What will happen if we forgot to type the comma between parameters? For example, will TwoParams(x
y) work?
▪ What will happen if we only supplied one parameter? For example, will TwoParams(x) work?
▪ What will happen if we forgot all the parameters? For example, will TwoParams() work?
▪ What will happen if we used more than two parameters? For example, will TwoParams(x, y, a) work?
C Programming Handout #5: Functions 7
Example:
The following example shows a function with four parameters of different data types.
#include <stdio.h>
void main(void)
{
char ch;
int i;
float f;
double d;
ch = ‘F’;
i = -25;
f = 100.75;
d = 1.23456789;
Test(ch, i, f, d); // use variables
NO. The type void should be used as the return type only when the function does not return anything.
However, there are cases wherein the function will have to return a char, an int, a float or a double
depending on the problem being solved.
Example:
#include <stdio.h>
z = x + y;
void main(void)
{
int a, b, c;
a = 25;
b = 75;
printf(“Sum = %d\n”, Sum(a, b)); // use variables
Exercise:
We show more examples of functions below. New concepts/ideas are introduced in each particular example.
Example:
Write a function that will accept an integer variable as parameter. The function should return 1 if the integer is
positive (assume that zero is positive), otherwise it should return 0.
if (n >= 0)
result = 1;
else
result = 0;
return result;
}
/* solves the same problem but does not use a temp variable */
int Positive(int n)
{
if (n >= 0)
return 1; // return statement may appear more than
else // once as shown in this example
return 0;
}
An experienced C programmer would write it however in a more efficient way (although at first glance might not be
that readable)
int Positive(int n)
{
return (n >= 0);
}
A beginning programmer is not really forced to write it in this way. But it is suggested that he/she be familiarized
with it in order to read/understand the source codes written by other programmers.
C Programming Handout #5: Functions 10
Example:
Write a function that will accept an integer variable as parameter. The function should return 1 if the integer is
negative, otherwise it should return 0.
The solution to this is almost the same as in the previous problem (i.e., test for positive).
int Negative(int n)
{
if (n < 0)
return 1;
else
return 0;
}
Alternatively, if we assume that the Positive() function has already been implemented, we could use it to write
the Negative() function as follows:
How do you think will an experienced C programmer implement the Negative() function. Hint #1: if-else is
not going to be used. Hint #2: A negative number is NOT a positive number. Got it?
Example:
Write a function that accepts two integers. Thereafter, the function should return a value of 1 if these numbers are
equivalent, otherwise it should return a value of 0.
How do you think will an experienced C programmer implement the Equivalent() function?
C Programming Handout #5: Functions 11
Example:
Write a function that accepts two double data type values. The function should return the smaller of the two values.
Example:
Write a function that will accept an integer whose value is between 1 to 75 corresponding to the numbers in a
BINGO game. Thereafter, the function should return the letter (use capital letter) of corresponding to the number.
That is, the numbers from 1 to 15 correspond to ‘B’, 16 to 30 correspond to ‘I”, 31 to 45 correspond to ‘N’, 46 to 60
correspond to ‘G’ and 61 to 75 correspond to ‘O’.
Exercise:
▪ Write a function that will accept an integer variable as parameter. The function should return 1 if the integer is
an even number, otherwise it should return 0.
▪ Write a function that accepts two floating point data type values. The function should return the bigger of the
two values.
▪ Solve/rewrite the examples and exercises in Handout #4 (Control Structures) as functions and include a call to
them inside main().
C Programming Handout #5: Functions 12
1. If the function will not return any value use, void as the return type.
2. If the function will return a value, the appropriate data type should be specified.
3. If the function will return a value, don’t forget to use the return statement inside the function.
4. The data type of the value that appears after the return statement must be compatible with the return data
type.
5. You can use any name for the function as long as you follow the naming conventions and do not use C
keywords as function names.
6. A function may have zero, one or more parameters.
7. If the function does not have any parameter, use void.
8. If the function has parameters, specify their data types and names.
9. Parameters should be separated by comma.
10. The name of the parameter does not matter. Always remember that the
▪ number of parameters,
▪ their respective data types, and
▪ their sequence
are the things that actually matter!
11. When calling a function, constants, expressions and variables maybe used as parameters.
12. A function can return at the most only one value at any given point in time.
C Programming Handout #5: Functions 13
How do I change the value of a parameter inside a function such that it will affect the original variable?
#include <stdio.h>
void test(int x)
{
x = 1234;
}
void main(void)
{
int x;
x = 0;
test(x);
printf(“x = %d\n”, x);
}
What do you think is the output of the program? If you answered “x = 1234”, then it is WRONG! Actually the
output on the screen will be “x = 0”.
Let us trace the program to fully understand the statements made above.
First, we show a program that does that kind of job. Note of the underlined items below.
#include <stdio.h>
void main(void)
{
int x;
x = 0;
test(&x); // pass the address of x as parameter
printf(“x = %d\n”, x);
}
If you run this program, the output that you will see on the screen is “x = 1234”.
Three things that you should take note (and learn) from this example:
▪ First, the call to the function test() uses &x as parameter. The & is actually one of unary operators defined
in C language. The & operator is called address of operator, and it is always written before a variable. Thus,
&x, is read as “the address of x”. What is being passed as a parameter is not the VALUE of x, but the
MEMORY ADDRESS of x.
To be able to change the data stored in a variable in another function, it is necessary to pass its address and not
(a copy) of its value. This is actually the explanation as to why the & operator is written before a variable
when calling scanf(), for example, scanf(“%d”, &n).
▪ Second, the function definition for test()declares its parameter as int *px. The * before px is a “special
symbol” to denote the fact that px is a variable that will contain memory address as its value. In the program
above, the value of px is the address of x. The address of x is assigned to px (implicitly) when the function
test() is called inside main().
▪ Third, to be able to change the value of the data stored in the original x, the * should also be written before px;
for example in the program above, *px = 1234.
Exercise:
▪ Try to remove the ampersand in test(&x) in the program above. What happens?
▪ Next using the original program above, try to remove the asterisk in the parameter declaration void
test(int *px). What happens?
C Programming Handout #5: Functions 15
Consider another example. The following program shows how to swap (interchange) the content of two variables.
#include <stdio.h>
void main(void)
{
int x, y, temp;
x = 1;
y = 2;
The swap operation can be rewritten as a function. However, if your implementation is something like the
program below, then it will not work correctly (read: it is INCORRECT!).
#include <stdio.h>
temp = x;
x = y;
y = temp;
}
void main(void)
{
int x, y;
x = 1;
y = 2;
swap(x, y);
If you run this program, note that the values of x and y were not swapped. They are still the same.
C Programming Handout #5: Functions 16
#include <stdio.h>
void main(void)
{
int x, y;
x = 1;
y = 2;
Exercise:
▪ Try to remove the ampersand in swap(&x, &y) above. What will happen?
▪ Next using the original program above, try to remove the asterisk in the parameter declaration void
swap (int *px, int *py). What happens?
A more detailed discussion of the & and * operators will be given in an advanced C programming course. So
you’ve got to wait until then…
Exercise:
▪ A function called sumdiff() is used to compute the sum and difference of two floating point variables. An
example of how it is called is shown below:
void main(void)
{
float a, b, c, d;
a = 1.25;
b = 3.12;
Exercise: (continuation…)
▪ A function called sumave()is used to compute the sum and average of three double data type variables. An
example of how it is called is shown below:
void main(void)
{
double a, b, c;
double sum; // used to store sum
double ave; // used to store the average
a = 1.0;
b = 2.0;
c = 3.0;
▪ A function called MinMax() is used to determine the smallest and largest valued elements given three floating
point variables. An example of how it is called is shown below:
void main(void)
{
float a, b, c;
float smallest; // used to store the smallest value
float largest; // used to store the largest value
a = 2.0;
b = 1.0;
c = 3.0;