ch4 functions

41
Chapter 4: Functions Introduction to Function

Upload: hattori-sidek

Post on 22-Nov-2014

1.646 views

Category:

Education


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Ch4 functions

Chapter 4: Functions

Introduction to Function

Page 2: Ch4 functions

Objectives

• To construct programs modularly from functions.

• To use common math functions available in the C Standard Library.

• To create functions with multiple parameters.

• The mechanisms for passing information between functions and returning results.

• How the function call/return mechanism is supported by the function call stack and activation records.

• To write and use recursive functions.

Page 3: Ch4 functions

Intro

• Divide and conquer.

• Use for various individual tasks.

• Functions enable grouping of commonly used code into a reusable and compact unit.

• In this chapter we will see how functions are defined and how they are

accessed from various places within a C program.

Overview of function, and a portion of the C Standard Library functions.

learn how to declare a function, and the manner in which information is passed to a function.

Page 4: Ch4 functions

Intro

• Advantages of using functions avoids the need for redundant (repeated)

programming of the same instructions. easier to write and easier to debug. logical structure is more apparent than

programs which lack this type of structure, especially true of lengthy, complicated programs.

avoids repetitive programming between programs

Page 5: Ch4 functions

Function Overview

• Every C program consists of one or more functions. One of these functions must be called main.

• A function will carry out its intended action whenever it is accessed or called from some other portion of the program.

• The same function can be accessed from several different places within a program.

• Once the function has carried out its intended action, control will be returned to the point from which the function was accessed.

Page 6: Ch4 functions

Function Overview

• Two type of functionsLibrary functions

• used to carry out a number of commonly used operations such as printf(…), getchar(), and putchar().

User/Programmer-defined functions• used to define their own functions for carrying

out various individual tasks.

• Information is passed to the function via special identifiers called arguments (also called parameters), and returned via the return statement.

Page 7: Ch4 functions

Library Functions

• 4 categories: Library functions that carry out standard I/O

operations (e.g., read and write characters, and numbers, etc.).

Functions that perform operations on characters (e.g., convert from lower- to uppercase, test for end of file, etc.).

Functions that perform operations on strings (e.g., copy a strings, compare strings, concatenate strings, etc.).

Functions that carry out various mathematical calculations (e.g. evaluate trigonometric, logarithmic and exponential functions,, etc.).

Page 8: Ch4 functions

Library Functions

• 3 types of library functions: return a data item to their access point. indicate whether a condition is true or false by

returning a 1 or a 0, carry out specific operations on data items but

do not return anything.

Page 9: Ch4 functions

Library Functions: Standard Library

Header Description<stdio.h> Functions for standard input

and output

<float.h> Floating point size limits

<limits.h> Contains integral size limits of system

<stdlib.h> Functions for converting numbers to text and text to numbers, memory allocation, random numbers, other utility functions

<math.h> Math library functions

<string.h> String processing functions

<stddef.h> Common definitions of types used by C

Page 10: Ch4 functions

Library Functions: Math.h Functions

Function Returns

sqrt(x) Square root

exp(x) Exponential function

log(x) Natural logarithm (base e)

log10(x) Logarithm (base 10)

fabs(x) Absolute value

pow(x,y) X raised to the power of y

sin(x) Trignometric sine (x in radians)

cos(x) Trignometric cosine (x in radians)

tan(x) Trignometric tangent (x in radians)

atan(x) Arctangent of x (returned value is in radians)

Page 11: Ch4 functions

Using Functions

• Include the header file for the required library using the preprocessor directive#include <libraryname.h>Note: no semi colon after this

• Variables defined in functions are local variables

• Functions have a list of parametersMeans of communicating information

between functions

• Functions can return values

• printf and scanf good examples of function calls

Page 12: Ch4 functions

User-defined Functions: Function Definition

• A function definition has two principal components: the first line (including the argument

declarations), and the body of the function.

• The first line of a function definition contains the type specification of the value returned by

the function followed by the function name, and (optionally) a set of arguments, separated by

commas and enclosed in parentheses.

Page 13: Ch4 functions

User-defined functions: Function Definition

• Format of a function definition

Return-value-type function-name(parameter-list){

declarations

statements}

A return value of type void indicates a function does notReturn a value.

