Vous êtes sur la page 1sur 18

CGll01

NATIONAL UNIVERSITY OF SINGAPORE

SCHOOL OF COMPUTING

EXAMINATION FOR

Semester 1 AY2009/2010

CGll01- Programming Methodology

Dec 2009

Time Allowed: 2 Hours

INSTRUCTIONS TO CANDIDATES:
1. This examination paper contains FOUR questions and comprises EIGTHEEN (18) printed pages, including

this page. The weightage for each question is as indicated, and total 100 marks.
2. Answer all questions in the boxes provided. Do not write outside of the boxes.
3. This is an Open Book examination.
4. You may answer using either a pencil or a pen.
5. Please write your matriculation number below. Do NOT write your name.
MATRICULATION NO:

This portion is for examiner's use only


Question
Ql
Q2
Q3
Q4
Total

Marks

Remarks

120
130
125
125
1100

CGllOl

Question 1 (20 Marks)

This question consists of 4 parts, each worth 5 marks. Answer each part fully in the spaces provided.
a.

For each of the following statements, circle T if you agree with the statement and F if you don't.

i. A C program is immediately understandable by computers.


11.

The following code fragment may never terminate

T/F
T/F

int x;

... code that may/may not involve x...

while (x)

... code that may/may not involve x

iii. The following program shows an example of good modular design


