function and program structure prepared by mmd, edited by msy1

49
CHAPTER 1 FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY 1

Post on 21-Dec-2015

214 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

CHAPTER 1FUNCTION AND

PROGRAM STRUCTURE

Prepared by MMD, Edited by MSY 1

Page 2: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Introduction to top-down methodology Introduction to function Standard functions User defined functions

◦function prototype◦function definition◦Function call

Variable scope Storage classes Scope Rules

Prepared by MMD, Edited by MSY 2

Functions and Program Structure

Page 3: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

FunctionTop Down Approach

Function

Prepared by MMD, Edited by MSY 3

Page 4: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

When we want to design a very large program, it is not practical to write all the gory details from the beginning.

A more practical approach would be to first write down all the major steps that we need to do in the program.

After writing all the major steps, only then we start refining each of the major steps and write down the details.

Other name: Divide and conquer

Prepared by MMD, Edited by MSY 4

Top Down Design Methodology

Page 5: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Problem:A taxpayer can determine his/her federal income tax by using the tax tables if thetaxable income is less than or equal to RM50,000. However, if taxable incomeexceeds this amount, the taxpayer must use the tax rate schedule. Tax rateschedule depend on filling status, which can be single, married filling jointly,married filling separately and head of household. The following table summarizesthe tax rates for the year 2001.

Filling status Taxable Income

Over But not over Tax

1. Single 59,300 - 11,158 + 31% of amount over 49,300

2. Married (joint) 34,000 82,150 5,100 + 28% of amount over 34,000

82,150 - 18,582 +31% of amount over 82,510

3. Married (separate) 41,075 - 9,291 + 31% of amount over 41,075

4. Head of household 27,300 70,450 4,095 + 28% of amount over 27,300

70,450 - 16,177 + 31% of amount over 70,450

Prepared by MMD, Edited by MSY 5

Top Down Design: Example

Page 6: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Modules:1. entered_gross_income – to read and verify

the value typed by the user for income.2. entered_filling_status – reads and verifies

the value provided for the variable filling_status

3. computed_tax – computes the federal income tax using values for income and filling_status and returns it to be saved in the variable tax.

4. output_result – values for income, filling_status and tax are printed out on the screen.

Prepared by MMD, Edited by MSY 6

Top Down Design: Example

Page 7: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

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.

Prepared by MMD, Edited by MSY 7

Introduction to Functions

Page 8: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Prepared by MMD, Edited by MSY 8

Consider this example:

#include <stdio.h>int GetScore(void);void CalculateTotal(int);void PrintTotal(void);int total = 0;

void main(void) { int score, count = 0; for (; count < 10; count++) { score = GetScore(); CalculateTotal(score); } PrintTotal();}

File header

} Function prototypes

} Function calls

Page 9: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

The use of functions resembles a pseudocode. Therefore we can easily convert steps in a pseudocode into function calls.

Our code looks a lot neater and more readable by using functions.

Prepared by MMD, Edited by MSY 9

Cont…

Page 10: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Prepared by MMD, Edited by MSY 10

Standard Functions Standard functions are functions that have

been pre-defined by C and put into standard C libraries. ◦ Example: printf(), scanf(), pow(), ceil(), rand(), etc.

What we need to do to use them is to include the appropriate header files.◦ Example: #include <stdio.h>, #include <math.h>

What contained in the header files are the prototypes of the standard functions. The function definitions (the body of the functions) has been compiled and put into a standard C library which will be linked by the compiler during compilation

Page 11: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Prepared by MMD, Edited by MSY 11

Standard Library Header

Explanation

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

<locale.h> Contains function prototype and other information that enables a program to be modified for the current locale on which it is running. The notion of locale enables the computer system to handle different conventions for expressing data like dates, times, dollar amount and large number throughout the world.

Page 12: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Prepared by MMD, Edited by MSY 12

Standard Library Header

Explanation

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

<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