Page 14: Ch4 functions

User-defined Functions: Function Definition

• Function Definition: argument/parameter The arguments are called formal argument

• because they represent the names of data items that are transferred into the function from the calling portion of the program.

There are also known as parameters or formal parameters.

The identifiers used as formal arguments are “local”

• because they are not recognized outside of the function.

• the names need not to be same as the names of the actual arguments in the calling portion of the program.

Page 15: Ch4 functions

User-defined Functions: Function Definition

• Function Definition: compound statement/body compound statement that defines the action to

be taken by the function. can contain expression statements, other

compound statements, control statements, and so on.

It should include one or more return statements, in order to return a value to the calling portion of the program.

Page 16: Ch4 functions

User-defined Functions: Function Definition

• Function definition: return Return control to point from which function called 3 Ways to return

• Function does not return a result (void) control is returned when function right brace } is reached.

• Execute the statement

– return;

• If the statement returns a value the following statement must be executed

– return expression;

Page 17: Ch4 functions

User-defined Functions: Example• Function prototype & definition

#include <stdio.h>int mod(int, int); /* Function Prototype */

main(){

printf("The mod is: %d ", mod(4,5));}/* Function Definition */int mod(int x, int y){

return x % y;}

Page 18: Ch4 functions

User-defined Functions: Example• Function with definition but without prototype

#include <stdio.h>int sum(int x, int y) /* Function Definition */{

return x+y;}

main(){

printf("The sum is: %d ", sum(4,5));}

Page 19: Ch4 functions

User-defined Functions: Function Prototype

• The function prototype Very important feature. Must be added to a C program before the main

function, if call that function before defining it. It tells the compiler what type of value the

function returns, number and types of parameters, and order in which these parameters are expected.

There is no need for a prototype if the function is called after its definition.

Page 20: Ch4 functions

User-defined Functions: Function Prototype

• Example function prototype

long int sum (int x, int y);

Where;x & y - Parameters

int - Parameter type

sum - Function name

long int - Function return type

Page 21: Ch4 functions

User-defined Functions: Function Calls

• A function can be accessed (i.e., called) by specifying its name, followed by a list of

arguments enclosed in parentheses and separated by commas.

• If the function call does not require any arguments empty pair of parentheses must follow the name

of the function.

• The arguments appearing in the function call are referred to as actual arguments, in contrast to the formal arguments that appear in the first line of the function definition.

Page 22: Ch4 functions

User-defined Functions: Function Calls

• In a normal function call there will be one actual argument for each formal

argument. may be expressed as constants, single

variables, or more complex expressions.

• If the function returns a value, the function access is written a statement; e.g.,

y = sum(x);

• if the function does not return anything, the function access appears by itself; e.g.,

view(a,b,c);

Page 23: Ch4 functions

User-defined Functions: Function Calls

• A function can be called by the main function other functions itself (recursion)

• In C, functions calls can be by value by reference

Page 24: Ch4 functions

User-defined Functions: Function Calls

• Call by value Copy of variable passed to function If that variable is modified within the function

then upon return from the function since only the copy has been modified, the actual variable is not modified

• Call by reference Pass the address of a variable (i.e. a pointer) to

a function The variable pointed to can be modified within

that function

Page 25: Ch4 functions

User-defined Functions: Function Calls

• Example Call By Value finval=FuncByValue(finval); The FuncByValue function

float FuncByValue(float fval){

return fval*fval;}

Page 26: Ch4 functions

User-defined Functions: Function Calls

• Example By Reference FuncByReference(&finref),

• Use & to pass the address of a variable to the function;

The FuncByReference function Value of the referenced variable passed to the

function is modified after returning from the function.

void FuncByReference(float *fvalptr){

*fvalptr = *fvalptr * *fvalptr;}

Page 27: Ch4 functions

User-defined Functions: Recursion

• A function calls itself repeatedly, until some specified condition has been satisfied.

• Each action is stated in terms of a previous result.

• Many iterative (i.e., repetitive) problems can be written in this form.

• In order to solve a problem recursively, two conditions must be satisfied. the problem must be written in recursive form. the problem statement must include a stopping

condition.

Page 28: Ch4 functions

User-defined Functions: Recursion

