52
1 MT258 Computer Programming and Problem Solving Unit 4

1 MT258 Computer Programming and Problem Solving Unit 4

Embed Size (px)

Citation preview

Page 1: 1 MT258 Computer Programming and Problem Solving Unit 4

1

MT258

Computer Programming and

Problem Solving

Unit 4

Page 2: 1 MT258 Computer Programming and Problem Solving Unit 4

2

UNIT FourBreak-down and build-up

Page 3: 1 MT258 Computer Programming and Problem Solving Unit 4

3

Records

Record type definition• Record variable• field

• types of data

• field identifier

Page 4: 1 MT258 Computer Programming and Problem Solving Unit 4

4

Records Example :

• struct MemberType

• {

• Char Name[20];

• Char Address[80];

• Char Postcode[10];

• char Gender;

• int Age;

• };

• struct MemberType ABCRec;

• struct MemberType DEFRec;

Page 5: 1 MT258 Computer Programming and Problem Solving Unit 4

5

Records Example :

• struct MemberType

• {

• Char Name[20];

• Char Address[80];

• Char Postcode[10];

• char Gender;

• int Age;

• } ABCRec, DEFRec;

Page 6: 1 MT258 Computer Programming and Problem Solving Unit 4

6

Records for single structure Example :

• struct

• {

• Char Name[20];

• Char Address[80];

• Char Postcode[10];

• char Gender;

• int Age;

• }

• ABCRec, DEFRec;

Page 7: 1 MT258 Computer Programming and Problem Solving Unit 4

7

Records for typedef

Example :• typedef

• struct

• {

• int month;

• int day;

• int year;

• }

• date_t;

• date_t datestart;

• date_t dateend;

Page 8: 1 MT258 Computer Programming and Problem Solving Unit 4

8

Records

Operations :• whole records

• =

• = =

• fields• depends on the type of the field

Page 9: 1 MT258 Computer Programming and Problem Solving Unit 4

9

Records

Exercise• define a record

• record variable : record1, record2

• field : int for field 1, field 2

• char for field 3, field 4

• assign value to each field of record 1• assign record 1 to record 2• change the field 2 of record 2 to 10

Page 10: 1 MT258 Computer Programming and Problem Solving Unit 4

10

Records

Exercise (Answer)• struct recordtype

• {

• int field1;

• int field2;

• char field3;

• char field4;

• };

• struct recordtype record1;

• struct recordtype record2;

Page 11: 1 MT258 Computer Programming and Problem Solving Unit 4

11

Records

Exercise (Answer)• assign value to each field of record 1

• record1.field1 = 2;

• record1.field2 = 3;

• record1.field3 = ‘a’;

• record1.field3 = ‘b’;

• assign record 1 to record 2• record2 = record1;

• change the field 2 of record 2 to 10• record2.field2 = 10;

Page 12: 1 MT258 Computer Programming and Problem Solving Unit 4

12

Table

Array of records Example

• struct Recordabc• { • int a;• int b;• char c;• };• struct Recordabc abc[100];

Page 13: 1 MT258 Computer Programming and Problem Solving Unit 4

13

Function

Function is a pre-written program segment that performs some tasks.

Execution thread branches to another program segment

A function has a unique name. Usually, execution thread will return to caller

(except exit). Data can be passed to a function. The data are

known as function parameters or function arguments.

Data can be returned from a function. The value is called return value.

Page 14: 1 MT258 Computer Programming and Problem Solving Unit 4

14

Function

You need to know

• What the function does

• Function name

• Number & type of input parameters

• Type of output parameter You do not need to know

• How the function does

(Information hiding)

Page 15: 1 MT258 Computer Programming and Problem Solving Unit 4

15

Function Information about the function getchar

• Name• getchar

• Library/Header file• Stdio.h

• Prototype• int getchar(void) or • int getchar()

• Description• This function reads a character from the keyboa

rd (standard input stream).• Parameter

• None• Return value

• It returns the next character read in from the keyboard (standard input stream) or it returns EOF if the end of the file is reached.

Page 16: 1 MT258 Computer Programming and Problem Solving Unit 4

16

Function prototype

int functionIdentifier (parameter1, parameter2, parameter3, . . . . . . );

Function name

Parameters (Arguments)

Return value

Page 17: 1 MT258 Computer Programming and Problem Solving Unit 4

17

Standard Library functions

Please refer to page 16 to 27 in Unit 4.

The online reference can be located via the Help menu - Content - C Runtime Library Reference - Borland C++ Builder Library Category overview.

Page 18: 1 MT258 Computer Programming and Problem Solving Unit 4

18

Writing Function

Program structure where declared functions• function declarations (prototypes);• int main(int argc, char **argv)• {• main program including calls to declared • and library functions• return 0;• }• function definitions

Page 19: 1 MT258 Computer Programming and Problem Solving Unit 4

19

Writing Functions Example

• float abcsqr(float cde);

• int main(int argc, char **argv)

