Download File

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
5.13
Recursion
• Recursive functions
– Functions that call themselves
– Can only solve a base case
– Divide a problem up into
• What it can do
• What it cannot do
– What it cannot do resembles original problem
– The function launches a new copy of itself (recursion step) to
solve what it cannot do
– Eventually base case gets solved
• Gets plugged in, works its way up and solves whole problem
5.13
Recursion
• Example: factorials
– 5! = 5 * 4 * 3 * 2 * 1
– Notice that
• 5! = 5 * 4!
• 4! = 4 * 3! ...
– Can compute factorials recursively
– Solve base case (1! = 0! = 1) then plug in
• 2! = 2 * 1! = 2 * 1 = 2;
• 3! = 3 * 2! = 3 * 2 = 6;
5.13
5!
Recursion
5!
5 * 4!
4 * 3!
3 * 2!
2 * 1!
1
( a ) Se q u en c e o f re c ursive c a lls.
Fin a l va lue = 120
5! = 5 * 24 = 120 is re turn ed
5 * 4!
4! = 4 * 6 = 24 is re turne d
4 * 3!
3! = 3 * 2 = 6 is re tu rn e d
3 * 2!
2! = 2 * 1 = 2 is re turne d
2 * 1!
1 re turne d
1
( b ) Va lue s re turne d fro m e a c h re cu rsive c a ll.
1
/* Fig. 5.14: fig05_14.c
Recursive factorial function */
2
3
#include <stdio.h>
4
5
long factorial( long number ); /* function prototype */
6
7
/* function main begins program execution */
8
int main()
9
{
10
int i; /* counter */
11
12
13
14
15
16
/* loop 10 times.
During each iteration, calculate
fig05_14.c (Part 1 of 2)
factorial( i ) and display result */
for ( i = 1; i <= 10; i++ ) {
printf( "%2d! = %ld\n", i, factorial( i ) );
} /* end for */
17
18
return 0; /* indicates successful termination */
19
20 } /* end main */
21
22 /* recursive definition of function factorial */
23 long factorial( long number )
24 {
25
/* base case */
26
if ( number <= 1 ) {
27
return 1;
28
} /* end if */
29
else { /* recursive step */
return ( number * factorial( number - 1 ) );
30
} /* end else */
31
32
33 } /* end function factorial */
1!
2!
3!
4!
5!
6!
7!
8!
9!
10!
=
=
=
=
=
=
=
=
=
=
1
2
6
24
120
720
5040
40320
362880
3628800
fig05_14.c (Part 2 of 2)
5.14Example Using Recursion: The
Fibonacci Series
• Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
– Each number is the sum of the previous two
– Can be solved recursively:
• fib( n ) = fib( n - 1 ) + fib( n – 2 )
– Code for the
fibonacci
function
long fibonacci( long n )
{
if (n == 0 || n == 1) // base case
return n;
else
return fibonacci( n - 1) +
fibonacci( n – 2 );
}
5.14Example Using Recursion: The
Fibonacci Series
• Set of recursive callsf(to
3 )function fibonacci
return
return
f( 1 )
return 1
f( 2 )
+
f( 0 )
return 0
+
f( 1 )
return 1
1
/* Fig. 5.15: fig05_15.c
Recursive fibonacci function */
2
3
#include <stdio.h>
4
5
long fibonacci( long n ); /* function prototype */
6
7
/* function main begins program execution */
8
int main()
9
{
10
long result; /* fibonacci value */
11
long number; /* number input by user */
12
13
/* obtain integer from user */
14
printf( "Enter an integer: " );
15
scanf( "%ld", &number );
fig05_15.c (Part 1 of 2)
16
17
/* calculate fibonacci value for number input by user */
18
result = fibonacci( number );
19
20
/* display result */
21
printf( "Fibonacci( %ld ) = %ld\n", number, result );
22
23
return 0; /* indicates successful termination */
24
25 } /* end main */
26
27 /* Recursive definition of function fibonacci */
28 long fibonacci( long n )
29 {
30
/* base case */
31
if ( n == 0 || n == 1 ) {
32
return n;
33
} /* end if */
34
else { /* recursive step */
35
36
return fibonacci( n - 1 ) + fibonacci(fig05_15.c
n - 2 ); (Part 2 of 2)
} /* end else */
37
38 } /* end function fibonacci */
Enter an integer: 0
Fibonacci( 0 ) = 0
Enter an integer: 1
Fibonacci( 1 ) = 1
Enter an integer: 2
Fibonacci( 2 ) = 1
Enter an integer: 3
Fibonacci( 3 ) = 2
Enter an integer: 4
Fibonacci( 4 ) = 3
Program Output
Enter an integer: 5
Fibonacci( 5 ) = 5
Enter an integer: 6
Fibonacci( 6 ) = 8
Enter an integer: 10
Fibonacci( 10 ) = 55
Enter an integer: 20
Fibonacci( 20 ) = 6765
Enter an integer: 30
Fibonacci( 30 ) = 832040
Enter anProgram
integer: 35
Output (continued)
Fibonacci( 35 ) = 9227465
5.14Example Using Recursion: The
Fibonacci Series
fibonacci( 3 )
return
return
fibonacci( 1 )
return 1
fibonacci( 2 )
+
fibonacci( 0 )
return 0
+
fibonacci( 1 )
return 1
5.15
Recursion vs. Iteration
• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case recognized
• Both can have infinite loops
• Balance
– Choice between performance (iteration) and good
software engineering (recursion)
14.4 Using Command-Line
Arguments
• Pass arguments to main on DOS or UNIX
– Define main as
int main( int argc, char *argv[] )
– int argc
• Number of arguments passed
– char *argv[]
• Array of strings
• Has names of arguments in order
– argv[ 0 ] is first argument
– Example:
•
•
•
•
argc:
argv[
argv[
argv[
$ mycopy input output
3
0 ]: “mycopy"
1 ]: "input"
2 ]: "output"
1
/* Fig. 14.3: fig14_03.c
Using command-line arguments */
2
3
#include <stdio.h>
Notice argc and
argv[] in main
Outline
4
5
int main( int argc, char *argv[] )
6
{
7
FILE *inFilePtr;
8
FILE *outFilePtr; /* output file pointer */
9
int c;
fig14_03.c (Part 1
of 2)
/* input file pointer */
/* define c to hold characters input by user */
argv[1] is the second
10
11
/* check number of command-line arguments */
12
if ( argc != 3 ) {
13
argument, and is being read.
printf( "Usage: copy infile outfile\n" );
14
} /* end if */
15
else {
16
17
/* if input file can be opened */
argv[2] is the third
18
if ( ( inFilePtr = fopen( argv[ 1 ], "r" ) ) != NULL ) {
argument, and is being
written to.
19
20
/* if output file can be opened */
21
if ( ( outFilePtr = fopen( argv[ 2 ], "w" ) ) != NULL ) {
22
23
/* read and output characters */
24
while ( ( c = fgetc( inFilePtr ) ) != EOF ) {
25
26
fputc( c, outFilePtr );
} /* end while */
27
28
} /* end if */
Loop until End Of File. fgetc a character from
inFilePtr and fputc it into outFilePtr.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson
29
30
31
else { /* output file could not be opened */
printf( "File \"%s\" could not be opened\n", argv[ 2 ] );
} /* end else */
Outline
32
33
} /* end if */
34
else { /* input file could not be opened */
35
36
printf( "File \"%s\" could not be opened\n", argv[ 1 ] );
} /* end else */
37
38
} /* end else */
39
40
return 0; /* indicates successful termination */
41
42 } /* end main */
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson
fig14_03.c (Part 2 of
2)
12.1 Introduction
• Dynamic data structures
– Data structures that grow and shrink during
execution
• Linked lists
– Allow insertions and removals anywhere
• Stacks
– Allow insertions and removals only at top of stack
• Queues
– Allow insertions at the back and removals from
the front
•
12.2 Self-Referential
Structures
Self-referential
structures
– Structure that contains a pointer to a structure
of the same type
– Can be linked together to form useful data
structures such as lists, queues, stacks and trees
– Terminated with a NULL pointer (0)
struct node {
int data;
struct node *nextPtr;
}
• nextPtr
– Points to an object of type node
– Referred to as a link
12.3 Dynamic Memory
Allocation
Figure 12.1 Two self-referential structures linked together
15
10
12.3 Dynamic Memory
Allocation
• Dynamic memory allocation
– Obtain and release memory during execution
• malloc
– Takes number of bytes to allocate
• Use sizeof to determine the size of an object
– Returns pointer of type void
*
• A void * pointer may be assigned to any pointer
• If no memory available, returns NULL
– Example
newPtr = malloc( sizeof( struct node ) );
• free
– Deallocates memory allocated by malloc
12.4 Linked Lists
• Linked list
– Linear collection of self-referential class objects,
called nodes
– Connected by pointer links
– Accessed via a pointer to the first node of the list
– Subsequent nodes are accessed via the linkpointer member of the current node
– Link pointer in the last node is set to NULL to mark
the list’s end
• Use a linked list instead of an array when
– You have an unpredictable number of data
12.4 Linked Lists
1
/* Fig. 12.3: fig12_03.c
Operating and maintaining a list */
2
3
#include <stdio.h>
4
#include <stdlib.h>
5
6
/* self-referential structure */
7
struct listNode {
8
char data;
9
struct listNode *nextPtr; /* listNode pointer */
/* define data as char */
10 }; /* end structure listNode */
11
12 typedef struct listNode ListNode;
13 typedef ListNode *ListNodePtr;
14
15 /* prototypes */
16 void insert( ListNodePtr *sPtr, char value );
17 char delete( ListNodePtr *sPtr, char value );
18 int isEmpty( ListNodePtr sPtr );
19 void printList( ListNodePtr currentPtr );
20 void instructions( void );
21
22 int main()
23 {
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson
Outline
fig12_03.c (Part 1 of
8)
24
ListNodePtr startPtr = NULL; /* initialize startPtr */
25
int choice;
/* user's choice */
26
char item;
/* char entered by user */
Outline
27
28
instructions(); /* display the menu */
29
printf( "? " );
30
scanf( "%d", &choice );
31
32
/* loop while user does not choose 3 */
33
while ( choice != 3 ) {
34
35
switch ( choice ) {
36
37
case 1:
38
printf( "Enter a character: " );
39
scanf( "\n%c", &item );
40
insert( &startPtr, item );
41
printList( startPtr );
42
break;
43
44
case 2:
45
46
/* if list is not empty */
47
if ( !isEmpty( startPtr ) ) {
48
printf( "Enter character to be deleted: " );
49
scanf( "\n%c", &item );
50
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson
fig12_03.c (Part 2 of
8)
51
/* if character is found */
52
if ( delete( &startPtr, item ) ) {
53
printf( "%c deleted.\n", item );
54
printList( startPtr );
55
} /* end if */
56
else {
printf( "%c not found.\n\n", item );
57
58
} /* end else */
59
60
} /* end if */
61
else {
62
63
printf( "List is empty.\n\n" );
} /* end else */
64
65
break;
66
67
default:
68
printf( "Invalid choice.\n\n" );
69
instructions();
70
break;
71
72
} /* end switch */
73
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson
Outline
fig12_03.c (Part 3 of
8)
74
printf( "? " );
75
scanf( "%d", &choice );
} /* end while */
76
Outline
77
printf( "End of run.\n" );
78
79
return 0; /* indicates successful termination */
80
81
82 } /* end main */
83
84 /* display program instructions to user */
85 void instructions( void )
86 {
printf( "Enter your choice:\n"
87
88
"
1 to insert an element into the list.\n"
89
"
2 to delete an element from the list.\n"
90
"
3 to end.\n" );
91 } /* end function instructions */
92
93 /* Insert a new value into the list in sorted order */
94 void insert( ListNodePtr *sPtr, char value )
95 {
96
ListNodePtr newPtr;
/* pointer to new node */
97
ListNodePtr previousPtr; /* pointer to previous node in list */
98
ListNodePtr currentPtr;
/* pointer to current node in list */
99
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson
fig12_03.c (Part 4 of
8)
100
newPtr = malloc( sizeof( ListNode ) );
101
102
if ( newPtr != NULL ) {
103
newPtr->data = value;
104
newPtr->nextPtr = NULL;
Outline
/* is space available */
fig12_03.c (Part 5 of
8)
105
106
previousPtr = NULL;
107
currentPtr = *sPtr;
108
109
/* loop to find the correct location in the list */
110
while ( currentPtr != NULL && value > currentPtr->data ) {
111
previousPtr = currentPtr;
/* walk to ...
112
currentPtr = currentPtr->nextPtr;
/* ... next node */
113
*/
} /* end while */
114
115
/* insert newPtr at beginning of list */
116
if ( previousPtr == NULL ) {
117
newPtr->nextPtr = *sPtr;
118
*sPtr = newPtr;
119
} /* end if */
120
else { /* insert newPtr between previousPtr and currentPtr */
121
previousPtr->nextPtr = newPtr;
122
newPtr->nextPtr = currentPtr;
123
} /* end else */
124
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson
125
} /* end if */
126
else {
printf( "%c not inserted. No memory available.\n", value );
127
Outline
} /* end else */
128
fig12_03.c (Part 6 of
8)
129
130 } /* end function insert */
131
132 /* Delete a list element */
133 char delete( ListNodePtr *sPtr, char value )
134 {
135
ListNodePtr previousPtr; /* pointer to previous node in list */
136
ListNodePtr currentPtr;
/* pointer to current node in list */
137
ListNodePtr tempPtr;
/* temporary node pointer */
138
139
/* delete first node */
140
if ( value == ( *sPtr )->data ) {
141
tempPtr = *sPtr;
142
*sPtr = ( *sPtr )->nextPtr;
/* de-thread the node */
143
free( tempPtr );
/* free the de-threaded node */
144
return value;
145
} /* end if */
146
else {
147
previousPtr = *sPtr;
148
currentPtr = ( *sPtr )->nextPtr;
149
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson
150
/* loop to find the correct location in the list */
151
while ( currentPtr != NULL && currentPtr->data != value ) {
152
previousPtr = currentPtr;
/* walk to ...
*/
153
currentPtr = currentPtr->nextPtr;
/* ... next node */
} /* end while */
154
155
156
/* delete node at currentPtr */
157
if ( currentPtr != NULL ) {
158
tempPtr = currentPtr;
159
previousPtr->nextPtr = currentPtr->nextPtr;
160
free( tempPtr );
161
return value;
} /* end if */
162
163
} /* end else */
164
165
return '\0';
166
167
168 } /* end function delete */
169
170 /* Return 1 if the list is empty, 0 otherwise */
171 int isEmpty( ListNodePtr sPtr )
172 {
173
return sPtr == NULL;
174
175 } /* end function isEmpty */
176
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson
Outline
fig12_03.c (Part 7 of
8)
177 /* Print the list */
178 void printList( ListNodePtr currentPtr )
Outline
179 {
180
181
/* if list is empty */
182
if ( currentPtr == NULL ) {
183
printf( "List is empty.\n\n" );
184
} /* end if */
185
else {
186
printf( "The list is:\n" );
187
188
/* while not the end of the list */
189
while ( currentPtr != NULL ) {
190
printf( "%c --> ", currentPtr->data );
191
currentPtr = currentPtr->nextPtr;
192
} /* end while */
193
194
195
printf( "NULL\n\n" );
} /* end else */
196
197 } /* end function printList */
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson
fig12_03.c (Part 8 of
8)
Enter your choice:
1 to insert an element into the list.
2 to delete an element from the list.
3 to end.
? 1
Enter a character: B
The list is:
B --> NULL
? 1
Enter a character: A
The list is:
A --> B --> NULL
? 1
Enter a character: C
The list is:
A --> B --> C --> NULL
? 2
Enter character to be deleted: D
D not found.
? 2
Enter character to be deleted: B
B deleted.
The list is:
A --> C --> NULL
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson
Outline
Program Output (Part
1 of 3)
? 2
Enter character to be deleted: C
C deleted.
The list is:
A --> NULL
? 2
Enter character to be deleted: A
A deleted.
List is empty.
? 4
Invalid choice.
Enter your choice:
1 to insert an element into the list.
2 to delete an element from the list.
3 to end.
? 3
End of run.
? 2
Enter character to be deleted: C
C deleted.
The list is:
A --> NULL
? 2
Enter character to be deleted: A
A deleted.
List is empty.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson
Outline
Program Output (Part
2 of 3)
? 4
Invalid choice.
Enter your choice:
1 to insert an element into the list.
2 to delete an element from the list.
3 to end.
? 3
End of run.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson
Outline
Program Output (Part
3 of 3)
12.4 Linked Lists
Related documents