Page 13: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

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 us (programmers) from having to unnecessarily rewrite what we have written before.

In order to write and and use our own function, we need to do these:◦ create a function prototype◦ define the function somewhere in the program◦ call the function whenever it needs to be used

Prepared by MMD, Edited by MSY 13

User Defined Functions

Page 14: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

A function prototype will tell the compiler that there exist a function with this name defined somewhere in the program and therefore it can be used even though the function has not yet been defined at that point.

Function prototypes need to be written at the beginning of the program.

If the function receives some arguments (parameter), the variable names for the arguments are not needed. State only the data types.

Parameter names are sometimes included in function prototypes for documentation purpose. The compiler ignores these names.

Prepared by MMD, Edited by MSY 14

Function Prototype

Page 15: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Examples:◦ void Function1(void);◦ void Function2(int);◦ char Function3(char, int, int);

Function prototypes can also be put in a header file. Header files are files that have a .h extension.

The header file can then be included at the beginning of our program.

Prepared by MMD, Edited by MSY 15

Function Prototypes Cont…

Page 16: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

To include a user defined header file, type:◦ #include “header_file.h”

Notice that instead of using < > as in the case of standard header files, we need to use “ ”. This will tell the compiler to search for the header file in the same directory as the program file instead of searching it in the directory where the standard library header files are stored.

Prepared by MMD, Edited by MSY 16

Function Prototypes Cont…

Page 17: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

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 it’s specific task.

A function definition has this format: return_value FunctionName(function arguments) {

variable declarations; statements;

}

Prepared by MMD, Edited by MSY 17

Function Definitions

Page 18: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

The return value is a data that will be returned by the functions. There can be only one return value.

The function arguments is a list of data to be passed to the function. The number of arguments that can be passed is infinite.

In the example that we have seen earlier, 3 function prototypes has been declared. The following are their definitions:

Prepared by MMD, Edited by MSY 18

Function Definitions Cont…

Page 19: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Prepared by MMD, Edited by MSY 19

Function Definitions Cont…

int 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);}

If the function has a return value, it needs to have a return statement at the end. Make sure the data typeis the same.

Give a name to the argument(s) that are passed to the function.

Page 20: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

In the CalculateTotal() function, the function takes only one argument. In the case where a function takes more than one argument, each arguments need to be separated by a coma. Make sure the data type for each arguments is stated. For example:

void Calc(int a, int b, double c, char d) { statements;}

Prepared by MMD, Edited by MSY 20

Function Definitions Cont…

Page 21: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

If the data type is not stated, for example:void Calc(a, b, c, d) {

statement; }

Each of them (a, b, c, d) by default will be an int. But, for the sake of good programming style, please state the data type even though it is an int.

Use the keyword void if no arguments will be passed to or returned from the function (even though it is perfectly okay not to write anything).

Prepared by MMD, Edited by MSY 21

Function Definitions Cont…

Page 22: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

A function is called by typing the name of the function.

If the function requires some arguments to be passed along, then the arguments need to be listed in the bracket () according to the specified order. For example:

void Calc(int, double, char, int); void main(void) { int a, b; double c; char d; … Calc(a, c, d, b);}

Prepared by MMD, Edited by MSY 22

Function Call

Page 23: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

If the function returns a value, then the returned value need to be assigned to a variable so that it can be stored. For example:

int GetUserInput(void);

void main(void) {

int input; input = GetUserInput();}

However, it is perfectly okay (syntax wise) to just call the function without assigning it to any variable if we want to ignore the returned value.

Prepared by MMD, Edited by MSY 23

Function Call Cont…

Page 24: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

We can also call a function inside another function. For example:

printf(“User input is: %d”, GetUserInput());

Prepared by MMD, Edited by MSY 24

Function Call Cont…

Page 25: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

The calling function may also send data to the called function.

The called function may pass data that it has generated back to the calling function.

There are 3 ways functions can communicate data:◦ Through global variables◦ By returning a value under a function name◦ By using parameters

