Principles of Programming
CSEB134 : BS/2008 1
Functions
Principles of Programming
CSEB134 : BS/2008 2
Objectives
Introduction to function Predefined functions / Standard functions User defined functions
function declarations/prototype function definition function call and return
Function with parameters/ argument Scope of variables – global and local variables Duration of variables Simple recursion
Principles of Programming
CSEB134 : BS/2008 3
Introduction to Functions A function is a block of code which is used to
perform a specific task. It can be written in one program and used by
another program without having to rewrite that piece of code.
Functions can be put in a library. If another program would like to use them, it will just need to include the appropriate header file at the beginning of the program and link to the correct library while compiling.
A function is used by calling the name of the function.
Principles of Programming
CSEB134 : BS/2008 4
Categories of Functions
Predefined functions (standard functions) Built-in functions provided by C that are used by
programmers without having to write any code for them. Pre-defined at the standard C libraries.
Example: printf(), scanf(), main() etc User-Defined functions
Functions that are written by the programmers themselves to carry out various individual tasks.
Examples: CalculateAverage(), Sum() etc
Principles of Programming
CSEB134 : BS/2008 5
Pre-defined Functions
<assert.h> Contains macros and information for adding diagnostics that aid program debugging.
<ctype.h> Contains function prototypes for functions that test characters for certain properties, convert lowercase letters to uppercase and vice versa.
<errno.h> Defines macros that are useful for reporting error condition.
<float.h> Contains the floating point size limits of the system.
<limits.h> Contains the integral size limits of the system.
<math.h> Contains function prototypes for math library functions.
<setjump.h>
Contains function prototypes for function that allow bypassing of the usual function call and return sequence.
Principles of Programming
CSEB134 : BS/2008 6
Pre-defined Functions<signal.h> Contains function prototypes and macros to handle various
conditions that may arise during program execution.
<stdarg.h> Defines macros for dealing with a list of arguments to a function whose number and types are unknown.
<stddef.h> Contains common definitions of types used by C for performing certain calculations.
<stdio.h> Contains function prototypes for the standard input/output library functions and information used by them.
<stdlib.h> Contains function prototypes for conversions of numbers to text and text to numbers, memory allocation, random numbers, and other utility functions
<string.h> Contains function prototypes for string processing functions.
<time.h> Contains functions prototypes and types for manipulating time and date.
Principles of Programming
CSEB134 : BS/2008 7
User-defined Functions
A programmer can create his/her own function(s).
It is easier to plan and write our program if we divide it into several functions instead of writing a long piece of code inside the main function.
A function is reusable and therefore prevents programmers from having to unnecessarily rewrite what we have written before.
Principles of Programming
CSEB134 : BS/2008 8
The Concept
#include <stdio.h>main() { …
printf(“This program draws a rectangle”);…
}
#include <stdio.h>void print_menu(void);main() { …
print_menu();…
} /* end main */
void print_menu(void) {
printf(“This program draws a rectangle”);
} /* end function */
Without Function
With Function
vs.
Principles of Programming
CSEB134 : BS/2008 9
User-defined Functions
In order to write and use our own function, we need to do these:
1. Function declarations Also called function prototype. Used to declare a
function.
2. Function calls Call the function whenever it needs to be used.
3. Function definitions Also called function implementation, which define the
function somewhere in the program.
Principles of Programming
CSEB134 : BS/2008 10
Example#include <stdio.h>void print_menu(void);
main() {
print_menu();print menu();
}
void print_menu(void) {
printf(“This program draws a rectangle”);} /* end function */
Function declaration.
Function call.
Function definition.
Principles of Programming
CSEB134 : BS/2008 11
Function Declarations/Prototype Consist of:
A function type. A function name. An optional list of parameter type enclosed in ().
Use commas to separate more than one parameter types. Use (void) or () if there is no parameter.
A terminating semicolon. Example:
void print_menu(void);int GetScore(void);void CalculateTotal(int);char Testing(char, char);
Principles of Programming
CSEB134 : BS/2008 12
Function Calls A function is called by the declared function
name. Requires:
Name of the function. A list of parameters, if any, enclosed in () A terminating semicolon.
Example:print_menu();print_menu(3);print_menu(3, answer);
Means NO parameter.
Principles of Programming
CSEB134 : BS/2008 13
Two Types of Function Calls Call by value
In this method, copy of actual parameter’s value is passed to the function. Any modification to the passed value inside the function will not affect the actual value.
In all the examples that we have seen so far, this is the method that has been used.
Call by reference In this method, the reference (memory address) of the
variable is passed to the function. Any modification passed done to the variable inside the function will affect the actual value.
To do this, we need to have knowledge about pointers and arrays, which will be discussed in the next chapter.
Principles of Programming
CSEB134 : BS/2008 14
Function Definitions
A function definition is where the actual code for the function is written. This code will determine what the function will do when it is called.
Consists of : A function type (return value data type). A function name. An optional list of formal parameters enclosed in
parentheses (function arguments) A compound statement ( function body)
Principles of Programming
CSEB134 : BS/2008 15
1. Receive no input parameter and return nothing,
2. Receive no input parameter but return a value,
3. Receive input parameter( one or more) and return nothing, OR
4. Receive input parameter( one or more) and return a value
A Function may…
Principles of Programming
CSEB134 : BS/2008 16
1.Receive no input parameter and return nothing: Example#include <stdio.h>
void print_menu(void);
main()
{
print_menu();
}
void print_menu(void)
{
printf(“This program draws a rectangle”);
} /* end function */
Function declaration.
Function call.
Function definition.
Principles of Programming
CSEB134 : BS/2008 17
2. Receive no input parameter and return a value: Example#include <stdio.h>int print_menu(void);main() {
int value; value = print_menu(); printf(“The return value is: %d”, value);}
int print_menu(void) {
printf(“This program draws a rectangle”);return 1;
} /* end function */
Function declaration.
Function call.
Function definition.
Principles of Programming
CSEB134 : BS/2008 18
3. Receive input parameter ( one or more) and return nothing: Example#include <stdio.h>void print_menu(int);main() {
print_menu(3);}
void print_menu(int x) {
printf(“This program draws %d rectangles”, x);} /* end function */
Function declaration.
Function call.
Function definition.
Principles of Programming
CSEB134 : BS/2008 19
4. Receive input parameter ( one or more) and return a value: Example#include <stdio.h>int print_menu(int);main() {
printf(“The value: %d\n”, print_menu(3));}
int print_menu(int x) {
printf(“This program draws %d rectangles\n\n”, x);return x;
} /* end function */
Function declaration.
Function call.
Function definition.
Principles of Programming
CSEB134 : BS/2008 20
Function with parameter/argument When a function calls another function to perform a
task, the calling function may also send data to the called function. After completing its task, the called function may pass data it has generated back to the calling function.
Two terms used: Formal parameter
Variables declared in the formal list of the function header (written in function prototype & function definition)
Actual parameter Constants, variables, or expression in a function call that
correspond to its formal parameter
Principles of Programming
CSEB134 : BS/2008 21
Example#include <stdio.h>void print_menu(int);main() {
print_menu(3);}
void print_menu(int x) {
printf(“This program draws %d rectangles”, x);} /* end function */
Formal parameter/argument
Actual parameter/argument
Principles of Programming
CSEB134 : BS/2008 22
#include <stdio.h>int print_menu(int);main() {
printf(“The value: %d\n”, print_menu(3));}
int print_menu(int x) {
printf(“This program draws %d rectangles\n\n”, x);return x;
} /* end function */
Formal parameter/argument
Actual parameter/argument
Principles of Programming
CSEB134 : BS/2008 23
Three important points concerning functions with parameters are: The number of actual parameters in a function
call must be the same as the number of formal parameters in the function definition.
A one-to-one correspondence must occur among the actual and formal parameters. The first actual parameter must correspond to the first formal parameter and the second to the second formal parameter, an so on.
The type of each actual parameter must be either the same as that of the corresponding formal parameter.
Principles of Programming
CSEB134 : BS/2008 24
Example : One Parameter#include <stdio.h>void print_menu(int);main() {
print_menu(3);}
void print_menu(int x) {
printf(“This program draws %d rectangles”, x);
} /* end function */
Function declaration.
Function call.
Function definition.
Principles of Programming
CSEB134 : BS/2008 25
Example: More than one Parameters#include <stdio.h>
void print_menu(int, char);
main()
{
char answer = ‘y’;
print_menu(3, answer);
}void print_menu(int x, char ans)
{
if (ans == ‘y’ || ans == ‘Y’)
printf(“This program draws %d rectangles”, x);
} /* end function */
Function declaration.
Function call.
Function definition.
Principles of Programming
CSEB134 : BS/2008 26
Example#include<stdio.h>void main( ) {
int first, second, temp=0;printf("Please enter the first number: ");scanf("%d", &first);
printf("Please enter the second number: ");scanf("%d", &second);
if(second>first) {temp=second;second=first;first=temp;
}printf("\n%d is bigger than %d. \n\n", first, second);
}
Maybe rewritten as:
Principles of Programming
CSEB134 : BS/2008 27
#include<stdio.h>void convert_number(int, int);void main( ) {
int first, second;printf("Please enter the first number: ");scanf("%d", &first);printf("Please enter the second number: ");scanf("%d", &second);
convert_number(first, second);}
void convert_number(int x, int y){
int temp=0;if(y > x) {
temp = y;y = x;x = temp;
}printf("\n%d is bigger than %d. \n\n", x, y);
}
Principles of Programming
CSEB134 : BS/2008 28
Example – To Return a Value#include<stdio.h>int convert_number(int, int);void main( ) {
int first, second, tmp;printf("Please enter 2 integer numbers: ");scanf("%d %d", &first, &second);
tmp = convert_number(first, second);printf("Value of temp : %d", tmp);
}int convert_number(int x, int y){
int temp=0;if(y > x) {
temp = y;y = x;x = temp;
}printf("\n%d is bigger than %d. \n\n", x, y);return temp;
}
Only one return value from each function and of the same data type.
Principles of Programming
CSEB134 : BS/2008 29
Declaration of Variables
Up until now, we have learnt to declare our variables within the braces of segments (or a function) including the main.
It is also possible to declare variables outside a function. These variables can be accessed by all functions throughout the program.
Principles of Programming
CSEB134 : BS/2008 30
Local and global variables
Local variables only exist within a function. After leaving the function, they are ‘destroyed’. When the function is called again, they will be created (reassigned).
Global variables can be accessed by any function within the program. While loading the program, memory locations are reserved for these variables and any function can access these variables for read and write (overwrite).
If there exist a local variable and a global variable with the same name, the compiler will refer to the local variable.
Principles of Programming
CSEB134 : BS/2008 31
Example#include <stdio.h>// Functions declarationint GetScore(void);void CalculateTotal(int);void PrintTotal(void);int total = 0;
void main(void) { int Score, count = 0; for (; count < 10; count++) {
// Functions call Score = GetScore();
CalculateTotal(Score); } PrintTotal();}
// Functions definitionint GetScore(void) { int temp; printf(“Enter the score: “); scanf(“%d”, temp); return temp;}
void CalculateTotal(int score) {total = total + score;}
void PrintTotal(void) { printf(“Total score is: %d\n”,
total);}
score – local formal parameter
Global variable
Local variable
Principles of Programming
CSEB134 : BS/2008 32
Example// To print integers from num down to 1.#include <stdio.h>void print_integers(int);void main (void){ int num; printf(“Enter an integer: “); scanf(“%d”, &num); print_integers(num);}void print_integers(int n){ if (n >= 1){ printf(“%d\n”, n); print_integers(n-1); } /* end if */} /* end function print_integers */
for (; num >= 1; num--) printf(“%d\n”, num);
Principles of Programming
CSEB134 : BS/2008 33
Summary
This chapter has introduced you to functions and discussed elements of user-defined functions.
Each function must be defined, declared, and called. You studied valued functions, which return a value
under their name, and learned to use the return statement.
We covered the concepts of global and local variables and simple recursion.
Principles of Programming
CSEB134 : BS/2008 34
Exercise
1. Write a function distance that calculates the distance between two points (x1,y1) and (x2,y2). All number and return values should be of type float.
2. Write a function multiply that accept 2 integers and returns the multiplication of those two integers.
3. Write a program that inputs a series of integers and passes them one at a time to function even, which uses the remainder operator to determine if an integer is even. The function should take an integer argument and return 1 if the integer is even and 0 otherwise.
Principles of Programming
CSEB134 : BS/2008 35
4. Write a program that accepts 3 floating point numbers then pass these numbers to a function called smallest that later return the smallest value of the three floating point numbers.
Principles of Programming
CSEB134 : BS/2008 36
5. Write a main program that calculates total of three scores and this calculation must be done in a separate function called total_score(). The main program should read three(3) scores and calls the function total_score(). Then the average of these three scores is calculated. If the average is > 40, then the status PASS is displayed. The sample output is as follows:
Please enter your name: NorashikinPlease enter the first score: 90.0Please enter the second score: 60.0Please enter the third score: 30.0Name : NorashikinTotal = 180.0Average = 60.0Status = Pass
Principles of Programming
CSEB134 : BS/2008 37
1. Rewrite the following program using a user-defined function.#include<stdio.h>main (){
int num;
printf("Enter an integer or 999:");scanf("%d",&num);do{
printf("Number is: %d\n",num);printf("Enter an integer or 999:");scanf("%d",&num);
} while (num != 999);/* end_do_while */
}
Principles of Programming
CSEB134 : BS/2008 38
2. Write program that calls another function, named message. Ask the users for their annual income in the main program. Pass the value of income from main program to the message function where this function will print a congratulatory message if the user makes more than RM50,000 a year or an encouragement message if the user makes less.