You are on page 1of 38

Principles of Programming

Functions

CSEB134 : BS/2008 1
Principles of Programming

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
CSEB134 : BS/2008 2
Principles of Programming

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.

CSEB134 : BS/2008 3
Principles of Programming

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
CSEB134 : BS/2008 4
Principles of Programming

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.
CSEB134 : BS/2008 5
Principles of Programming

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.
CSEB134 : BS/2008 6
Principles of Programming

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.
CSEB134 : BS/2008 7
Principles of Programming

The Concept
With Function
#include <stdio.h>
vs. void print_menu(void);
main()
{ …
print_menu();
Without Function …
} /* end main */
#include <stdio.h>
main()
void print_menu(void)
{ …
{
printf(“This program
draws a rectangle”); printf(“This program
draws a rectangle”);

} /* end function */
}
CSEB134 : BS/2008 8
Principles of Programming

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.
CSEB134 : BS/2008 9
Principles of Programming

Example
#include <stdio.h>
void print_menu(void); Function declaration.

main()
{
print_menu();
Function call.
print menu();
}

void print_menu(void)
Function definition.
{
printf(“This program draws a rectangle”);
} /* end function */

CSEB134 : BS/2008 10
Principles of Programming

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);
CSEB134 : BS/2008 11
Principles of Programming

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: Means NO parameter.

print_menu();
print_menu(3);
print_menu(3, answer);
CSEB134 : BS/2008 12
Principles of Programming

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.
CSEB134 : BS/2008 13
Principles of Programming

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)
CSEB134 : BS/2008 14
Principles of Programming

A Function may…
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

CSEB134 : BS/2008 15
Principles of Programming
1.Receive no input parameter
and return nothing: Example
#include <stdio.h>
Function declaration.
void print_menu(void);
main()
{
print_menu(); Function call.
}

void print_menu(void) Function definition.


{
printf(“This program draws a rectangle”);
} /* end function */
CSEB134 : BS/2008 16
Principles of Programming
2. Receive no input parameter
and return a value: Example
#include <stdio.h>
int print_menu(void); Function declaration.
main()
{
int value; Function call.
value = print_menu();
printf(“The return value is: %d”, value);
}

int print_menu(void)
Function definition.
{
printf(“This program draws a rectangle”);
return 1;
} /* end function */

CSEB134 : BS/2008 17
Principles of Programming
3. Receive input parameter ( one or
more) and return nothing: Example
#include <stdio.h>
Function declaration.
void print_menu(int);
main()
{ Function call.
print_menu(3);
}

void print_menu(int x) Function definition.


{
printf(“This program draws %d rectangles”, x);
} /* end function */
CSEB134 : BS/2008 18
Principles of Programming
4. Receive input parameter ( one or
more) and return a value: Example
#include <stdio.h>
Function declaration.
int print_menu(int);
main()
Function call.
{
printf(“The value: %d\n”, print_menu(3));
}

int print_menu(int x) Function definition.


{
printf(“This program draws %d rectangles\n\n”, x);
return x;
} /* end function */
CSEB134 : BS/2008 19
Principles of Programming
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

CSEB134 : BS/2008 20
Principles of Programming

Example
#include <stdio.h>
Formal parameter/argument
void print_menu(int);
main()
{
print_menu(3); Actual parameter/argument
}

void print_menu(int x)
{
printf(“This program draws %d rectangles”, x);
} /* end function */
CSEB134 : BS/2008 21
Principles of Programming

#include <stdio.h>
Formal parameter/argument
int print_menu(int);
main()
{
printf(“The value: %d\n”, print_menu(3));
}
Actual parameter/argument
int print_menu(int x)
{
printf(“This program draws %d rectangles\n\n”, x);
return x;
} /* end function */
CSEB134 : BS/2008 22
Principles of Programming
 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.

CSEB134 : BS/2008 23
Principles of Programming

Example : One Parameter


#include <stdio.h>
Function declaration.
void print_menu(int);
main()
{
print_menu(3); Function call.
}

void print_menu(int x) Function definition.


{
printf(“This program draws %d rectangles”,
x);
} /* end function */

CSEB134 : BS/2008 24
Principles of Programming
Example: More than one
Parameters
#include <stdio.h>
Function declaration.
void print_menu(int, char);
main()
{
char answer = ‘y’; Function call.
print_menu(3, answer);
}
void print_menu(int x, char ans)
Function definition.
{
if (ans == ‘y’ || ans == ‘Y’)
printf(“This program draws %d rectangles”, x);
} /* end function */
CSEB134 : BS/2008 25
Principles of Programming

Example
#include<stdio.h>
void main( )
{
int first, second, temp=0;
printf("Please enter the first number: "); Maybe
scanf("%d", &first);
rewritten as:
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);
}

CSEB134 : BS/2008 26
Principles of Programming
#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;
}
CSEB134 : BS/2008 27
printf("\n%d is bigger than %d. \n\n", x, y);
}
Principles of Programming
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);
} Only one return value
int convert_number(int x, int y) from each function and
{
of the same data type.
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; CSEB134 : BS/2008 28

}
Principles of Programming

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.

CSEB134 : BS/2008 29
Principles of Programming

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.
CSEB134 : BS/2008 30
Principles of Programming

Example // Functions definition


int GetScore(void)
#include <stdio.h> {
// Functions declaration int temp;
int GetScore(void); printf(“Enter the score: “);
void CalculateTotal(int); scanf(“%d”, temp);
void PrintTotal(void); return temp;
int total = 0; } score – local formal parameter
void main(void) Local variable void CalculateTotal(int score)
{ {
int Score, count = 0; total = total + score;
for (; count < 10; count++) }
{
// Functions call void PrintTotal(void)
Score = GetScore(); {
printf(“Total score is: %d\n”,
CalculateTotal(Score); total);
} }
PrintTotal(); Global variable
}
CSEB134 : BS/2008 31
Principles of Programming

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);
for (; num >= 1; num--)
print_integers(num);
printf(“%d\n”, num);
}
void print_integers(int n){
if (n >= 1){
printf(“%d\n”, n);
print_integers(n-1);
} /* end if */
} /* end function print_integers */
CSEB134 : BS/2008 32
Principles of Programming

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.

CSEB134 : BS/2008 33
Principles of Programming

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.
CSEB134 : BS/2008 34
Principles of Programming

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.

CSEB134 : BS/2008 35
Principles of Programming

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: Norashikin


Please enter the first score: 90.0
Please enter the second score: 60.0
Please enter the third score: 30.0
Name : Norashikin
Total = 180.0
Average = 60.0
Status = Pass

CSEB134 : BS/2008 36
Principles of Programming

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 */
} CSEB134 : BS/2008 37
Principles of Programming

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.
CSEB134 : BS/2008 38

You might also like