21
Chapter 4 Chapter 4 Functions and Program Functions and Program Structure Structure Ku-Yaw Chang Ku-Yaw Chang [email protected] [email protected] Assistant Professor, Department of Assistant Professor, Department of Computer Science and Information Engineering Computer Science and Information Engineering Da-Yeh University Da-Yeh University

Chapter 4 Functions and Program Structure Ku-Yaw Chang [email protected] Assistant Professor, Department of Computer Science and Information Engineering

Embed Size (px)

Citation preview

Page 1: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

Chapter 4Chapter 4

Functions and Program StructureFunctions and Program Structure

Ku-Yaw ChangKu-Yaw [email protected]@mail.dyu.edu.tw

Assistant Professor, Department of Assistant Professor, Department of Computer Science and Information EngineeringComputer Science and Information Engineering

Da-Yeh UniversityDa-Yeh University

Page 2: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

22Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.1 Basics of Functions4.1 Basics of Functions

A programA program Print each line of its input that contains a particular Print each line of its input that contains a particular

“pattern” or string of characters“pattern” or string of characters

For exampleFor example Search for the pattern of “ould” in the set of linesSearch for the pattern of “ould” in the set of lines

Page 3: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

33Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.1 Basics of Functions4.1 Basics of Functions

Ah Love! Could you and I with Fate conspireAh Love! Could you and I with Fate conspireTo grasp this sorry Scheme of Things entire,To grasp this sorry Scheme of Things entire,Would not we shatter it to bits – and thenWould not we shatter it to bits – and thenRe-mould it nearer to the Heart’s Desire!Re-mould it nearer to the Heart’s Desire!

Ah Love! CAh Love! Couldould you and I with Fate conspire you and I with Fate conspireWWouldould not we shatter it to bits – and then not we shatter it to bits – and thenRe-mRe-mouldould it nearer to the Heart’s Desire! it nearer to the Heart’s Desire!

Page 4: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

44Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.1 Basics of Functions4.1 Basics of Functions

The jobs falls into three pieces:The jobs falls into three pieces:

while (there’s another line)while (there’s another line)

if (the line contains the pattern)if (the line contains the pattern)

print itprint it

Page 5: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

55Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.1 Basics of Functions4.1 Basics of Functions#include <stdio.h>#include <stdio.h>#define MAXLINE 1000 #define MAXLINE 1000 int getline(char line[], int max);int getline(char line[], int max);int strindex(char source[], char searchfor[]);int strindex(char source[], char searchfor[]);char pattern[] = “ould”;char pattern[] = “ould”;

main() {main() {char line[MAXLINE];char line[MAXLINE];int found = 0;int found = 0;

while (while (getline(line, MAXLINE)getline(line, MAXLINE) > 0) > 0)if (if (strindex(line, pattern)strindex(line, pattern) >= 0) { >= 0) {

printf(“%s”, line);printf(“%s”, line);found ++;found ++;

}}return found;return found;

}}

Page 6: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

66Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.1 Basics of Functions4.1 Basics of Functions

Each function has the formEach function has the formreturn-type function-name (argument declarations)return-type function-name (argument declarations)

{{

declarations and statementsdeclarations and statements

}}

Various parts may be absentVarious parts may be absent A minimal function isA minimal function is

dummy() {}dummy() {} If the return type is omitted, int is assumed.If the return type is omitted, int is assumed.

The calling function is free to ignore the returned value.The calling function is free to ignore the returned value.

Page 7: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

77Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

Exercise 4-1Exercise 4-1

Write a function integerPower( base, exponent ) that Write a function integerPower( base, exponent ) that returns the value of basereturns the value of baseexponentexponent..

For example, integerPower(3, 4) = 3 * 3 * 3 * 3. Assume For example, integerPower(3, 4) = 3 * 3 * 3 * 3. Assume that exponent is a positive, nonzero integer, and base is that exponent is a positive, nonzero integer, and base is an integer. Function integerPower should use for to an integer. Function integerPower should use for to control the calculation. Do not use any math library control the calculation. Do not use any math library functions.functions.

Page 8: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

88Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

Exercise 4-2Exercise 4-2

Write a function multiple that determines for a pair of Write a function multiple that determines for a pair of integers whether the second integer is a multiple of the integers whether the second integer is a multiple of the first. The function should take two integer arguments and first. The function should take two integer arguments and return 1(true) if the second is a multiple of the first, and return 1(true) if the second is a multiple of the first, and 0(false) otherwise. Use this function in a program that 0(false) otherwise. Use this function in a program that inputs a series of pairs of integers.inputs a series of pairs of integers.

Page 9: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

99Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

Exercise 4-3Exercise 4-3

Write the function strrindex(s, t), which returns the Write the function strrindex(s, t), which returns the position of the position of the rightmostrightmost occurrence of t in s, or -1 if occurrence of t in s, or -1 if there is none.there is none.

Page 10: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

1010Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.2 Functions Returning4.2 Functions ReturningNon-integersNon-integers

Many numerical functions return doubleMany numerical functions return double sqrtsqrt sinsin coscos

Other specialized functions return other typesOther specialized functions return other types

A function takes no argumentsA function takes no arguments Use voidUse void

double atof(void);double atof(void);

Page 11: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

1111Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.5 Header Files4.5 Header Files

