Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
26 views

Basic Programming Handouts

1) A function is a block of code that performs a specific task. Functions allow programmers to divide a large problem into smaller, more manageable parts. 2) There are two types of functions in C - predefined functions provided by libraries like printf(), and user-defined functions written by the programmer. 3) To define a user-defined function, a programmer specifies its return type, name, parameters, and the statements that implement its behavior between curly braces. Functions are invoked by calling their name and passing any required parameters.

Uploaded by

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

Basic Programming Handouts

1) A function is a block of code that performs a specific task. Functions allow programmers to divide a large problem into smaller, more manageable parts. 2) There are two types of functions in C - predefined functions provided by libraries like printf(), and user-defined functions written by the programmer. 3) To define a user-defined function, a programmer specifies its return type, name, parameters, and the statements that implement its behavior between curly braces. Functions are invoked by calling their name and passing any required parameters.

Uploaded by

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

C Programming Handout #5: Functions 1

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.

What types of function are there in C?

There are two types of function, namely:


1. Input/Outputpre-defined – those functions that have been written by for us (by some other programmers);
examples of such pre-defined functions are printf() and scanf() library functions
2. user-defined – those function that we are going to write/implement by ourselves; for example, we always have
to write our own implementation of the main() function

Our objective here is to learn how to write our own (i.e. user-defined) functions!

How do you define a function in C?

The syntax for a function definition is

<data type> <function name> (<parameter list>)


