unit 8

18
F1001 PROGRAMMING FUNDAMENTALS FUNCTION Concepts of Functions User-defined Functions 105 UNIT 8

Upload: rohassanie

Post on 22-May-2015

226 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: Unit 8

F1001 PROGRAMMING FUNDAMENTALS

FUNCTION

Concepts of Functions

User-defined Functions

105

UNIT

8

Page 2: Unit 8

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>

float kira_cal(int);

main(){

clrscr();int j;float luas_area1;float luas_area2;

luas_area1 = kira_cal(5);printf("Luas bulatan / Circle area : %.f\n", luas_area1);

printf("Masukkan nilai jejari / Enter radius : ");scanf("%d", &j);luas_area2 = kira_cal(j);

printf("Luas bulatan / Circle area : %.f\n", luas_area2);}

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

Variable argument

Function Prototype

Calling a Function

Called Function

Constant argument

Page 3: Unit 8

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

Function basics

A function definition has two principle components:

Example:

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.

Braces must enclose the body of each function, starting immediately after the closing parentheses of

the function name.

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)

107

main(){

}

head

body

Page 4: Unit 8

F1001 PROGRAMMING FUNDAMENTALS

User Defined Functions:

Defining User Defined Functions

Is a function that is created by the user.

Syntax:

Where:

FunctionName it is the function’s name

Similar rules for naming the variable will be used for

naming functions.

returnDataType data type of the item returned by the function.

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 :

Example :

2. Function that does not receive a value but returns a value.

108

ReturnDataType functionName(ParameterList){

/*Any C statements/}

OR

FunctionName(){

/*function body*/}

void message (void){

printf(“WELCOME”);

}

void message (){

printf(“WELCOME”);

}

Page 5: Unit 8

F1001 PROGRAMMING FUNDAMENTALS

Syntax :

Example :

3. Function that receives values but returns nothing.

Syntax :

Example :

4. Function that receives and returns values.

109

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;

}

ReturnDataType functionName( ){

/*function body*/return value;

}

void print (int age){

printf(“My age is %d years old”, age);}

FunctionName(parameterList){

/*function body*/}

Page 6: Unit 8

F1001 PROGRAMMING FUNDAMENTALS

Syntax :

Example :

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 :

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 :

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.

It allows the C compiler to check the syntax of function calls.

110

ReturnDataType functionName(ParameterList);

/*function prototype*/#include <stdio.h>

void message (); /*function prototype*/

main (){

/*main function body*/}

void message (){

/*function body*/}

int count (int a, int b){

int total;total = a + b;return total;

}

ReturnDataType functionName(parameterList){

/*Function body*/return value;

}

Page 7: Unit 8

F1001 PROGRAMMING FUNDAMENTALS

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 :

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:

We can also call function from another function.

Example :

111

/*Usage of functions without function prototype*/

#include <stdio.h>

void message (){

/*badan fungsi*/}

main (){

/*badan fungsi main*/}

#include <stdio.h>

void message (); /*function prototype*/

main (){

message (); /*calling function*/}

void message () /*called function*/{

/*function body*/}

Page 8: Unit 8

F1001 PROGRAMMING FUNDAMENTALS

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.

Passing by Value (by copy)

112

#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*/}

Function that sends one or more arguments (local

variables) to the receiving function

Function that receives the parameters from the calling function

VALUES:Local variables or constants

Calling FunctionSend : Argument

Called Function(Receiving Function)Receive : Parameter

Page 9: Unit 8

F1001 PROGRAMMING FUNDAMENTALS

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 :

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

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.

113

/*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);

}

Page 10: Unit 8

F1001 PROGRAMMING FUNDAMENTALS

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.

We declare the variables A and B.  Therefore in memory we have space to retain two pieces of information.

   

We take input from the keyboard.

When A and B are passed to the swap() function copies are made for x and y.            

             We then perform the statements in the body, swapping the copies.           

                        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.

114

#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() : %d\n", A); printf("The value of B before calling swap() : %d\n", B); swap(A, B); printf("The value of A after calling swap() : %d\n", A); printf("The value of B after calling swap() : %d\n", B); return 0;}

A B

A 2 B 3

A 2 B 3

x 2 y 3

A 2 B 3

x 3 y 2

Note that after the swap has occurred, the original values of A and B are retained.

Page 11: Unit 8

F1001 PROGRAMMING FUNDAMENTALS

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 :

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.

115

/*Penghantaran dengan alamat*/#include <stdio.h>

void change (int *);

void main (){

int local = 3;change (&local);

}

void change (int *p) {

printf (“The value that you send is %d”, *p);}

Must be declared with an asterisk

Output :

#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() : %d\n", A); printf("The value of B before calling swap() : %d\n", B); swap(&A, &B); printf("The value of A after calling swap() : %d\n", A); printf("The value of B after calling swap() : %d\n", B); return 0;}

Page 12: Unit 8

F1001 PROGRAMMING FUNDAMENTALS

 

 

           

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.

             We take input from the keyboard.

When A and B are passed to the swap() function x and y point to the same space in memory.                                                        We then perform the statements in the body, swapping the originals.

After we return from the function, we are left with:

Return Values

Returns data from a receiving function (called function) to its calling function by putting the return

value after the return statement.

116

return value;

A B

A 2 B 3

A 2 B 3

yx

A 3 B 2

yx

A 3 B 2The result is that the values are swapped appropriately.

Page 13: Unit 8

F1001 PROGRAMMING FUNDAMENTALS

Syntax :

Example :

117

Calling Called

Returns Value

#include <stdio.h>

float cal (int, int);

void main(){

int s, t;float a;

printf(“Please Enter Two Number ”);scanf(“%d %d”, &s, &t);a = cal(s, t);printf(“Average of two numbers is : %.2f”, a);

}

float cal (int num1, int num2){

float avg;

avg = (float)(num1 + num2) / 2;return avg;

}

Return Data Type

Returns a value

Value which is returned from

the called function is

assigned to a

Output :

NOTES

1. Do not return global variables because their values are already known through the code.

Even though a function can receive more than one parameter, it can return one single value to the

calling function. If you want to return more than a value, you must pass the value by address.

Example : #include <stdio.h>

char* change ();

void main (){

char *a;

a = change ();printf("The word is : %s ", a);

}

char* change (){

char *word = "Love";

return (word);}

Return Data Type

Return value is assigned to a

Returns the value“Love”

Output :

Page 14: Unit 8

F1001 PROGRAMMING FUNDAMENTALS

118