A program is usually divided into several source A program is usually divided into several source filesfiles implementation file (*.c / *.cpp )implementation file (*.c / *.cpp )

codescodes header file (*.h / *.hpp)header file (*.h / *.hpp)

Definitions and declarationsDefinitions and declarations

Page 12: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

1212Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4-10 Recursion4-10 Recursion

RecursionRecursion A function may call itself either directly or indirectlyA function may call itself either directly or indirectly

Recursive functionRecursive function Base caseBase case

Simply return a resultSimply return a result Recursive callRecursive call or or recursion steprecursion step

Call a fresh copy of itself to go to work on the smaller Call a fresh copy of itself to go to work on the smaller problemproblem

Page 13: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

1313Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4-10 Recursion4-10 Recursion

ExampleExample Factorial of a nonnegative integer nFactorial of a nonnegative integer n

n ! = n * (n-1) * (n-2) * (n-3) * ….. * 1n ! = n * (n-1) * (n-2) * (n-3) * ….. * 1 Factorial(n)Factorial(n)

Base caseBase case Factorial(0) = 1Factorial(0) = 1 Factorial(1) = 1Factorial(1) = 1

Recursion stepRecursion step Factorial(n) = n * Factorial(n-1)Factorial(n) = n * Factorial(n-1)

Page 14: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

1414Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.11 The C Preprocessor4.11 The C Preprocessor

Two most frequently used featuresTwo most frequently used features #include#include

To include the contents of a file during compilationTo include the contents of a file during compilation #define#define

To replace a token by an arbitrary sequence of To replace a token by an arbitrary sequence of characterscharacters

Page 15: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

1515Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.11.1 File Inclusion4.11.1 File Inclusion

Make it easy to handle collections of #defines Make it easy to handle collections of #defines and declarationsand declarations #include “#include “filenamefilename””

Searching for the file begins where the source program was Searching for the file begins where the source program was foundfound

If not found there, searching follows an implementation-If not found there, searching follows an implementation-defined rule to find the filedefined rule to find the file

#include <#include <filenamefilename>>Searching for the file follows an implementation-defined ruleSearching for the file follows an implementation-defined rule

Page 16: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

1616Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.11.1 File Inclusion4.11.1 File Inclusion

An include file may itself contain #include lines.An include file may itself contain #include lines. Usually with *.h file extensionUsually with *.h file extension

#include#include Tie the declaration together for a large programTie the declaration together for a large program

The same definitions and variable declarationsThe same definitions and variable declarations An include file is changed, all files that depend on it An include file is changed, all files that depend on it

must be recompiledmust be recompiled

Page 17: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

1717Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.11.2 Macro Substitution4.11.2 Macro Substitution

A macro substitutionA macro substitution#define #define namename replacement_textreplacement_text Subsequent occurrences of the token Subsequent occurrences of the token namename will be will be

replaced by the replaced by the replacement_textreplacement_text

ScopeScope From its definition to the end of the source file being From its definition to the end of the source file being

compiledcompiled

Only for tokensOnly for tokens Not take place within quoted stringsNot take place within quoted strings

Page 18: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

1818Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.11.2 Macro Substitution4.11.2 Macro Substitution

ExampleExample #define forever for (;;) /* infinite loop */#define forever for (;;) /* infinite loop */ #define max(A, B) ((A) > (B) ? (A) : (B))#define max(A, B) ((A) > (B) ? (A) : (B))

Look like a function callLook like a function callExpand into in-line codeExpand into in-line code

x = max(p+q, r+s)x = max(p+q, r+s)is replaced by the lineis replaced by the linex = ( (p+q) > (r+s) ? (p+q) : (r+s) )x = ( (p+q) > (r+s) ? (p+q) : (r+s) )

Pitfall exists (optional assignment)Pitfall exists (optional assignment) #define square(x) x * x#define square(x) x * x

Consider square(z+1)Consider square(z+1)

Page 19: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

1919Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.11.3 Conditional Inclusion4.11.3 Conditional Inclusion

To make sure that the contents of a file hdr.h are To make sure that the contents of a file hdr.h are included only once:included only once:

#if !defined(HDR) or #ifndef HDR#if !defined(HDR) or #ifndef HDR

#define HDR#define HDR

/* contents of hdr.h go here *//* contents of hdr.h go here */

#endif#endif

#pragma once#pragma once

Page 20: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

2020Ku-Yaw ChangKu-Yaw Chang Functions and Program StructureFunctions and Program Structure

4.11.3 Conditional Inclusion4.11.3 Conditional Inclusion

To test the name SYSTEM to decide which version of a To test the name SYSTEM to decide which version of a header to include:header to include:

#if SYSTEM == SYSV#if SYSTEM == SYSV

#define HDR “sysv.h”#define HDR “sysv.h”

#elif SYSTEM == BSD#elif SYSTEM == BSD

#define HDR “bsd.h”#define HDR “bsd.h”

#elif SYSTEM == MSDOS#elif SYSTEM == MSDOS

#define HDR “msdos.h”#define HDR “msdos.h”

#else#else

#define HDR “default.h”#define HDR “default.h”

#endif#endif

#include HDR#include HDR

Page 21: Chapter 4 Functions and Program Structure Ku-Yaw Chang canseco@mail.dyu.edu.tw Assistant Professor, Department of Computer Science and Information Engineering

To be continued…To be continued…