{
[<local variable declaration>]

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

How do you invoke a function that has already been defined?

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;

for (i = 0; i < 500; i++)


hello(); // call inside the body of the loop

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

Can you call a function inside another function (besides main)?

YES. Any function can be called inside any function.

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

Is the function parameter always void?

NO. The following are examples of functions with parameters.

Example:

#include <stdio.h>

/* this function has one parameter, type is int and name is x */


void OneParam(int x)
{
printf(“Number is %d\n”, x);
}

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>

/* this function has two parameters */


void TwoParams(int x, int y)
{
printf(“First parameter is %d\n”, x);
printf(“Second parameter is %d\n”, y);
}

void main(void)
{
int x;
int y;

int a;
int b;

TwoParams(10, 20); // use constants as parameters

x = 5;
y = 12;
TwoParams(x, y); // use variables as parameters

TwoParams(x + 2, y * 10); // use expressions 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>

/* this function has four parameters of different types */


void Test(char ch, int i, float f, double d)
{
printf(“char is %c\n”, ch);
printf(“integer is %d\n”, i);
printf(“float is %f\n”, f);
printf(“double is %lf\n”, d);
}

void main(void)
{
char ch;
int i;
float f;
double d;

Test(‘A’, 100, 1.25, 3.14159); // use constants

ch = ‘F’;
i = -25;
f = 100.75;
d = 1.23456789;
Test(ch, i, f, d); // use variables

Test(‘X’, i*2, f, d); // use constant, expression and variables


}
C Programming Handout #5: Functions 8

Are all functions of (return) type void?

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:

The following shows a function with an int return type.

#include <stdio.h>

int Sum(int x, int y)


{
int z;

z = x + y;

return z; // don’t forget to return a value


}

void main(void)
{
int a, b, c;

printf(“Sum = %d\n”, Sum(5, 10)); // use constants

c = Sum(100, 300); // store the return value into a variable


printf(“c = %d\n”, c);

a = 25;
b = 75;
printf(“Sum = %d\n”, Sum(a, b)); // use variables

printf(“Sum = %d\n”, Sum(a+2, b-3); // use expressions


}

Exercise:

▪ What will happen if the statement return z was omitted ?


▪ Write a function named Difference that accepts two integer parameters named x and y. The function
should compute and return the value of the difference of x and y (i.e., x – y). Call this function inside
main().
▪ Write a function named Product that accepts two floating point parameters named x and y. The function
should compute and return the value of the product of x and y (i.e., x * y). Use float as the return type. Call
this function inside main().
▪ Write a function named Quotient that accepts two double data type parameters named x and y. The
function should compute and return the value of the quotient of x and y (i.e., x / y). Use double as the return
type. Call this function inside main().
C Programming Handout #5: Functions 9

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.

/* example of a function that saves the return value


in a temporary variable */
int Positive(int n)
{
int result; // this is the temporary variable

if (n >= 0)
result = 1;
else
result = 0;

return result;
}

Another way to implement this function is as follows:

/* 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:

/* a function that calls another function */


int Negative(int n)
{
if (Positive(n)) // (Positive(n) == 1) is redundant!
return 0;
else
return 1;
}

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.

int Equivalent(int x, int y)


{
if (x == y)
return 1;
else
return 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.

double Minimum(double x, double y)


{
if (x < y)
return x;
else
return y;
}

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’.

/* example of a function that uses several return statements */


char Bingo(int n)
{
if (n >= 1 && n <= 15)
return ‘B’;
else if (n > 15 && n <= 30)
return ‘I’;
else if (n > 30 && n <= 45)
return ‘N’;
else if (n > 45 && n <= 60)
return ‘G’;
else return ‘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

What important things do I need to remember about functions?

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?

First, consider the following program:

#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.

▪ The program will start executing from the main() function.


▪ Inside main(), a variable named x is declared. This means that memory space which will be used in storing
an integer value for x will be allocated somewhere in the RAM.
▪ The variable x is then initialized to 0.
▪ Afterwards, the main() function calls test() with the “value” of x as a parameter. The program control is
passed from main() to test().
▪ If you look at the definition of test(), note that a parameter is declared as int x. Since this is also a
variable declaration by itself, memory space for this variable will be allocated somewhere in the RAM.
Therefore, there are two variables in our program, the first is variable x declared in main(), and the second is
variable x declared in test(). These two variables occupy different memory locations. It is imperative for
you to realize that although they have the same name, the two variables are different from each other!
(The following analogy should help. Imagine that there is a person named Ramon Garcia in the Philippines,
and another person of the same name somewhere in America and still another person of the same name in
Spain. Although they have the same name, these people are actually different individuals. The people would
correspond to program variables, while the countries would correspond to the functions where the variables
are declared.)
▪ Implicitly, the value of x in main() is copied as the initial value of variable x declared in test(). Thus,
the entity that is going to be manipulated inside test() is not the original variable x of main(), but a
COPYof it!
▪ The value of x defined in test()is changed to 1234 . This operation does not in any way affect the original
variable x in main(). The value of x in test() is 1234, the value of x in main() stays as 0.
▪ Since there is no more instruction after the increment operation, the function test() terminates and returns
the control back to main(). Actually, before doing this, the allocated memory space for the variable will be
de-allocated, which means that its content will no longer be accessible anymore to the program.
▪ The printf() function is called, which then prints the current value of x which is 0. Thereafter, the
program terminates. Note of course that before the actual program termination, the memory allocated to x will
be de-allocated.
The “question how can we change the value of the variable passed as a parameter to a function?” is still unanswered.
C Programming Handout #5: Functions 14

First, we show a program that does that kind of job. Note of the underlined items below.

#include <stdio.h>

void test(int *px)


{
*px = 1234; // don’t forget to affix the *
}

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;

// swap the contents of x and y


temp = x;
x = y;
y = x;

printf(“x = %d, y = %d\n”, x, y);


}

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>

// swap the contents of x and y


void swap(int x, int y)
{
int temp;

temp = x;
x = y;
y = temp;
}

void main(void)
{
int x, y;

x = 1;
y = 2;

swap(x, y);

printf(“x = %d, y = %d\n”, 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

The correct implementation is shown below.

#include <stdio.h>

// swap the contents of *px and *py


void swap(int *px, int *py)
{
int temp;

temp = *px; // don’t forget to affix the *


*px = *py;
*py = temp;
}

void main(void)
{
int x, y;

x = 1;
y = 2;

swap(&x, &y); // pass the address of x and y

printf(“x = %d, y = %d\n”, x, y);


}

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;

sumdiff(a, b, &c, &d); // c stores the sum of a and b


// d stored the difference of a and b
}

Write the implementation of the sumdiff() function.


C Programming Handout #5: Functions 17

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;

sumave(&sum, &ave, a, b, c);

printf(“Sum = %lf\n”, sum);


printf(“Average = %lf\n”, ave);
}

Write the implementation of the sumave() function.

▪ 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;

MinMax(a, b, c, &smallest, &largest);

printf(“Smallest value = %f\n”, smallest);


printf(“Largest value = %f\n”, largest);
}

Write the implementation of the MinMax() function.

You might also like