• Example Factorial

long int factorial (int n)/* calculate the factorial of n */{

if (n <= 1)return(1);

elsereturn(n * factorial(n-1));

}

Page 29: Ch4 functions

Additional Info: Header Files

• Standard libraries have header files containing function prototypes for all functions in that library

• Programmer can create custom header files Should end in .h e.g. myfunctionlib.h

• Programmer function prototypes declared using the pre processor directive #include “myfunctionlib.h”

Page 30: Ch4 functions

• Tuliskan satu fungsi takrifan pengguna yang diberi nama kuasa( ). Fungsi ini menerima input dua nombor integer iaitu x dan n, dan seterusnya mengira xn tanpa menggunakan fungsi pow(x,n). Kembalikan nilai tadi kepada fungsi yang memanggil

• Tuliskan satu cara untuk menggunakan/memanggil fungsi kuasa( ) di atas.

Page 31: Ch4 functions

• Tulis satu fungsi dalam bahasa C untuk luas_bulatan( ) yang menerima argumen berjenis float iaitu jejari kepada bulatan, kemudian mengira luas bulatan dan seterusnya mengembalikan luas bulatan tersebut kepada fungsi pemanggil.

• Tuliskan satu cara untuk menggunakan/memanggil fungsi luas_bulatan( ) di atas.

Page 32: Ch4 functions

• Based on the following function, write the function calls and prototype function for that function when x = 4.2 and y = 2.1. Then write the output.

void printresults( float x, float y)

{

float num1, num2;

num1 = x;

num2 = y;

printf(“Result of add the value = %.2f”, num1+num2);

printf(“Result of multiply the value = %.2f”, num1*num2);

• }

Page 33: Ch4 functions

Based on the following function:

float calculate_dividen(float saving)

{

float dividen;

dividen = saving * 0.16;

return (dividen);

}

• Write an example of function calls.

• What is the prototype of this function?

Page 34: Ch4 functions

• What is the first line syntax of function definition of the following statement?

A function called maximum accepts three integers (x, y, and z) and returns integer

A. maximum (int, int, int)

B. maximum (x, y, z)

C. int maximum (x, y, z)

D. int maximum (int x, int y, int z)

Page 35: Ch4 functions

What is the output for the following C program if the entered input is 108?

#include<stdio.h>

void final_value(int z)

{

int a = 5;

while ( z > 0)

{

a++;

z /=10;

}

printf(“ Final value of z = %d and a = %d\n”, z, a);

}

main( )

{

int x, y = 0;

printf(“\n Enter one integer value: “);

scanf (“%d”, &x);

final_value(x);

}

Page 36: Ch4 functions

Which one of the following is the correct function call for function xyz?

A. call xyz( );

B. void xyz(void);

C. xyz;

D. p = xyz( );

Page 37: Ch4 functions

• What is the correct function prototype for the following statement?

A function called Average accepts two float arguments (a and b) and print the average of a

and b.

A. float Average (a, b);B. void Average (a, b);C. void Average (float, float);D. float Average (float float);

Page 38: Ch4 functions

Contoh

Setempat

void main()

{

int i, j;

:

:

}

void fungsi()

{ :

:

}

Sejagat

int i, j;

void main(void)

{

:

:

}

void fungsi1()

{ :

:

}

Page 39: Ch4 functions

#include <stdio.h>

int i, j;

void fungsi1();

void main()

{

fungsi1();

printf("Main: i = %d, j = %d\n", i, j);

}

void fungsi1()

{

i = 1000;

j = 500;

printf(“Fungsi1: i = %d, j = %d\n", i, j);

}

Page 40: Ch4 functions

#include <stdio.h>

void fungsi1();

void main()

{

int i = 1000;

printf("Main: i = %d\n", i);

fungsi1();

printf("Main lagi: i = %d\n", i);

}

void fungsi1()

{

int i = 500;

printf("Fungsi1: i = %d\n", i);

}

Page 41: Ch4 functions

#include <stdio.h>

void fungsi1(int);

void main()

{

int i = 1000;

fungsi1(i);

printf("Main: i = %d\n", i);

}

void fungsi1(int j)

{

j = 5 * j;

printf("Fungsi1: j = %d\n", j);

}