Prepared by MMD, Edited by MSY 25

Functions with Parameters

Page 26: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

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

Prepared by MMD, Edited by MSY 26

Functions with Parameters

Page 27: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Defining functions with parameters:type_specifier function_name(formal_parameter_list)

Formal parameters are variables declared in the formal parameter list of the function header. They are used to send values to the function, return values from it or both.

Calling functions with parameters◦ If the function has formal parameters, then its call must

have actual parameters.◦ Actual parameters (arguments) are constants, variables

or expressions in a function call that correspond to its formal parameters.

Prepared by MMD, Edited by MSY 27

Functions with Parameters Cont…

Page 28: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

C supports 2 types of formal parameters:◦ Value parameters which are used only to send values to

functions. Only the copy of variable’s value is passed to the

function. Any modification to the passed value inside the function will not affect the actual value

◦ Pointer parameters which are used to send values to and/or returning values from functions. 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, which will be discussed in the next topic

Prepared by MMD, Edited by MSY 28

Functions with Parameters Cont…

Page 29: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Used when invoking functions Call by value

◦ Copy of argument passed to function◦ Changes in function do not effect original◦ Use when function does not need to modify argument

Avoids accidental changes Call by reference

◦ Passes original argument◦ Changes in function effect original◦ Only used with trusted functions

For now, we focus on call by value

Prepared by MMD, Edited by MSY 29

Calling Functions: Call by Value and Call by Reference

Page 30: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

int function2(int, double, int);void main(){

int a, b, d; double b;. . .d = function2(a, b, c);. . .

}int function2(int x, double y, int z){

int w;. . .return w;

}

Prepared by MMD, Edited by MSY 30

1. Parameter passing by value

2. Parameter passing by reference will be discussed in next chapter

Page 31: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

A function may◦ Receive no input parameter and return nothing◦ Receive no input parameter but return a value◦ Receive input parameter(s) and return nothing ◦ Receive input parameters(s) and return a value

Prepared by MMD, Edited by MSY 31

Notes:

Page 32: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Three important points concerning functions with parameters are: (number, order and type)◦ 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 data type of each actual parameter must be the same as that of the corresponding formal parameter.

Prepared by MMD, Edited by MSY 32

Notes: Cont…

Page 33: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

#include <stdio.h>int calSum(int, int); /*function protototype*/

void main(void){

int sum, num1, num2;

printf(“Enter two numbers to calculate its sum:”);scanf(“%d%d”,&num1,&num2);

sum = calSum(num1,num2); /* function call */printf(“\n %d + %d = %d”, num1, num2, sum);

}

int calSum(int val1, int val2) /*function definition*/{

int sum;sum = val1 + val2;return sum;

}

Prepared by MMD, Edited by MSY 33

Formal / Actual parameters

Formal Parameters

Actual Parameters

Formal Parameters

Page 34: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Divide and conquer◦ Manageable program development

Software reusability◦ Use existing functions as building blocks for new

programs◦ Abstraction - hide internal details (library

functions) Avoids code repetition

Prepared by MMD, Edited by MSY 34

Benefits

Page 35: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Variable scope

Prepared by MMD, Edited by MSY 35

Page 36: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

The scope of a variable is the portion of the program in which the identifier can be referenced.

A local variable can only be referenced in the block in which it is declared (a block is indicated by curly bracers { } ).

A global variable can be referenced from any functions in the program.

Prepared by MMD, Edited by MSY 36

Variable Scope

Page 37: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

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.

Prepared by MMD, Edited by MSY 37

Local and Global Variables

Page 38: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Prepared by MMD, Edited by MSY 38

Local and Global Variables#include <stdio.h>void initialise(void);void getInputs(void);void calSum(void);

int sum, num1, num2;

void main(void){

/* initialise sum to 0 */ initialise( );

/* read num1 and num2 */getInputs( );

calSum( );

printf("Sum is %d\n",sum);

}

