Download PG Reading C Lab Script pdf
Transcript
224 Computer Programming Using C Revision 1.3 Exercise 18.3: Investigating Recursion Try building and executing the “lab18” program. Try putting different combinations of numbers in and check the results(the program will break if you put a large number in first!). Try stepping through the program and watching the contents of the variables change. Make sure you understand how the program works. Exercise 18.4: Calculating a Factorial Recursively In the “lab3a” program you wrote a program which calculated the factorial of a number using a for loop. Change this program (or write a new one) so that it calculates the factorial of the number using a recursive function. 18.4 Searching Using Recursion You have been taught about binary searches in your lectures. A binary search looks for a particular item in a sorted list by repeatedly breaking the list down into two parts. Exercise 18.5: A Recursive Binary Search Alter the “lab17a” program so that, after it has sorted the list of numbers, it asks the user for a number to search for. It should then perform a binary search using a recursive search function to find the number. The program should tell the user the line number of the number they requested in the sorted.txt file. (This is the same as its index in the array). 18.5 Summary Now that you have finished this laboratory you should understand how to implement a bubble sort algorithm, both for simple arrays of numbers and for more complex situations like strings and linked lists. Whilst doing this you will have used the strcmp and strcmpi string comparison functions. In the second part of the lab you learnt about recursion, which is a way of looping parts of your program by creating a function which calls itself. You should have used this technique to calculate a factorial and to perform a binary search on a sorted array of integers.