• {

• float aa;

• aa = 3;

• printf(“The number is %f\n”, abcsqr(aa));

• return 0;

• }

• float abcsqr(float cde)

• {

• codings ;

• } Void

• void abcsqr(float cde) - no output

• float abcsqr(void) - no input parameter is required

Page 20: 1 MT258 Computer Programming and Problem Solving Unit 4

20

Parameters

Value parameters• a value is passed from the calling program to

the function.• Parameter cannot be changed.

Reference parameters• A variable rather than a value is passed from

the calling program to the function.• Parameter may be changed.

Page 21: 1 MT258 Computer Programming and Problem Solving Unit 4

21

Value Parameters

Example• int abc(int aa, int bb)• {• int Temp;• Temp = aa + bb;• return Temp;• }

Page 22: 1 MT258 Computer Programming and Problem Solving Unit 4

22

Reference Parameters

Example• void abc(int &aa, int &bb)• {• int Temp;• Temp = 2;• aa = Temp;• bb = Temp;• }

Array must pass by reference.

Page 23: 1 MT258 Computer Programming and Problem Solving Unit 4

23

Reference Parameters

Example• int strcmp (char *s, char *t)• {• int i;• for (i=0; s[i] == t[i]; i++)• if (s[i] == ‘\0’)• return 0;• return s[i] - t[i];• }

Page 24: 1 MT258 Computer Programming and Problem Solving Unit 4

24

Activity

Find the errors and explain how to debug them.• The following function returns the square of an

integer.• void square (int n, int result)• {• result = n * n• }

Page 25: 1 MT258 Computer Programming and Problem Solving Unit 4

25

Activity

Answer :• The following function returns the square of an integer.

• int square (int n)

• { int result;

• result = n * n ;

• return result ;

• }

Page 26: 1 MT258 Computer Programming and Problem Solving Unit 4

26

Local / Global Variable

type1 identifier1;type2 function2 (parameter21, parameter22);void main(){ type3 identifier3; type4 function4 (parameter41, parameter42); . . . .} type2 function2 (parameter21, parameter22);{ type5 identifier5;}

Global Variables

Local Variables)

Page 27: 1 MT258 Computer Programming and Problem Solving Unit 4

27

Local / Global Variable

Local variable• within the defining function• in one function is unrelated with local variable

of other function Global variable

• begins from the place declared• extends to the end of the program

Parameter variable• local variable• Initialized with parameter passing during

function call

Page 28: 1 MT258 Computer Programming and Problem Solving Unit 4

28

Return Value

Only one piece of data can be returned as the return value of the function

Page 29: 1 MT258 Computer Programming and Problem Solving Unit 4

29

Return Value

Use return valueeg

int inToFtIn ( int totalIn)

{

return totalIn / 12;

}

void main( )

{

int nearestFeet = inToFtIn (70);

}

Page 30: 1 MT258 Computer Programming and Problem Solving Unit 4

30

Return Value

To return more than one data• Use struct (record) type as return type• Use global variables• Use pointer (address) type parameters

Page 31: 1 MT258 Computer Programming and Problem Solving Unit 4

31

Return Value Use struct (record) type as return type

struct length{ int feet; int inches; };

struct length inToFtIn ( int totalIn) { struct length result; result.feet = totalIn / 12; result.inch = totalIn % 12; return result; } void main( ) { struct length result = inToFtIn(70); int resultFeet = result.feet; int resultInch = result.inch; }

Page 32: 1 MT258 Computer Programming and Problem Solving Unit 4

32

Return Value

Use global variable

int feet;

int inches;

void inToFtIn ( int totalIn){ feet = totalIn / 12; inch = totalIn % 12; return; } void main( ) { inToFtIn (70); resultFeet = feet; resultInch = inch; }

Page 33: 1 MT258 Computer Programming and Problem Solving Unit 4

33

Return Value Use pointer type parameters

void inToFtIn ( int totalIn, int * feet, int * inch) { * feet = totalIn / 12; * inch = totalIn % 12; return; } void main( ) { int tempFeet, tempInch; inToFtIn (70, &tempFeet, & tempInch); iut resultFeet = tempFeet; int resultInch = tempInch; }

Page 34: 1 MT258 Computer Programming and Problem Solving Unit 4

34

Recursion

Definition of recursion• Recursion is the name for the case when a

subprogram invokes itself or invokes a series of other subprograms that eventually invokes the first subprogram again.

Page 35: 1 MT258 Computer Programming and Problem Solving Unit 4

35

Overview of recursion Direct recursion

• eg Function A• int A(…..)

• { .

• .

• A(….);

• .

• }

Page 36: 1 MT258 Computer Programming and Problem Solving Unit 4

36

Overview of recursion Indirect recursion

• eg Function A• int B(…..)

• { .

• C(….);

• .

• }

• int C(…)

• { .

• B(….);

• .

• }

Page 37: 1 MT258 Computer Programming and Problem Solving Unit 4

37

Divide and conquer approach

It is a technique that relies on the idea of dividing a problem into smaller but similar functions that are easier to handle.