#include <stdio.h>
int f;
double myfun(double x)
{

if(f==l)
return 2*x;
else
if(f==2)
return x;
else
return -x;

int main ()
{

double x;
f=l;
x=myfun(O.5);

T / F

CGll01

iv. The function call to myfun in the code fragment is an example of "call-by-value"
T/F

void myfun (double xl])


{

... do something with x...


int main ()
{

double x [ ] = {3 . 0, 1. 5, 1. 1 };
myfun (x);

v. The "if' and "else" parts of a ternary if statement can only hold one statement each.
T/F
b. Describe in a single statement of at most 30 words what the following function does. Each
additional word over 30 words will attract a 1 mark penalty.

int f(char xl], int a, int b)


if(a>=b)
return 1;
else
if (x [a] ==x [b] )
return f(x, a+1, b-1);
else
return 0;

Answer:

CG1101

c. The function in part b is given in recursive form. Rewrite the function in iterative form using the
function header given below, assuming that x is a properly terminated C string.
int g(char x[])

CGll01

d. Find and correct the mistakes in the program below. You may do the amendments directly on the
program. Note that you should only make the changes necessary to make the program run
correctly. Any unnecessary changes will result in a 1 mark penalty.
*include <stdio.h>

/* Program reverses the case of the letters in a string. I.e. if strl


holds "hElLo WoRlD! !N, this program will reverse the case to give
HeLlO wOrLD! t. Punctuations and spaces are left untouched */

int main()
char strl [) ={ , H', 'e', ' 1 ' , I' , '0' "
I

"

'W','o','r','l','d','!',

'!'};

char str2[32);

printf("Original string is %s\n", strl);

printf("String with reversed case is %s\n", reverseCase(strl));

void reverseCase(char str)

for(i=O; str[i] !='\O'; i++)

if(isupper(str[i]))

str[i)=toupper(str[i);

else

str[i)=tolower(str[i);

CG1101

Question 2 (30 Marks)

Sometimes we want to scramble messages we send for privacy reasons. The following example below
shows a "swing scrambler" in action. The "clear text" is the original message while the "cipher text" is the
scrambled message:
Clear text:

Cipher Text:

This algorithm scrambles a message first by taking the character at the extreme ends of the clear text
and placing them next to each other. The algorithm then moves one character inwards from either end
of the clear text, and repeats by placing the two extreme characters together. This process is repeated
until the entire clear text is scrambled. This process for the first few characters is shown below:

I~
The clear text can consist of any lower or upper-case letters (though the example only shows upper
case letters), punctuations and spaces. The cipher text is identical to the clear text except that the
characters are scrambled as shown. Of course it would be pointless if we could not unscramble the
text, so a reverse process is applied to get the clear text out of the cipher text.
In this question we will explore recursion and iteration by using recursion to scramble the text, and
iteration to unscramble.
a. We will now write the scrambling routine using recursion. You will not receive any credit if you
use an iterative algorithm. To begin, answer the following questions:
1.

What is the anchor condition for this recursion? (4 MARKS)

CG1101

ll.

What is the recurrent relation? (5 MARKS)

iii.

Using your answers to part i. and ii., write the full scrambling routine using
recursion in the space below. You should use the function definition as given.
(6 MARKS)
J* clr: Clear text. enc: Scrambled output. start: Starting position.
end: Ending position. count: Used by recursion to keep track of how
many characters have been written to enc. */
void scramble(char clr[], char enc[], int start, int end, int count)
{

CG1101

b. Write the unscrambling routine using iteration. You will not receive any credit if you use a
recursive algorithm. Once again use the function header given below. The calling function will
provide a C string in enc, and expects clr to hold the unscrambled text as a C string. (8 MARKS).
/* enc=Scrambled text. clr=Unscrambled text. */
void unscramble(char enc[], char clr[])

c. Write a full C program (inclusive of #includes, etc)that prompts the user for a filename, and
whether the user wants to encrypt the file (by entering "e" or "E"), or decrypt the file (by entering
"d" or "0"). If the user enters anything other than "e", "E", "d" or "0", the program will loop
until the user enters a valid choice. The program then prompts for an output filename, and
proceeds to encrypt or decrypt the input file and writing to the output file. (7 MARKS)

CGll01

Page is intentionally left blank

CGll01

Question 3 (25 Marks)

There are 6 related sub-questions (A to F) in this question. These sub-questions are written with 'loose
coupling' in mind but nevertheless there are some dependencies. Try to answer from A to F, in that order.
Please write your answers in the given boxes. Answers written outside the boxes will NOT be graded.
In this question, you are given a 3 x 3 grid of numbers named as g where each cell of g contains either an
integer 0 or an integer I, e.g.

111
100
001
Now, we define a function f(g) that transforms such a grid: each cell of the grid next--l5 = f(g) is the sum
(modulo 2) of its adjacent cells in g (two cells are considered adjacent if and only if they share a common
side, i.e. top, right, down, left). Note that a cell can have either 2, 3, or 4 adjacent cells in this 3 x 3 grid.
For clarity, see the example below:
9

= 111 --> sum adjacent cells --> 221 --> % 2 --> next_g
100
001

(not including that


cell itself)

010 --> sum adjacent cells --> 211 --> % 2 --> next_g
121
110
110
000

In general:

9 = ABC --> next_g


DEF
GHI

f(g)

(B+D)%2
(A+E+C)%2
(B+F)%2
(A+E+G)%2 (B+D+F+H)%2 (C+E+I)%2
(D+H) %2
(G+E+I) %2
(F+H) %2

A. (Conceive): Understandingf(g) (3 MARKS):


No
I

9
001
100
110
101
000
101
000
000
000

f(g)

001
100
110

f(g)

011
101
110

122
110

next 9 = f(g)

10

C61101

E. (Design): Grid g is a 2-D array of fixed size 3 x 3. We can pass this 2-D array to a functionf(g) but it is
not straightforward for a function to return a modified 2-D array next.J5.
Fortunately, there is the following mechanism in C: One can pass array g as a formal argument of f(g),
modify g insideJ(g), and setf(g) to return void. As array is passed by
_
whatever modifications to g inside functionJ(g) will be reflected outside this function.
'What should be written in place of the blank in the paragraph above? (1 MARK)

This is what we want! A function that takes in input grid g, modifies it according to the transformation
rule above, and 'returns' the modified g! That's it, rather than using next.J5, we simply overwrite g with
the new values after one call off(g).
C. (Implement): Now, write the body offunctionJ(g) in the box below (6 MARKS):

JI

optional: you can add few sub functions to support function f(g) below

II this is the main part of this question, write function f(g) here:
void f (int 9 [3] [3]) {

11

C61101
Furthennore, we define f{i} (g) recursively:
= g
(base case when i = 0), and
= f(f{i-J}(g))
(recursive case when i ~ 1).
Do not confusef(g), standard transfonnation shown above, with!i)(g), the recursive transfonnation.

fro} (g)
f(i)(g)

D. (Conceive): Understandingp(g) (3 MARKS):


No
1

f(U)

(g)

f(l)

(g)

f(~)

(g)

f(~)

f(4) (g)

(g)

111
100
001
101
000
101
000
000
000

2
,.,

"

I} (g) will transfonn the grid

E. (Design + Implement): Given any starting grid g, recursive application of


into a grid containing all zeroes at certain index i!

Now, design and implement a function to check whether a given 3 x 3 grid contains all zeroes? That
function should return an integer 1 if it is true, but return an integer 0 otherwise (3 MARKS).

int all zero(int g[3] [3])

{ II function prototype given

F. (Design + Implement): Your final task in this question is to compute the greatest index max i
when starting grid g is first transfonned into an all zeroes grid, for example:
g

111 --> max i


100

001

101 --> max i


000

101

000 --> max i


000

000

12

CGllOl

Show how you will implement a main function that performs the following top-down design:
I. Read one 3 x 3 grid from file named "grid.txt" that is written using the format below, e.g.
111 \n
100\n
00l\n
end of file

and store it into a 2-D integer array of size 3 x 3 (4 MARKS).


(Note that using "%d" in scanf will give you a single III for the first line instead of 1, 1, and 1).
2. Determine the greatest index maxj using functions void f (int
int all_zero (int 9 (3] (3] ) that you have created previously (4 MARKS).
(Yes, this is a coarse step, you need to refine it on your own).
3. Output this index max_i (1 MARK).
int main() {
II write variable declarations here:

II write code for step 1 here:

II write code for step 2 here:

II write code for step 3 here:

I }

return 0;

13

9 [3] [3])

and

CGl101

Question 4 (25 Marks)

There are 6 related sub-questions (A to F) in this question. Try to answer from A to F, in that order.
Please write your answers in the given boxes. Answers written outside the boxes will NOT be graded.
You are given an M * N grid where each cell contains the following data, 1 <= M, N <= 10:
1. A character that can have one of these values:
a. ' .', that denotes a sea.
b. '#', that denotes a land.
c. 'h', that denotes a house.
2. An integer that stores the amount of money that you have to pay for that cell:
a. if that cell is a '.' (sea), 0 SOD.
b. if that cell is a '#' (land), X SOD, where 0 < X :s 9, as you can plant crops there.
c. if that cell is a 'h' (house), Y SOD, where 0 < Y :s 9, the price of the house.
A. (Design

+ Implement): You want to store this grid as a 2-D array of structures.

Write how you will write a C code to construct the structure (name the structure as 'cell') and then the
array of such structure (name the array as 'grid') (2 MARKS):
#include <stdio.h>

II write struct declaration here (below #include <stdio.h:

II other function prototypes here


int main ()
II write array of structures declaration here (inside int main()):

return 0;

14

CG1101

Your task is as follow: Given a 2-D map of islands, what is the value of cheapest island to buy?
Two cells of either '#' (land) or 'h' are part of the same island if they share adjacent cells
(top, right, down, left). The island value is the sum of cell values that are '#' or 'h' in that island.
For example, see the following 5 * 7 island map written in "input.txt" below:

input. txt

The Map:

The Values:

5 7

... # #

.. # . #

.##.#h#

0000101

.##.#h#

0110272

.h# . . #.

0520030

.h# . . #.

0000101

0110272

0520030

0000000

0000999

... . hhh

0000000

... . hhh

0000999

We can see that there are several islands in this map:


1. One island looks like a 2 x 2 square at coordinate (1,1) to (2,2), denoted with bold.
It has value: 1+1+5+2 = 9.

2. Another looks like a I x 3 rectangle at coordinate (4,4) to (4,6), denoted with underline.
It has value 9+9+9 = 27.
B. (Conceive):
Are
those
two
islands
the
only
islands
In
the
Ifno, please roughly describe the shape of the other island(s) with its value(s) (2 MARKS).

map?

Answer:

C. (Conceive): After knowing all the islands and computing their values, what is the value ofthe cheapest
island (1 MARK)?
Answer:

15

CGll01

Now, please follow the step by step engineering process below to solve this question.
D. (Design + Implement): Suppose you are given 'input.txt' in the format above, Le. the first line contains
two integers, M and N. Then 2 * M lines appear. Each odd lines (line I, 3, 5, ..., 2*M-I) contains N
characters of celI type ('.', '#', or, 'h'). Each even lines (line 2, 4, 6, ..., 2*M) contains None-digit
integers denoting the value of the individual cell.
Show how you are going to write a C code that wi11 open this file 'input.txt', read its data, and store the
data in 2-D array of structures defined in part A!
Write your code inside the main function inside the box below (5 MARKS)!
int main () {
II you do not have to re-write your answer from part A again here
II but it is ok if you do so

II program for this part stops here


II the remaining part will be graded in part E
return 0;

E. (Implement + Operate): Suppose you have been given a working recursive function that has the following
function prototype:

16

CG1101

int island_value(struct cell grid.[10] [10], int r, int c, int M,

int N);

This function returns the value of an island that has cell(r, c) as part of the island AND 'turns' all cells in
the island into water (a '.'). The meaning of parameter grid, M, and N, are obvious.
So, using 'input.txt' above:
island_value(grid, 0,4,5,7) will return 1+2+7+2+1+3 = 16,
then cell(1,1), cell(1 ,2), cell(2, I), and cell(2,2) are all turned into a ' .' (water).
island_value(grid; 4, 4, 5, 7) will return 9+9+9 = 27,
then cell(4,4), cell(4,5), and cell(4,6) are all turned into a '.' (water).
island_value(grid, 0, 0, 5, 7) will return 0 = 0, as cell(O,O) is not actually part of an island!
Nothing else will happen as cell(O,O) is already a '.' (water).
This recursive function is robust enough to handle this case!
Now, show how you can use this recursive function to help you determine which island has the cheapest
value (5 MARKS)?
int main () {
II you may have to declare additional variables here:

II
II

the middle part (reading from input. txt)


the same as part B above

II
II
II

when your C code reach this line, it already has 2-D array

named 'grid' that already contains information from 'input.txt',

now write code to use function 'island value' here:

II

write code for displaying output here:

return 0;

17

is exactly

CGl101

F. (Conceive + Design + Implement): Now, the hard part, detecting the islands and computing its value, i.e.
how to implement such recursive function island_value?
int island_value(struct cell grid[10] [10]; int r, int c, int M, int N);
To solve this problem, you need to answer series of mini questions below.

These mini questions will guide you towards the solution.

a. Parameter grid, M, and N will be rather fixed, but parameter r and c will be varied throughout the
execution of this recursive function.
Now suppose that you are given a cell(r,c) that is 'outside' the map,what should be the return
value and what should this function do? (1 MARK).
I Answer:

b. Now suppose that you are given a cell(r,c) that is 'inside' the map, but it is a '.' (water), what
should be the return value and what should this function do? (1 MARK).
I Answer:

c. Now suppose that you are given a cell(r,c) that is 'inside' the map and that cell is either a '#' (land)
or 'h' (house), a.k.a. a 'valid cell', what should be the return value and what should this function
do? (2 MARKS).
I Answer:

d.

Why that after you encounter a 'valid cell' and have added its value toward the island value, you
have to 'turn' that 'valid cell' into a '.' (water)? (1 MARK).
I Answer:

e.

Now, write the recursive function in the box below (5 MARKS):

int island_value(struct cell grid[10] [10], int r, int c, int M, int N)

-End of Paper

18

Vous aimerez peut-être aussi