void initialise(void){

sum = 0;}

void getInputs(void){

printf("Enter num1 and num2:");scanf("%d%d",&num1,&num2);

}

void calSum(void){

sum = num1 + num2;}

Page 39: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

In the previous example, no variables are passed between functions.

Each function could have access to the global variables, hence having the right to read and write the value to it.

Even though the use of global variables can simplify the code writing process (promising usage), it could also be dangerous at the same time.

Since any function can have the right to overwrite the value in global variables, a function reading a value from a global variable can not be guaranteed about its validity.

Prepared by MMD, Edited by MSY 39

Global variable – example explained

Page 40: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Storage Classes

Prepared by MMD, Edited by MSY 40

Page 41: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Each identifier in a program has attributes such as storage class, storage duration, variable scope and linkage.

C provides 4 storage classes indicated by the storage class specifiers: auto, register, extern and static.

The 4 storage classes can be split into 2 storage durations:◦ automatic storage duration

auto and register◦ static storage duration

static and extern

Prepared by MMD, Edited by MSY 41

Storage Classes

Page 42: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Variables with automatic storage duration are created when the block in which they are declared is entered, exist when the block is active and destroyed when the block is exited.◦ The keyword auto explicitly declares variables of

automatic storage duration. It is rarely used because when we declare a local variable, by default it has class storage of type auto. “int a, b;” is the same as “auto int a, b;”

◦ Start from scratch – re-initialise the variables

Prepared by MMD, Edited by MSY 42

Storage Classes Cont…

Page 43: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

The keyword register is used to suggest to the compiler to keep the variable in one of the computer’s high speed hardware register. However, it is also rarely used since compilers nowadays are smart enough detect frequently used variables to be put in a register.

Prepared by MMD, Edited by MSY 43

Storage Classes Cont…

Page 44: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Identifiers with static storage duration exist from the point at which the program begin execution.

The static keyword is applied to a local variable so that the variable still exist even though the program has gone out of the function. As a result, whenever the program enters the function again, the value in the static variable still holds.◦ Continue where we left off – remember the last value

The keyword extern is used to make an identifier global. Global variables and function names are of storage class extern by default.

Prepared by MMD, Edited by MSY 44

Storage Classes Cont…

Page 45: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

#include <stdio.h>void auto_example(void);void static_example(void);

void main(void){

int i;

printf("Auto example:\n");

for (i=1; i<=3; i++)auto_example( );

printf(“\nStatic example:\n");

for (i=1; i<=3; i++)static_example( );

}

Prepared by MMD, Edited by MSY 45

Auto and Static - Examplevoid auto_example(void){

auto int num = 1;

printf(“ %d\n”,num);num = num + 2;

}

void static_example(void){

static int num = 1;

printf(“ %d\n”,num);num = num + 2;

}Output:

Auto example:111

Static example:135

Page 46: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Scope Rules

Prepared by MMD, Edited by MSY 46

Page 47: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

File scope ◦ Identifier defined outside function, known in all

functions◦ Global variables, function definitions, function

prototypes

Function scope ◦ Can only be referenced inside a function body◦ Only labels (start: case: , etc.)

Prepared by MMD, Edited by MSY 47

Scope Rules

Page 48: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

Block scope ◦ Identifier declared inside a block

Block scope begins at declaration, ends at right brace◦ Variables, function parameters (local variables of

function)◦ Outer blocks "hidden" from inner blocks if same

variable name

Function prototype scope ◦ Identifiers in parameter list◦ Names in function prototype optional, and can be

used anywhere

Prepared by MMD, Edited by MSY 48

Scope Rules

Page 49: FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

In this chapter, you have learnt:◦Standard vs User Define functions◦Function prototype, function definition

and function call◦Formal vs Actual parameters◦Local vs Global variables◦Auto vs Static storage class◦Scope Rules (File, Function, Block and

Function Prototype scope)

Prepared by MMD, Edited by MSY 49

SUMMARY