Arrays, pointers and functions

Due Friday 30 September at the beginning of lab. Turn in your report on Blackboard

Exercise 1

Compile and run the program analyse.c. Modify the program to replace the loop containing repeated getchar() calls with a single call to gets() or scanf(). Note that you will no longer have the length of the string in MAX, so you will either have to use the function strlen() (see textbook or manual pages or search online for details), or implement a sentinel-based approach (the string is terminated by a NULL or 0 value).

Now modify the program further so that it outputs the line entered by the user in the reversed order of characters before displaying the statistics.

Run the final program (after both the modifications) on two or three inputs, and show the output obtained.

Exercise 2

Understand the following program to multiply two 3x3 matrices: array4.c. Modify it to read the values of matrices A and B at run-time instead of defining them in the program. Suggest two sensible pairs of sample matrices to test your program. Compile and run the program on these inputs, and show the results obtained.

Now modify the program to deal with 7x7 rather than 3x3 matrices. Specifically, use loops to input and output the elements. Once again, suggest two sensible pairs of sample matrices to test your program. Compile and run the program on these inputs, and show the results obtained.

Exercise 3

Have a look at the program bubble.c. Do you understand how it works? Compile and run the program.

The number of swaps is not a very accurate measure of performance, as much time is inevitably spent comparing elements that do not require swapping. Modify the program to count the number of iterations of the do...while loop and display this number together with the number of swaps. Now compare these performance characteristics for the following two nearly-sorted input sequences: 10 1 2 3 4 5 6 7 8 9 and 2 3 4 5 6 7 8 9 10 1

Explain the difference.

Exercise 4

Have a look at the program funct6.c and try to predict its output. Run the program to see whether you were right. Can you see where the problem is?

What is the role of the two return statements in this program? Will it make any difference if you remove them?

Re-write the program to make it work. Do it in two different ways: by using a function that returns a value and by using a function that actually modifies variable x.

Compile and run the program, and show the results obtained.

Revised: 25 September 2005, f.mokhtarian@surrey.ac.uk
Revised: 24 September 2010, Montek Singh, montek@cs.unc.edu
Revised: 19 September 2011, Gary Bishop