Eg. 4! = 4 x 3!

Page 38: 1 MT258 Computer Programming and Problem Solving Unit 4

38

Recursive process

A smallest, base case that is processed without recursion.

A general method that reduces a particular case to one or more of the smaller cases, thereby making progress toward eventually reducing the problem all the way to the base case.

Eg. n! = 1 if n = 0 n x (n-1)! if n > 0

Page 39: 1 MT258 Computer Programming and Problem Solving Unit 4

39

Activity

Write a function of calculating factorial• int Factorial (int n)• {• if (n==0)• return 1;• else• return n*Factorial(n-1);• }

Page 40: 1 MT258 Computer Programming and Problem Solving Unit 4

40

Activity Write a complete program to calculate factorial.

• #include <stdio.h>

• int Factorial(int);

• int Factorial (int n)

• {

• if (n==0)

• return 1;

• else

• return n*Factorial(n-1);

• }

• int main(void)

• {

• int j;

• printf(“Input n for n! : “);

• scanf(“%d”,&j);

• printf(“\nFactorial(%d) = %d\n”, j,Factorial(j));

• return 0;

• }

Page 41: 1 MT258 Computer Programming and Problem Solving Unit 4

41

Problems with a recursive solution There are one or more base cases of the

problem. A base case is a straightforward solution that can be obtained directly, without using further recursion.

The other cases can be redefined as problems that are closer to the base case.

By applying the redefinition process every time the recursive function is called, the problem is eventually reduced entirely to a simpler one that is relatively easier to solve. Eventually, the problem is reduced to a base case.

Page 42: 1 MT258 Computer Programming and Problem Solving Unit 4

42

Basic rules of recursion

Base cases. You must always have some base case(s) that can be solved without recursion.

Making progress. For cases that are to be solved recursively, the recursive call must always be to a case that makes progress toward a base case.

Page 43: 1 MT258 Computer Programming and Problem Solving Unit 4

43

Activity

Write down the base case and the other cases for the problem of multiplying 4 by 6, but using only the addition.• Base case :

• result = m if n = 1

• Other case :• result = m + multiply(m, n-1)

Page 44: 1 MT258 Computer Programming and Problem Solving Unit 4

44

Disadvantage of recursion

Recursion repeatedly invokes the mechanism, and consequently the overhead, of the functions call. It can be expensive in both processor time and memory space.

Each recursive call causes another copy of the function to be created, which can consume considerable memory.

Page 45: 1 MT258 Computer Programming and Problem Solving Unit 4

45

Activity If we are to write a function to compute f(n) where

f(n) is defined as:• If we are to write a function to compute f(n) where f(n) is defined

as:

• f(n) = 2 if n=1,

• f(n) = n * f(n-1) + 3 if n > 1

• for n >= 1

What is wrong with the following function:• int fun(int n)

• {

• if (n ==1) return 2;

• else (n* fun(n) +3);

• }

Page 46: 1 MT258 Computer Programming and Problem Solving Unit 4

46

Activity (Answer)

The value n is not decremented in the recursive invocation.

Page 47: 1 MT258 Computer Programming and Problem Solving Unit 4

47

Activity

Find out the purpose of the following recursive function:

• int xxx(int a, int b)• {• return (b == 1 ? a : xxx(a, b-1) + a);

• }

Give a suitable function name for xxx.

Modify this recursive function to handle for the cases that either a, b or both are zero.

Page 48: 1 MT258 Computer Programming and Problem Solving Unit 4

48

Activity (Answer)

The xxx function is to compute the product of two positive integers in terms of addition through the recursion. Therefore, xxx can be renamed as multiply.

• int multiply (int a, int b)• {• if (a == 0 || b == 0) return 0;• else return (b == 1 ? a : multiply(a, b-1)

+ a);• }

Page 49: 1 MT258 Computer Programming and Problem Solving Unit 4

49

Activity

Consider the following function

• f(1) = 1

• f(2) = 3

• f(n) = f(n-1) * f(n-2) when n > 2

• for all n > 0. What are the stopping conditions? Write a recursive function that returns the value of f(n)

for any n > 0.

Page 50: 1 MT258 Computer Programming and Problem Solving Unit 4

50

Activity (Answer)

when n = 1 and n = 2

int fun(int n) { if (n == 1) return (1); else if (n == 2) return (3); else return( fun(n-1) * fun(n-2)); }

Page 51: 1 MT258 Computer Programming and Problem Solving Unit 4

51

Modular Program Design

Dividing a problem into smaller problems (tasks)• Divide-and-conqure (Top-down approach)

Producing a task list• Only address which tasks are• Not include how to implement the tasks

Structural diagram• Refine task on each level (step-wise refinem

ent)

Page 52: 1 MT258 Computer Programming and Problem Solving Unit 4

52

Program Design

Use module approach• (module, sub-routine, sub-program, component,

function)

Module should be• Manageable size

• One specific task (high cohesion)

• Independent of other modules (low coupling)

Specify for each module• Data-in

• Data-out