215
COVENANT UNIVERSITY ALPHA SEMESTER TUTORIAL KIT (VOL. 2) PROGRAMME:CIS 300 LEVEL

COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

COVENANT UNIVERSITY

ALPHA SEMESTER TUTORIAL KIT (VOL. 2)

P R O G R A M M E : C I S

300 LEVEL

Page 2: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

1

DISCLAIMER

The contents of this document are intended for practice and learning purposes at the undergraduate

level. The materials are from different sources including the internet and the contributors do not

in any way claim authorship or ownership of them. The materials are also not to be used for any

commercial purpose.

Page 3: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

2

LIST OF COURSES

CSC311: Discrete Structures

CSC312: Fundamentals of Data Structures

CSC313: Computer Programming IV (JAVA)

CSC314: Theory of Computing

CSC315: Computer Architecture and Organization

CSC317: System Analysis and Design

CSC318: Compiler Construction I

CSC319: Operation Research

*Not included

Page 4: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

3

COVENANT UNIVERSITY CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA. TITLE OF EXAMINATION: B.Sc DEGREE EXAMINATION

COLLEGE: SCEINCE AND TECHNOLOGY

SCHOOL: NATURAL AND APPLIED SCIENCES

DEPARTMENT: COMPUTER AND INFORMATION SCIENCES

SESSION: 2014/2015 SEMESTER: ALPHA

COURSE CODE: CSC 311 CREDIT UNIT: 3 Units

COURSE TITLE: DISCRETE STRUCTURES

INSTRUCTION: ATTEMPT ANY FOUR (4) QUESTIONS Time: 3 Hours

1a. Music is an interesting field of study besides being an integrative instrument for relaxation and

pleasure. Its impact transcends beyond continental and intercontinental borders. All musical

instruments have tones. Stringed instruments and pianos have keys which can be modulated or

changed. How does Modulo Arithmetic, as a sub-field of Discrete Structures, apply to music with

respect to keys and tones of musical instruments? Discuss extensively. 7.5 Marks

1b. Distinguish between asymptotic complexity and analysis of algorithms 2 Marks

1c. Prove that the De Morgan’s law as shown below is valid

(i) QPQP )( 2 Marks

(ii) QPQP )( 2 Marks

1d. The power set of a set A is the set of all subsets of A, and is denoted by; That is, Find all the

elements in A. if A = {2, 4, 17, 23} 2 Marks

1e.What is an Equivalence relation? 2 Marks

2a. Cocktail parties form an interesting aspect of end of semester programs for students of

Covenant University. The students of 300 level computer sciences were invited to a cocktail party.

Assuming there were 66 of them, and they were to shake hands shortly before the commencement

of the cocktail, show that they will end up shaking hands with odd number of participants. Justify

this by proving the Handshake Lemma. 7.5 Marks

2b. In Modulo Arithmetic, when are two integers said to be congruent? 2 Marks

2c. What is a predicate? Justify your answers with suitable illustrations 2 Marks

2d. Is it true that PQP )( is a tautology? Justify your answer 2 Marks

2e. When are two sets A and B said to be equal? 2 Marks

2f. What is a graph? Enumerate the contents of a graph 2 Marks

Page 5: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

4

3a. (i) Show that ))(()( ngOnf if and only if there exist a positive constant c and a constant

on , such that )()( ngcnf for all onn 5 Marks

3b.Can we assume that QQPP ))(( is a tautology? Justify your answer 2.5 Marks

3c. What is a poset? 2 Marks

3d. Define the term “cliques” 2 Marks

3e. What is a proposition? 2 Marks

3f. What is Modulo Arithmetic? 2 Marks

3g. What are some of the various applications of Modulo Arithmetic? 2 Marks

4a. Show that ))(()( ngnf if and only if ))(()( nfOng 5 Marks

4b. Mention and define the types of quantifiers we have in Mathematical logic 2.5 Marks

4c. Highlight some of the applications of a graph? 4 Marks

4d. What is a total order relation? 2 Marks

4e. Describe the term Graph Isomorphism 2 Marks

4f. When are two integers said to be congruent within the context of Modulo Arithmetic?

2 Marks

5a. Show that ))(()( ngnf if and only if ))(()( ngOnf and ))(()( ngnf 5 Marks

5b. Why is it essential to study Mathematical Logic? 2.5 Marks

5c. What is a set? Illustrate with examples 2 Marks

5d. What is a k-regular graph? 2 Marks

5e. What is a tree? 2 Marks

5f. What is a Spanning tree? 2 Marks

5g. Discuss some of the applications of Bipartite Graphs 2 Marks

6a. From your knowledge of Discrete structures, briefly estimate the asymptotic notation of this

equation

17log2

11512

11

1)( 3

23 nnnnnf 5 Marks

6b. If you are given a planar graph with 6 vertices and 14 edges, calculate the number of face(s) in

this planar graph. Draw this planar graph. 2.5 Marks

6c. Distinguish between paths and cliques. 2 Marks

6d. What is a walk within a graph? 1 Mark

6e. Prove that the Proposition CBCAXCBA is correct 3 Marks

6f. Discuss some of the applications of Bipartite Graphs and Graph coloring. 2 Marks

6g. What are some of the various applications of planar graphs to solving real-life problems in our

present society? 2 Marks

Page 6: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

5

Marking scheme

1a. In music, arithmetic modulo 12 is used in the consideration of the system of

twelve-tone equal temperament, where octave and enharmonic equivalency occurs

(that is, pitches in a 1:2 or 2:1 ratio are equivalent, and C-sharp is considered the

same as D-flat).

1b. Analysis of algorithms is concerned with estimating how many steps various

algorithms make while solving problems of various sizes. Asymptotic complexity

is a way of expressing the main component of the cost of an algorithm, using

idealized units of computational work.

1d.

1e.

2a.

Page 7: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

6

7.5 Marks

2b.

2 Marks

2c. What is a predicate? Justify your answers with suitable illustrations

2 Marks

2d. Yes

Page 8: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

7

2e.

2Marks

2f. What is a graph? Enumerate the contents of a graph

2 Marks

Page 9: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

8

3a. (i) Show that ))(()( ngOnf if and only if there exist a positive constant c and a constant

on , such that )()( ngcnf for all onn

Let there be a positive constants c and on

Then if ))(()( ngOnf

it implies that for all onn

)()( ngcnf

5 Marks

3b. Can we assume that QQPP ))(( is a tautology? Justify your answer

Yes, it is.

2.5 Marks

3c. What is a poset?

A partial order relation or a (poset) is

2 Marks

3d. Define the term “cliques”

2 Marks

3e. What is a proposition?

Page 10: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

9

2

Marks

3f. What is Modulo Arithmetic?

Modular arithmetic is a system of arithmetic for integers, where numbers "wrap around" upon

reaching a certain value—the modulus. The modern approach to modular arithmetic was

developed by Carl Friedrich Gauss in his book Disquisitiones Arithmeticae, published in 1801

2 Marks

3g. What are some of the various applications of Modulo Arithmetic?

Modular arithmetic is referenced in number theory, group theory, ring theory, knot theory, abstract

algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical

arts.

It is one of the foundations of number theory, touching on almost every aspect of its study, and

provides key examples for group theory, ring theory and abstract algebra.

Modular arithmetic is often used to calculate checksums that are used within identifiers -

International Bank Account Numbers (IBANs) for example make use of modulo 97arithmetic to

trap user input errors in bank account numbers.

In cryptography, modular arithmetic directly underpins public key systems such as RSA and

Diffie-Hellman, as well as providing finite fields which underlie elliptic curves, and is used in a

variety of symmetric key algorithms including AES, IDEA, and RC4.

In computer algebra, modular arithmetics is commonly used to limit the size of integer coefficients

in intermediate calculations and data. It is used in polynomial factorization, a problem for which

all known efficient algorithms use modular arithmetic. It is used by the most efficient

implementations of polynomial greatest common divisor, exact linear algebra and Gröbner basis

algorithms over the integers and the rational numbers.

In computer science, modular arithmetic is often applied in bitwise operations and other operations

involving fixed-width, cyclic data structures. The modulo operation, as implemented in many

programming languages and calculators, is an application of modular arithmetic that is often used

in this context. XOR is the sum of 2 bits, modulo 2.

In chemistry, the last digit of the CAS registry number (a number which is unique for each

chemical compound) is a check digit, which is calculated by taking the last digit of the first two

parts of the CAS registry number times 1, the next digit times 2, the next digit times 3 etc., adding

all these up and computing the sum modulo 10.

Page 11: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

10

In music, arithmetic modulo 12 is used in the consideration of the system of twelve-tone equal

temperament, where octave and enharmonic equivalency occurs (that is, pitches in a 1∶2 or 2∶1

ratio are equivalent, and C-sharp is considered the same as D-flat).

The method of casting out nines offers a quick check of decimal arithmetic computations

performed by hand. It is based on modular arithmetic modulo 9, and specifically on the crucial

property that 10 ≡ 1 (mod 9).

Arithmetic modulo 7 is used in algorithms that determine the day of the week for a given date. In

particular, Zeller's congruence and the doomsday algorithm make heavy use of modulo-7

arithmetic.

More generally, modular arithmetic also has application in disciplines such as law (see e.g.,

apportionment), economics, (see e.g., game theory) and other areas of the social sciences, where

proportional division and allocation of resources plays a central part of the analysis.

2 Marks

4a. Show that ))(()( ngnf if and only if ))(()( nfOng

Let there be a positive constants c and on

and for all onn if ))(()( nfOng

then it implies that ))(()( ngnf 5 Marks

4b. Mention and define the types of quantifiers we have in Mathematical logic

2.5 Marks

Page 12: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

11

4c. Highlight some of the applications of a graph?

4 Marks

4d. What is a total order relation?

2 Marks

4e. Describe the term Graph Isomorphism

2

Marks

Page 13: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

12

4f. When are two integers said to be congruent within the context of Modulo Arithmetic?

2 Marks

5a. Show that ))(()( ngnf if and only if ))(()( ngOnf and ))(()( ngnf

Let there be a positive constants c and on

Then if ))(()( ngOnf

And if ))(()( ngnf for all onn

Provided the constants c and on exists, then it implies that

)()( ngcnf 5 Marks

5b. Why is it essential to study Mathematical Logic?

2.5 Marks

5c. What is a set? Illustrate with examples

2 Marks

5d. What is a k-regular graph?

Page 14: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

13

2 Marks

5e. What is a tree?

2 Marks

5f. What is a Spanning tree?

2 Marks

5g. Discuss some of the applications of Bipartite Graphs

2 Marks

6a. From your knowledge of Discrete structures, briefly estimate the asymptotic notation of this

equation

Page 15: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

14

17log2

11512

11

1)( 3

23 nnnnnf

5 Marks

6b. If you are given a planar graph with 6 vertices and 14 edges, calculate the number of face(s) in

this planar graph. Draw this planar graph.

The formular n-e + f = 2

Therefore, n = 6, e = 14, then we have; 6 – 14 + f = 2

- 8 + f = 2

f = 2+8

f = 10 faces 1 Mark

1.5 Marks

6c. Distinguish between paths and cliques.

Page 16: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

15

2 Marks

6d. What is a walk within a graph?

1

Mark

6e. Prove that the Proposition CBCAXCBA is correct

3 Marks

6f. Discuss some of the applications of Bipartite Graphs and Graph coloring.

Page 17: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

16

Planar graphs can be applied in the aviation industry especially in modeling air

transportation networks.

-Train and subway transportation networks

-Computer networking (resolving issues)

- Road transportation network modeling

- network design, database management system modeling

- applied in designing and developing VLSI (Very large scale Integrated circuits) in

computer architecture

2 Marks

6g. What are some of the various applications of planar graphs to solving real-life problems in our

present society?

2 Marks

Page 18: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

17

COVENANT UNIVERSITY CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA. TITLE OF EXAMINATION: B.Sc DEGREE EXAMINATION

COLLEGE: SCEINCE AND TECHNOLOGY

SCHOOL: NATURAL AND APPLIED SCIENCES

DEPARTMENT: COMPUTER AND INFORMATION SCIENCES

SESSION: 2014/2015 SEMESTER: ALPHA

COURSE CODE: CSC 312 CREDIT UNIT: 3 Units

COURSE TITLE: FUNDAMENTALS OF DATA STRUCTURES

INSTRUCTION: INSTRUCTION: ATTEMPT ANY FOUR (4) QUESTIONS

Time: 2½Hours

1. Henry Chen is the captain of a rescue boat. One of his important tasks is to visit a group of

islands once a day to check if everything is all right. Captain Henry starts from the west-most

island, makes a pass to the east-most island visiting some of the islands, then makes a second pass

from the east-most island back to the first one visiting the remaining islands. In each pass Captain

Henry moves steadily east (in the first pass) or west (in the second pass), but moves as far north

or south as he needs to reach the islands. The only complication is that there are two special islands

where Captain Henry gets fuel for his boat, so he must visit them in separate passes. Figure 1

shows the two special islands in pink (1 and 3) and one possible path Captain Henry could take.

Figure 1

Page 19: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

18

(a) What data structure will be useful in analyzing this problem? [2 Marks]

(b) Write an algorithm to calculate the length of the shortest path to visit all the islands in

two passes when each island’s location and the identification of the two special

islands are given [11 Marks]

(c) In your algorithm, highlight the section where your data structure for solving the

problem will be embedded and the task it performs at the highlighted section. [4.5

Marks]

2a. Construct the DFS (Depth-First Search) and BFS (Breadth-First Search) by finding a path

between nodes A and K in the following Graph:

4 Marks

2b (i). Distinguish between recursion and a recursive function? 1 Mark

(ii). Distinguish between direct recursion and indirect recursion. 1 Mark

(iii). What is a mutual recursion? 1 Mark

2c. Recursion allows elegantly simple solutions to problems. In the light of this description, write

a Java or C++ recursive function that prints all the permutations of the first n characters of a string.

For example, the call print (“ABC”, 3) would print

ABC

ACB

BAC

BCA

CBA

CAB 3 Marks

Page 20: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

19

2d. Implement the recursive Ackermann function:

1),0( na

2)0,1( a

1,2)0,( ifmmma

),1),,1((),( nnmaanma if 0m and 0n

3 Marks

2e. Is stack a restricted data structure? Provide justification for your answer. 1 Mark

2f. For the weighted digraph G1, shown in Figure 2;

(i) Draw the adjacency matrix. 2 Marks

(ii) Draw the adjacency list. 1.5 Marks

3a. Draw the expression tree of this expression: (5-x) * y + 6 / (x + z) 3 Marks

3b. What are the infix, prefix and postfix representation for the expression (5-x) * y + 6 / (x + z)

3 Marks

3c. Here are three (3) trees. Describe how you will represent these trees as a forest (single binary

tree). Draw the new forest diagram. 5 Marks

Page 21: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

20

3d. (i) Define a Search tree. (ii) What is a Binary Search Tree? (iii) Mention one advantage of a

binary search tree 3 Marks

3e. (i) What is a Hash Table? (ii)Why do hash tables generally have faster access time? 3 Marks

3f. What is a good hash function? 0.5 Mark

4a. Draw the (1)stack and (2)linear queue (the original one), and (3)circular queue data structures

in array implementations for “each step” in the following sequence: add(A), add(B), remove,

remove, add(D), add(E), remove, add(F), add(G). Assume an initial size of 5 for the array

implementation. Remember to show TOP (top of the stack) for stack and both Front and Back for queue.

In circular queue implementation, assume we sacrifice one storage space for telling the difference between

FULL and EMPTY [5 Marks]

4b. What are circular queues? Write down routines for inserting and deleting elements from a

circular queue implemented using arrays. [5 marks]

4c. Describe a Stack as an ADT. [2.5 marks]

4d. How do you find the complexity of an algorithm? What is the relation between the time and

space complexities of an algorithm? Justify your answer with an example. [5 marks]

5a. This question tests your understanding of stacks. You must implement a stack ADT in C++.

The underlying representation of the stack should be a C++ primitive array.

You will be graded mostly on the correctness of the ideas of your solution rather than exact

C++ syntax, but your solution should be clear. Correct C++ code is the best way to ensure we

understand your solution.

You should implement all the functions with > in front of them.

class Stack {

public:

Stack(int initialcapacity); // constructor

void push(int value); // pushes value onto the stack.

int pop(); // returns and removes the value on the top of the

stack.

Page 22: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

21

bool isEmpty(); // returns true if the stack contains no

elements.

bool isFull(); // returns true if the stack is full

}; [8 marks]

5b. Sort the following list using Heap Sort technique, displaying each step.

20, 12, 25 6, 10, 15, 13 [4 mks]

5c. (i) Compare the merits and demerits of using array and pointer-based implementation for List

data structure [4 mks]

(ii) Given a pointer based implementation of a queue, write a short code for inserting an item

into a nonempty queue. Using the diagram below: [11/2 mks]

6a. In implementing a Queue using an array, a problem might arise if the Queue is implemented

in such a way that items in the Queue are inserted at the next available location and removed from

the next leading position, but such that, once deleted, the emptied space is unused. The problem

that arises is one where there is free space still in the array, but it is not usable because it is not at

the end. Demonstrate this problem with a Queue that is stored in an array of size 5 for the following

instructions. Next, explain how you might resolve this problem.

Queue q = new Queue(5); //assume the Queue constructor takes 5 as size of the array

q.enqueue(3);

q.enqueue(4);

q.enqueue(1);

q.dequeue( );

q.dequeue( );

q.enqueue(6);

q.enqueue(5);

q.dequeue( ); // at this point, there are only 2 item2 in the queue

q.enqueue(7); // this enqueue can not occur, why?? [5 marks]

6b. Create a heap with following list of keys:

8, 20, 9, 4, 15, 10, 7, 22, 3, 12 [4 marks]

6c. (i) Write an algorithm for searching a key from a sorted list using binary search technique.

Page 23: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

22

(ii) Using a binary search algorithm and trace to search element 91 in following list:

13 30 62 73 81 88 91

(iii) What are the limitations of Binary Search? [4 marks]

6d. Explain the method to calculate the address of an element in an array. A 25×4 matrix array

DATA is stored in memory in ‘row-major order’. If base address is 200 and w = 4 words per

memory cell. Calculate the address of DATA [12, 3]. [4 marks]

Marking Scheme

1a. Graph data structure [2 Marks]

1b. Dijkstra's algorithm, conceived by computer scientist Edsger Dijkstra in 1956 and published in

1959,[1][2] is a graph search algorithm that solves the single-source shortest path problem for

a graph with non-negative edge path costs, producing a shortest path tree. This algorithm is often

used in routing and as a subroutine in other graph algorithms.

For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the

shortest path) between that vertex and every other vertex. It can also be used for finding costs of

shortest paths from a single vertex to a single destination vertex by stopping the algorithm once

the shortest path to the destination vertex has been determined.

Dijkstra's algorithm- It picks the unvisited vertex with the lowest-distance, calculates the distance

through it to each unvisited neighbor, and updates the neighbor's distance if smaller. Mark visited

(set to red) when done with neighbors. 3 Marks

Dijkstra's Algorithm:

1 function Dijkstra(Graph, source):

2 dist[source] := 0 // Distance from source to source

3 for each vertex v in Graph: // Initializations

4 if v ≠ source

5 dist[v] := infinity // Unknown distance function from source to v

6 previous[v] := undefined // Previous node in optimal path from source

7 end if

8 add v to Q // All nodes initially in Q (unvisited nodes)

9 end for

10

11 while Q is not empty: // The main loop

12 u := vertex in Q with min dist[u] // Source node in first case

13 remove u from Q

14

Page 24: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

23

15 for each neighbor v of u: // where v has not yet been removed from Q.

16 alt := dist[u] + length(u, v)

17 if alt < dist[v]: // A shorter path to v has been found

18 dist[v] := alt

19 previous[v] := u

20 end if

21 end for

22 end while

23 return dist[], previous[]

24 end function

8 Marks

Dijkstra's Algorithm Description

Let the node at which we are starting be called the initial node. Let the distance of node Y be the distance from the initial

node toY. Dijkstra's algorithm will assign some initial distance values and will try to improve them step by step.

1. Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes.

2. Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited nodes called the unvisited

set consisting of all the nodes.

3. For the current node, consider all of its unvisited neighbors and calculate their tentative distances. Compare the newly

calculatedtentative distance to the current assigned value and assign the smaller one. For example, if the current

node A is marked with a distance of 6, and the edge connecting it with a neighbor B has length 2, then the distance

to B (through A) will be 6 + 2 = 8. If B was previously marked with a distance greater than 8 then change it to 8.

Otherwise, keep the current value.

4. When we are done considering all of the neighbors of the current node, mark the current node as visited and remove it

from theunvisited set. A visited node will never be checked again.

5. If the destination node has been marked visited (when planning a route between two specific nodes) or if the smallest

tentative distance among the nodes in the unvisited set is infinity (when planning a complete traversal; occurs when there

is no connection between the initial node and remaining unvisited nodes), then stop. The algorithm has finished.

6. Select the unvisited node that is marked with the smallest tentative distance, and set it as the new "current node" then go

back to step 3.

4.5 Marks

2a. DFS (Depth-First Search)

OpenList: G, C

ClosedList: A, B, D, E, F

||

OpenList: H, I, C

ClosedList: A, B, D, E, F , G

||

OpenList: J, K, I, C

ClosedList: A, B, D, E, F, G, H

||

OpenList: J, I, C

Page 25: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

24

ClosedList: A, B, D, E, F, G, H, K

BFS (Breadth-First Search)

OpenList: E

Closed List: A, B, C, D

||

OpenList: F, G

ClosedList: A, B, C, D, E

||

OpenList: G, H, I

ClosedList: A,B, C, D, E, F

||

OpenList: H, I

ClosedList: A, B, C, D, E, F, G

||

OpenList: J, K, I

ClosedList: A,B, C, D, E, F, G, H

||

OpenList: I

Closed List: A, B, C, D, E, F, G, H, J, K

||

Final ClosedList: A, B, C, D, E, F, G, H, I, J, K

2b. (i)

Recursion Recursive function

Recursion is the repeated

application of a recursive

procedure or definition.

Recursion is the process of

repeating items in a self-

similar way. For instance,

when the surfaces of two

mirrors are exactly parallel

with each other, the nested

images that occur are a form

of infinite recursion.

Thus, a recursive function is one that calls

itself. This powerful technique produces

repetition without using while loops,

do…while loops, or for loops. Thus, it can

produce substantial results from very little

code.

Recursion in computer

science is a method where the

Page 26: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

25

solution to a problem depends

on solutions to smaller

instances of the same problem

(as opposed to iteration)

(Ronald et al., 1990) .The

approach can be applied to

many types of problems, and

recursion is one of the central

ideas of computer science

(Epp, Susanna (1995)).

2b(ii). When a function calls itself, it is called a direct recursion. Another form of recursion

is when a function calls other functions that call other functions that eventually call the

original function. This is called indirect recursion.

2b(iii). It s most common form is when two functions call each other. This is called mutual

recursion.

2c. Recursion allows elegantly simple solutions to problems.

A recursive function that prints permutations:

public static void print (String str)

{ print (“ “, str);

}

public static void print (String left, String right)

{ int n= right.length ( );

If (n = = 0) return;

If ( n = = 1)

{ System.out.println (left+right);

Return;

}

StringBuffer s = new StringBuffer (right);

for (int I =0; i < n; i++)

{ char temp = s.charAt (i);

s.setCharAt (i,s.charAt(0));

s.setCharAt (0, temp);

print (left+temp, s.substring (1,n));

}

Page 27: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

26

}

}

2d. The Ackermann function:

public static int ackermann (int m, int n)

{ if (m = = 0) return 1;

if ( n = = 0)

if ( m = = 1 ) return 2;

else return m + 2;

return ackermann (ackermann (m – 1, n), n-1);

}

2e. YES, Stack is a restricted data structure. This is because only a small number of

operations are performed on it. The nature of the pop and push operations also means that

stack elements have a natural order. Elements are removed from the stack in the reverse

order to the order of their addition. Therefore, the lower elements are those that have been

on the stack the longest.

2f.

The adjacency matrix.

7004

0002

0015

0306

A

2 Marks

(iii) The adjacency list.

A 3 6

B15

C2

D74

1.5 Marks

Page 28: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

27

3a.

3b. The infix, prefix and postfix representation for the expression (5-x) * y + 6 / (x + z)

Prefix: +*-5xy/6+xz 1 Mark

Infix: 5-x*y+6/x+z 1 Mark

Postfix(RPN): 5x-y*6xz+/+ 1 Mark

3c. A forest is a collection or list of trees. Here is a forest that consists of three (3) trees.

5 Marks

Page 29: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

28

3d. (i) A Search tree is a tree that maintains its data in some sorted data. 1 Mark

(ii) A Binary search tree is a binary tree whose elements include a key field of some ordinal

type and which has the following property:

if k is the key value at any node, then k≥x for every key x in the nodes left subtree and

k≤y for every key y in the node’s right subtree. This property, called the BST property,

guarantees that an inorder traversal of the binary search tree will produce the elements in

the increasing order. 1 Mark

(iii) One of the advantages of using tree structures is that they are useful in storing data because

their organization renders or allows more efficient access to stored data. 1 Mark

3e.(i) A Hash Table is a table that uses a special function to compute the location of data values

from their key values instead of storing the keys in the table.

The special function is called the Hash function for the table. 1 Mark

(ii) Hash Tables generally have faster access time because the lookup time is independent of the

size of the the table. 2 Marks

3f. A Good hash function is a function that is unlikely to return the same value for different keys.

0.5 Mark

Page 30: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

29

Page 31: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

30

Page 32: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

31

Page 33: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

32

Page 34: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

33

Page 35: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

34

Page 36: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

35

Page 37: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

36

Page 38: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

37

COVENANT UNIVERSITY

CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA.

TITLE OF EXAMINATION: B.Sc DEGREE EXAMINATION

COLLEGE: SCEINCE AND TECHNOLOGY

SCHOOL: NATURAL AND APPLIED SCIENCES

DEPARTMENT: COMPUTER AND INFORMATION SCIENCES

SESSION: 2015/2016 SEMESTER: ALPHA

COURSE CODE: CSC 313 CREDIT UNIT: 2

COURSE TITLE: COMPUTER PROGRAMMING IV (JAVA)

INSTRUCTION: ANSWER QUESTION ONE AND ANY TWO QUESTIONS

Time: 2 Hours

1. a) What will be the output of the following: 31/2Marks class Hat {

Hat() { System.out.println("Hat constructor"); }

}

class Fedora extends Hat {

Fedora() { System.out.println("Fedora constructor"); }

}

public class Stetson extends Fedora {

Page 39: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

38

Stetson() { System.out.println("Stetson constructor"); }

public static void main(String[] args) {

Stetson st = new Stetson();

}

}

b) Explain the following terms and give a typical example

i. Applets

ii. JSP

6Marks

c) Write the appropriate code segment to verify if firstName (entered from a textbox) and

lastName(entered from a textbox) is existing in a particular table name “Registration”

containing only two columns named “firstname” and “lastnane” in the database called

“Students”

10Marks

d) Write an application that inputs one number consisting of five digits from the user, separates the

number into its individual digits and prints the digits separated from one another by three spaces

each. For example, if the user types in the number 42339, the program should print

4 2 3 3 9 71/2Marks

e) Consider the following code snippet

if (aNumber >= 0)

if (aNumber == 0)

System.out.println("first string");

else System.out.println("second string");

System.out.println("third string");

What output does the code produce if aNumber is -1? 3 Marks

Page 40: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

39

2. a) Write the JSP code that can be used to enter the following from a website interface (via text

fields) into a table called “Biodata” in the database named “RecordStudents”

i. Name

ii. Surname

iii. Address

iv. Email

iv. Sex

vi. Password

10Marks

b) Explain the difference between a binary file and a text file 3 Marks

c) Explain is the difference between Swing and AWT in Java netbeans 3 Marks

d) What is the difference between a class and an object in Java? 4 Marks

3. a) Explain a Typical JSP architecture 4Marks

b) Mention 4 message dialog constant and their uses (JOptionPane Message Dialog Constants)

4Marks

c) Write a program to create a text file called “MyName” in Java and write an essay of at least 5

lines about yourself into the file. 6Marks

d) Write a program that reads in a year and determines whether it is a leap year. A year is a leap

year if it is divisible by four, unless it is divisible by 100. Years divisible by 100 are leap years

only if divisible by 400. 6Marks

4. a) Mention 5 Uses of JSP 21/2Marks

b) There are different types of variables in Java. List and briefly describe any three

Page 41: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

40

6 Marks

c) Write a program to calculate the average of the following student scores

Maths English CIS

Tomi 80.0 45.8 60.6

Chinwe 50.0 60.4 12.8

71/2Marks

d) Explain and give examples of the following in Java

i. Polymorphism ii. Inheritance 5Marks

5. a) Given String aString = "Niagara O roar again!";

What will be the value returned from the following:

i. aString.substring(11,15);

ii. aString.indexOf(“g”);

iii. aString.lastIndexOf(“g”, 8); 4Marks

b) What will be the output of the following program

5Marks

c) Write a BMI calculator program that reads the user’s weight in kilograms and height in meters, then

calculates and displays the user’s body mass index

BMI = weightInKilograms / (heightInMeters × heightInMeters)

Page 42: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

41

Based on the BMI value, the program should tell the user whether she/he is underweight, normal

weight, overweight or obese using the following information:

BMI VALUES

Underweight: less than 18.5

Normal: between 18.5 and 24.9

Overweight: between 25 and 29.9

Obese: 30 or greater 8Marks

d) What will be the output of the following

class Shape {

public String toString() {

return " a Shape";

}

}

class Triangle extends Shape {

public String toString() {

return "a Triangle";

}

}

public class DrawShape {

static void draw(Shape s) {

System.out.println("Drawing " + s);

}

public static void main(String[] args) {

Triangle t = new Triangle();

draw(t);

}

}

Page 43: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

42

3Marks

Page 44: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

43

COVENANT UNIVERSITY

CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA.

TITLE OF EXAMINATION: B.Sc DEGREE EXAMINATION MARKING SCHEME

COLLEGE: SCEINCE AND TECHNOLOGY

SCHOOL: NATURAL AND APPLIED SCIENCES

DEPARTMENT: COMPUTER AND INFORMATION SCIENCES

SESSION: 2015/2016 SEMESTER: ALPHA

COURSE CODE: CSC 313 CREDIT UNIT: 2

COURSE TITLE: COMPUTER PROGRAMMING IV (JAVA)

INSTRUCTION: ANSWER QUESTION ONE AND ANY FOUR OTHER TWO QUESTIONS

Time: 2 Hours

QUESTION 1

a) Hat constructor

Fedora constructor

Stetson constructor

b)

i. Applets are Java programs that can be embedded in HTML documents. Furthermore, a Java applet can

be described as a small application which is written in Java and delivered to users in the form of bytecode.

The user launches the Java applet from a web page, and the applet is then executed within a Java Virtual

Machine (JVM) in a process separate from the web browser itself.

Page 45: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

44

• When a browser loads a web page containing an applet, the applet downloads into the web

browser and executes.

• The browser that executes an applet is known as the applet container. The JDK includes the appletviewer

applet container for testing applets before you embed them in a web page.

ii.

Java Server Pages (JSP) technology is an extension of servlet technology. Each JSP is translated by the

JSP container into a servlet. Unlike servlets, JSPs help you separate presentation from content. JavaServer

Pages enable web application programmers to create dynamic content by reusing predefined components

and by interacting with components using server-side scripting. A JSP is a server side scripting language

similar to ASP or PHP. It is a text file that had a “.jsp”.extension and contains a mix of HTML and

embedded java code.

c)

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

try {

Page 46: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

45

String firstName = jTextField1.getText().trim();

String lastName = jTextField2.getText().trim();

boolean verify=true;

//Create a connection to the database

Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/Students", "root","ibk");

Statement st = (Statement) con.createStatement();

ResultSet res = st.executeQuery("SELECT * FROM Registration");

//select the items in the database table one after the other

while (res.next()) {

String firstnameStored= res.getString("firstname").trim();

String lastnameStored = res.getString("lastname").trim();

if ((firstname.equals(firstnameStored)) && (lastname.equals(lastnameStored)))

{

verify=true;

break;

}

else

{

verify=false;

}

}

if (verify==true)

{// this section can be replaced with printing out valid or not valid

this.setVisible(false);

AvailableBurgers newAvailableBurgers = new AvailableBurgers();

newAvailableBurgers.setVisible(true);

}

else

{// this section can be replaced with printing out valid or not valid

Page 47: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

46

this.setVisible(false);

RegistrationPage newRegistrationPage = new RegistrationPage();

newRegistrationPage.setVisible(true);

}

con.close();

} catch (SQLException ex) {

Logger.getLogger(HomePage.class.getName()).log(Level.SEVERE, null, ex);

}

}

d)

import javax.swing.JOptionPane;

/**

*

* @author adewoleadewumi

*/

public class NumberSeparation {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

char [] digit = new char[5];

// Accept the number using JOptionPane

String num = JOptionPane.showInputDialog(null, "Enter a five digit number");

// Is the number of length five

Page 48: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

47

if (num.length()==5){

// Use charAt() method to retrieve each digit

for(int i = 0; i < num.length(); i++){

digit[i] = num.charAt(i);

}

JOptionPane.showMessageDialog(null, digit[0] + " " + digit[1] + " " + digit[2]+ " " + digit[3] +

" " + digit[4]);

}

else{

JOptionPane.showMessageDialog(null, "The input is not five digit long!!");

}

}

e) third string

QUESTION 2.

a)

<%

String name =request.getParameter("name");

String surname =request.getParameter("surname");

String address =request.getParameter("address");

String email =request.getParameter("email");

String sex =request.getParameter("sex");

String password =request.getParameter("password");

String sql = "INSERT INTO Biodata

VALUES('"+name+"','"+surname+"','"+address+"','"+email+"','"+sex +"','"+password+"')";

try{

Connection conn = (Connection)

DriverManager.getConnection("jdbc:mysql://localhost/RecordStudents", "root","ibk");

Statement st = (Statement) conn.createStatement();

st.executeUpdate(sql);

conn.setAutoCommit(true);

response.sendRedirect("availableBurgers.jsp");//line not compulsory

Page 49: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

48

}catch(Exception e){

e.printStackTrace();}

%>

b)

Data stored in a text file are represented in human-readable form. Data stored in a binary file are

represented in binary form. You cannot read binary files. Binary files are designed to be read by

programs. For example, the Java source programs are stored in text files and can be read by a text

editor, but the Java classes are stored in binary files and are read by the JVM. The advantage of

binary files is that they are more efficient to process than text files.

c)

There are actually two sets of GUI components in Java. Before Swing was introduced in Java SE

1.2, Java GUIs were built with components from the Abstract Window Toolkit (AWT) in package

java.awt. When a Java application with an AWT GUI executes on different Java platforms, the

application’s GUI components display differently on each platform. Sometimes, the manner in

which a user can interact with a particular AWT component differs between platforms.

Together, the appearance and the way in which the user interacts with the application are known as

that application’s look-and-feel.

Swing GUI components allow you to specify a uniform look-and-feel for your application across

all platforms or to use each platform’s custom look-and-feel. An application can even change the

look-and-feel during execution to enable users to choose their own preferred look-and-feel.

d)

A class is as an extensible template that specifies the structure of a particular style of object. An

object is a conceptually integrated entity that encapsulates both state and behavior. Each object is

an instance of a particular class, which can, in turn, serve as a template for many different objects.

If you want to create objects in Java, you must first define the class to which those objects belong

and then construct individual objects that are instances of that class.

QUESTION 3.

a)

JSP Architecture

To process JSP pages, a web server needs a JSP container and a servlet engine.

The JSP container is responsible for intercepting requests for JSP pages

Page 50: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

49

It works with the web server to provide the runtime environment and other services a JSP

needs.

It understands the special elements that are part of a JSP

Apache and Glassfish have a built in JSP container and servlet engine.

b)

c)

public class FilesProject {

public static void main(String[] args) {

try {

BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\test\\MyName.txt"));

bw.write("This is the story of my life");

bw.write("My name is ibk");

bw.write("My School is CU");

bw.write("I am tall");

bw.write("I love Java");

Page 51: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

50

bw.newLine();

bw.close();

} catch (Exception e) {

System.out.println("Error");

}

}

}

d)

QUESTION 4

a)

Java Server Pages are used for developing web pages that have dynamic content…

Colleting input from users through forms

Presenting records from a database

Sharing information between pages

Sending emails

Uploading files

b) Instance variable (non-static fields)

Objects store their individual states in “non static fields”, i.e. a field declared without the static

keyword. Non-static fields are also known as instance variables because their values are unique to

each instance of a class. For example: the currentSpeed of a bicycle is independent of the

currentSpeed of another.

Class variables (static fields)

Page 52: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

51

A class variable is any field declared with the static modifier. This tells the compiler that there is

exactly one copy of this variable in existence regardless of how many times the class has been

instantiated. A field defining the number of wheels of a car could be marked as static since this applies

to all instances. The code will be:

static int numberOfWheels = 4;

Local variables

A method stores its temporary state in local variables. The syntax for declaring a local variable is

similar to declaring a field. Found within the opening and closing braces of a method. Local variables

are only visible to the methods in which they are declared; they are not accessible from the rest of

the class.

Parameters

They are variables that are passed to the methods of a class.

c)

d) i.Polymorphism: It uses a program that uses inheritance. Polymorphism literally means taking more

than one form. polymorphism is a characteristic of being able to assign a different behavior or value in a

subclass, to something that was declared in a parent class

Page 53: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

52

ii. Inheritance is a compile-time mechanism in Java that allows you to extend a class (called the base

class or superclass) with another class (called the derived class or subclass).

NUMBER 5

a) i) oar

ii) 3

iii) 3

b) van.wheels = 6

van.doors = 3

keke.wheels = 6

keke.doors = 0

Vehicles.wheels = 6

c) import javax.swing.JOptionPane;

public class BMICalculator {

public static void main(String[] args) {

double weightInKilograms;

double heightInMetres;

double bmi;

weightInKilograms = Double.parseDouble(JOptionPane.showInputDialog("Enter weight in kilograms:

"));

heightInMetres = Double.parseDouble(JOptionPane.showInputDialog("Enter height in metres: "));

bmi = weightInKilograms / (heightInMetres * heightInMetres);

String message = "";

if (bmi < 18.5){

message = " \nYou are underweight!!";

}

else if (bmi >= 18.5 && bmi <= 24.9){

message = " \nYou are normal weight!!";

}

Page 54: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

53

else if (bmi >= 25 && bmi <= 29.9){

message = " \nYou are overweight!!";

}

else

message = " \nYou are obese!!";

JOptionPane.showMessageDialog(null, "Your BMI is " + bmi + message);

}

}

d) Drawing a Triangle

Page 55: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

54

COVENANT UNIVERSITY

CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA.

B.SC DEGREE EXAMINATION

COLLEGE: Science & Technology SCHOOL: Natural &

Applied Sciences

DEPARTMENT: Computer & Information Sciences SESSION:2014/2015

SEMESTER: Alpha COURSE CODE: CSC313

CREDIT UNIT: 2 COURSE TITLE: Computer Programming IV (JAVA)

INSTRUCTION: Answer question ONE and any other TWO Questions

TIME: 2 HOURS

1. Given the interface; write the java program code segment, such that when the enter

button is clicked, values are sent successfully into;

a. A text file. 7Marks

b. A database 7Marks

c. Write a program to calculate the sum of the first 10 terms of the series.

1/1 + ¼ + 1/9 + 1/16………………….. 6Marks d. What is the output of the following code

public class GUIDemo {

public static void main(String[] args) {

Page 56: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

55

JFrame frame = new JFrame("TESTING");

frame.setSize(100, 300);

frame.setVisible(true);

frame.setDefaultCloseOperation(

JFrame.EXIT_ON_CLOSE);

frame.getContentPane().add(new JButton("THANKS")); } } 4Marks

e. Write a program to compute the sum of the matrices.

2 5 3 1 1 1

4 5 6 + 1 1 1 =

7 8 9 1 1 1

Declare and initialize the matrices in the program. 6Marks

2. a) Write a program that adds two values gotten from two different functions.

i. The first function should calculate the sum of 2+6+10+14--------100.

ii. The second function should calculate the sum of 2+4+6+8----------100

iii. In the main function, calculate and print the sum of the results from the first two

functions. 8Marks

b) Explain the following; 8Marks

i. Java is Architecture Neutral

ii. Java is Secure

iii Polymorphism

iv Inheritance

.

c) What is the output of this program;

public class Test {

public static void main(String[] args) {

int x = 1; // x represents an int value

int[] y = new int[10]; // y represents an array of int values

m(x, y); // Invoke m with arguments x and y

System.out.println("x is " + x);

System.out.println("y[0] is " + y[0]); }

public static void m(int number, int[] numbers) {

number = 1001; // Assign a new value to number

numbers[0] = 5555; // Assign a new value to numbers[0] }}

4Marks

3. a. Sketch the interface and write a program attached to the command button that calculates the

average of the following student scores

Maths English CIS

Page 57: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

56

Tomi 80.0 45.8 60.6

Chinwe 50.0 60.4 12.8 7Marks

b. The Fibonacci numbers are members of an interesting sequence in which each

number is equal to the sum of the previous two numbers. i.e. Fi =Fi-1 +Fi-2

Where Fi refers to the ith Fibonacci number. By definition, the first two Fibonacci

numbers equal 1; i.e.F1= F2 = 1. Hence,

F3 = F2+F1 = 1+1 = 2

F4 = F3+F2 = 2+1 = 3

F5 = F4+F3 = 3+2 = 5

And so on. Write a program that will determine the first n Fibonacci numbers.

8Marks

c) Explain the following;

Java uses pass by value to pass parameters to a method.

5Marks

4. a) Write a program to that adds all the elements of an integer array using the enhanced for

loop. Display the total. 6Marks

b) Write a program that reads in the first m elements of a one dimensional floating point array

and calculates the mean. 8Marks

c) List and explain the three categories of errors in Java. 6Marks

5a) Write a program that calculates the area of a cylinder by receiving the value of radius and

height from the user through the keyboard. 8Marks

b) What are Java applets? 3Marks

c) What are the major differences between an applet and an application? 3Marks

d) Write Java applets and HTML codes to display the message Welcome to Covenant

University in a Browser 6Marks

MARKING SCHEME

1. a)

String room= jTextField1.getText();

String amount = jTextField2.getText();

Page 58: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

57

Object selectedItem = jComboBox1.getSelectedItem();

String Gender = selectedItem.toString();

try{

BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\test\\hotel.txt",true));

bw.write(room);

bw.write("\t");

bw.write(amount);

bw.write("\t");

bw.write(Gender );

bw.newLine();

bw.close();

}

catch(Exception e){

System.out.println("you have an error");

}

jTextField1.setText(null);

jTextField2.setText(null);

b)

String room= jTextField1.getText();

String amount = jTextField2.getText();

Object selectedItem = jComboBox1.getSelectedItem();

String Gender = selectedItem.toString();

try {

Connection con = DriverManager.getConnection("jdbc:mysql://localhost/hotel",

"root","ibk");

Statement st = (Statement) con.createStatement();

String insert = "INSERT INTO hotelDetails VALUES (' " +roomr+ "', ' "

+amount+ "',' " +Gender+ "')";

st.executeUpdate(insert);

System.out.print("Successfully inserted value");

con.close();

} catch (Exception e) {

e.printStackTrace(); }

jTextField1.setText(null);

jTextField2.setText(null);

c)

Page 59: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

58

d)

e)

Page 60: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

59

f) i.Polymorphism: It uses a program that uses inheritance. Polymorphism literally means taking

more than one form. polymorphism is a characteristic of being able to assign a different behavior

or value in a subclass, to something that was declared in a parent class

ii. Inheritance is a compile-time mechanism in Java that allows you to extend a class (called the

base class or superclass) with another class (called the derived class or subclass).

2.

a)

public static void main(String[] args) {

int total;

total = one() + two();

System.out.printf("The sum of both functions is %d", total);

}

int one(){

int x = 0;

for(int counter = 2; counter <= 100; counter += 4) {

x = x + counter; }

return x;

Page 61: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

60

}

int two(){

int y = 0;

for(int counter = 2; counter <= 100; counter += 2) {

y = y + counter;}

return y;

}

b) i. Java implements several security mechanisms to protect your system against harm

caused by stray programs.

ii. Write once, run anywhere. With a Java Virtual Machine (JVM), you can write one

program that will run on any platform.

iii. Inheritance is a compile-time mechanism in Java that allows you to extend a class

(called the base class or superclass) with another class (called the derived class or

subclass).

iv. It uses a program that uses inheritance. Polymorphism literally means taking more

than one form. polymorphism is a characteristic of being able to assign a different

behavior or value in a subclass, to something that was declared in a parent class.

c)

3a)

Page 62: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

61

b)

. public class Tutorials2 {

public static void main(String[] args)

{

int index = 0;

while (true)

{

System.out.println(fibonacci(index));

index++;

}

}

public static long fibonacci (int i)

{

if (i == 0) return 0;

if (i<= 2) return 1;

long fibTerm = fibonacci(i - 1) + fibonacci(i - 2);

return fibTerm;

}

}

c)

Java uses pass by value to pass parameters to a method. There are important differences between

passing a value of variables of primitive data types and passing arrays.

• For a parameter of a primitive type value, the actual value is passed. Changing the value

of the local parameter inside the method does not affect the value of the variable outside

the method.

• For a parameter of an array type, the value of the parameter contains a reference to an

array; this reference is passed to the method. Any changes to the array that occur inside

the method body will affect the original array that was passed as the argument.

4a) class fruits{

public static void main(String [] args){

int apples[]={3,4,5,6,7);

int total=0;

for(int x: apples){

total+=x;

}

System.out.println(total);

Page 63: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

62

}

}

b) public class Tutorials2 {

public static void main(String[] args) {

Scanner input = new Scanner (System.in);

int[] apples = new int[5];

double total=0.0;

System.out.println("Enter number: ");

for (int i=0; i<5;i++)

apples[i] = input.nextInt();

double ave;

for(int i=0; i<5;i++)

total+= apples[i];

ave=total/5;

System.out.println(ave);

}

}

c) There are three categories of errors:

• Syntax errors

– Arise because the rules of the language have not been followed.

– They are detected by the compiler.

• Runtime errors

– Runtime errors occur while the program is running if the environment detects an

operation that is impossible to carry out.

• Logic errors.

– Logic errors occur when a program doesn't perform the way it was intended to.

5.

a)

public class Geometry2 {

public static void main(String[] args) {

Cylinder cyl = new Cylinder();

Page 64: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

63

cyl.process();

}

}

public class Cylinder {

double EnterRadius() {

double rad;

Scanner scnr = new Scanner(System.in);

System.out.print("Radius: ");

rad = scnr.nextDouble();

return rad;

}

double EnterHeight() {

double h;

Scanner scnr = new Scanner(System.in);

System.out.print("Height: ");

h = scnr.nextDouble();

return h; }

double calculateVolume(double rad, double hgt) {

return 3.14159 * rad * rad * hgt; }

void process() {

double radius;

double height;

double volume;

System.out.println("Enter the dimensions of the cylinder");

radius = EnterRadius();

height = EnterHeight();

volume = calculateVolume(radius, height);

System.out.println("\nCylinder Characteristics");

System.out.printf("Radius: %g\n", radius);

System.out.printf("Height: %g\n", height);

System.out.printf("Volume: %f\n", volume);

}

}

b) A Java applet is a special kind of small Java program that runs on a browser. An applet is

typically embedded inside a web page and runs in the context of a browser. An applet must be a subclass

of the java.applet.Applet class.

c) Applets are usually small and run under the control of a browser, whereas an application runs

stand-alone, with the support of a virtual machine.

d)

import java.awt.*; // import the AWT graphic classes

import java.util.*; // import the utility classes

import java.applet.*; // import the AWT graphic classes

import javax.swing.*; // import the swing classes

Page 65: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

64

/**

* This the famous first program (hello world) it is an

* Apllet that prints out “hello World” to the screen

*

* @ author your Name

*

*/

Public class Hello World extends J Applet

{

Public void paint (Graphics g)

{

g.drawString(“Welcome to Covenant University”, 95,130);

}

}

<html>

<head>

<title>Welcome </title>

</head>

<body>

<p>Welcome to Covenant University

<applet code="Welcome.class" width=300 height=200>

</applet>

</body>

</html>

Page 66: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

65

COVENANT UNIVERSITY CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA. TITLE OF EXAMINATION: B.Sc DEGREE EXAMINATION

COLLEGE: SCEINCE AND TECHNOLOGY

SCHOOL: NATURAL AND APPLIED SCIENCES

DEPARTMENT: COMPUTER AND INFORMATION SCIENCES

SESSION: 2014/2015 SEMESTER: ALPHA

COURSE CODE: CSC 311 CREDIT UNIT: 3 Units

COURSE TITLE: DISCRETE STRUCTURES

INSTRUCTION: ATTEMPT ANY FOUR (4) QUESTIONS Time: 3 Hours

1a. Music is an interesting field of study besides being an integrative instrument for relaxation and

pleasure. Its impact transcends beyond continental and intercontinental borders. All musical

instruments have tones. Stringed instruments and pianos have keys which can be modulated or

changed. How does Modulo Arithmetic, as a sub-field of Discrete Structures, apply to music with

respect to keys and tones of musical instruments? Discuss extensively. 7.5 Marks

1b. Distinguish between asymptotic complexity and analysis of algorithms 2 Marks

1c. Prove that the De Morgan’s law as shown below is valid

(i) QPQP )( 2 Marks

(ii) QPQP )( 2 Marks

1d. The power set of a set A is the set of all subsets of A, and is denoted by; That is, Find all the

elements in A. if A = {2, 4, 17, 23} 2 Marks

1e.What is an Equivalence relation? 2 Marks

2a. Cocktail parties form an interesting aspect of end of semester programs for students of

Covenant University. The students of 300 level computer sciences were invited to a cocktail party.

Assuming there were 66 of them, and they were to shake hands shortly before the commencement

of the cocktail, show that they will end up shaking hands with odd number of participants. Justify

this by proving the Handshake Lemma. 7.5 Marks

2b. In Modulo Arithmetic, when are two integers said to be congruent? 2 Marks

2c. What is a predicate? Justify your answers with suitable illustrations 2 Marks

2d. Is it true that PQP )( is a tautology? Justify your answer 2 Marks

2e. When are two sets A and B said to be equal? 2 Marks

2f. What is a graph? Enumerate the contents of a graph 2 Marks

Page 67: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

66

3a. (i) Show that ))(()( ngOnf if and only if there exist a positive constant c and a constant

on , such that )()( ngcnf for all onn 5 Marks

3b.Can we assume that QQPP ))(( is a tautology? Justify your answer 2.5 Marks

3c. What is a poset? 2 Marks

3d. Define the term “cliques” 2 Marks

3e. What is a proposition? 2 Marks

3f. What is Modulo Arithmetic? 2 Marks

3g. What are some of the various applications of Modulo Arithmetic? 2 Marks

4a. Show that ))(()( ngnf if and only if ))(()( nfOng 5 Marks

4b. Mention and define the types of quantifiers we have in Mathematical logic 2.5 Marks

4c. Highlight some of the applications of a graph? 4 Marks

4d. What is a total order relation? 2 Marks

4e. Describe the term Graph Isomorphism 2 Marks

4f. When are two integers said to be congruent within the context of Modulo Arithmetic?

2 Marks

5a. Show that ))(()( ngnf if and only if ))(()( ngOnf and ))(()( ngnf 5 Marks

5b. Why is it essential to study Mathematical Logic? 2.5 Marks

5c. What is a set? Illustrate with examples 2 Marks

5d. What is a k-regular graph? 2 Marks

5e. What is a tree? 2 Marks

5f. What is a Spanning tree? 2 Marks

5g. Discuss some of the applications of Bipartite Graphs 2 Marks

6a. From your knowledge of Discrete structures, briefly estimate the asymptotic notation of this

equation

17log2

11512

11

1)( 3

23 nnnnnf 5 Marks

6b. If you are given a planar graph with 6 vertices and 14 edges, calculate the number of face(s) in

this planar graph. Draw this planar graph. 2.5 Marks

6c. Distinguish between paths and cliques. 2 Marks

6d. What is a walk within a graph? 1 Mark

6e. Prove that the Proposition CBCAXCBA is correct 3 Marks

6f. Discuss some of the applications of Bipartite Graphs and Graph coloring. 2 Marks

6g. What are some of the various applications of planar graphs to solving real-life problems in our

present society? 2 Marks

Page 68: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

67

Marking scheme

1a. In music, arithmetic modulo 12 is used in the consideration of the system of

twelve-tone equal temperament, where octave and enharmonic equivalency occurs

(that is, pitches in a 1:2 or 2:1 ratio are equivalent, and C-sharp is considered the

same as D-flat).

1b. Analysis of algorithms is concerned with estimating how many steps various

algorithms make while solving problems of various sizes. Asymptotic complexity

is a way of expressing the main component of the cost of an algorithm, using

idealized units of computational work.

1d.

1e.

Page 69: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

68

2a.

7.5 Marks

2b.

2 Marks

2c. What is a predicate? Justify your answers with suitable illustrations

Page 70: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

69

2 Marks

2d. Yes

Page 71: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

70

2e.

2Marks

2f. What is a graph? Enumerate the contents of a graph

2 Marks

3a. (i) Show that ))(()( ngOnf if and only if there exist a positive constant c and a constant

on , such that )()( ngcnf for all onn

Let there be a positive constants c and on

Then if ))(()( ngOnf

it implies that for all onn

)()( ngcnf

5 Marks

3b. Can we assume that QQPP ))(( is a tautology? Justify your answer

Yes, it is.

Page 72: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

71

2.5 Marks

3c. What is a poset?

A partial order relation or a (poset) is

2 Marks

3d. Define the term “cliques”

2 Marks

3e. What is a proposition?

2

Marks

3f. What is Modulo Arithmetic?

Modular arithmetic is a system of arithmetic for integers, where numbers "wrap around" upon

reaching a certain value—the modulus. The modern approach to modular arithmetic was

developed by Carl Friedrich Gauss in his book Disquisitiones Arithmeticae, published in 1801

2 Marks

Page 73: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

72

3g. What are some of the various applications of Modulo Arithmetic?

Modular arithmetic is referenced in number theory, group theory, ring theory, knot theory, abstract

algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical

arts.

It is one of the foundations of number theory, touching on almost every aspect of its study, and

provides key examples for group theory, ring theory and abstract algebra.

Modular arithmetic is often used to calculate checksums that are used within identifiers -

International Bank Account Numbers (IBANs) for example make use of modulo 97arithmetic to

trap user input errors in bank account numbers.

In cryptography, modular arithmetic directly underpins public key systems such as RSA and

Diffie-Hellman, as well as providing finite fields which underlie elliptic curves, and is used in a

variety of symmetric key algorithms including AES, IDEA, and RC4.

In computer algebra, modular arithmetics is commonly used to limit the size of integer coefficients

in intermediate calculations and data. It is used in polynomial factorization, a problem for which

all known efficient algorithms use modular arithmetic. It is used by the most efficient

implementations of polynomial greatest common divisor, exact linear algebra and Gröbner basis

algorithms over the integers and the rational numbers.

In computer science, modular arithmetic is often applied in bitwise operations and other operations

involving fixed-width, cyclic data structures. The modulo operation, as implemented in many

programming languages and calculators, is an application of modular arithmetic that is often used

in this context. XOR is the sum of 2 bits, modulo 2.

In chemistry, the last digit of the CAS registry number (a number which is unique for each

chemical compound) is a check digit, which is calculated by taking the last digit of the first two

parts of the CAS registry number times 1, the next digit times 2, the next digit times 3 etc., adding

all these up and computing the sum modulo 10.

In music, arithmetic modulo 12 is used in the consideration of the system of twelve-tone equal

temperament, where octave and enharmonic equivalency occurs (that is, pitches in a 1∶2 or 2∶1

ratio are equivalent, and C-sharp is considered the same as D-flat).

The method of casting out nines offers a quick check of decimal arithmetic computations

performed by hand. It is based on modular arithmetic modulo 9, and specifically on the crucial

property that 10 ≡ 1 (mod 9).

Arithmetic modulo 7 is used in algorithms that determine the day of the week for a given date. In

particular, Zeller's congruence and the doomsday algorithm make heavy use of modulo-7

arithmetic.

Page 74: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

73

More generally, modular arithmetic also has application in disciplines such as law (see e.g.,

apportionment), economics, (see e.g., game theory) and other areas of the social sciences, where

proportional division and allocation of resources plays a central part of the analysis.

2 Marks

4a. Show that ))(()( ngnf if and only if ))(()( nfOng

Let there be a positive constants c and on

and for all onn if ))(()( nfOng

then it implies that ))(()( ngnf 5 Marks

4b. Mention and define the types of quantifiers we have in Mathematical logic

2.5 Marks

4c. Highlight some of the applications of a graph?

Page 75: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

74

4 Marks

4d. What is a total order relation?

2 Marks

4e. Describe the term Graph Isomorphism

2

Marks

4f. When are two integers said to be congruent within the context of Modulo Arithmetic?

2 Marks

5a. Show that ))(()( ngnf if and only if ))(()( ngOnf and ))(()( ngnf

Let there be a positive constants c and on

Then if ))(()( ngOnf

And if ))(()( ngnf for all onn

Page 76: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

75

Provided the constants c and on exists, then it implies that

)()( ngcnf 5 Marks

5b. Why is it essential to study Mathematical Logic?

2.5 Marks

5c. What is a set? Illustrate with examples

2 Marks

5d. What is a k-regular graph?

2 Marks

5e. What is a tree?

Page 77: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

76

2 Marks

5f. What is a Spanning tree?

2 Marks

5g. Discuss some of the applications of Bipartite Graphs

2 Marks

6a. From your knowledge of Discrete structures, briefly estimate the asymptotic notation of this

equation

17log2

11512

11

1)( 3

23 nnnnnf

Page 78: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

77

5 Marks

6b. If you are given a planar graph with 6 vertices and 14 edges, calculate the number of face(s) in

this planar graph. Draw this planar graph.

The formular n-e + f = 2

Therefore, n = 6, e = 14, then we have; 6 – 14 + f = 2

- 8 + f = 2

f = 2+8

f = 10 faces 1 Mark

1.5 Marks

6c. Distinguish between paths and cliques.

Page 79: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

78

2 Marks

6d. What is a walk within a graph?

1

Mark

6e. Prove that the Proposition CBCAXCBA is correct

3 Marks

6f. Discuss some of the applications of Bipartite Graphs and Graph coloring.

Planar graphs can be applied in the aviation industry especially in modeling air

transportation networks.

-Train and subway transportation networks

-Computer networking (resolving issues)

- Road transportation network modeling

- network design, database management system modeling

Page 80: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

79

- applied in designing and developing VLSI (Very large scale Integrated circuits) in

computer architecture

2 Marks

6g. What are some of the various applications of planar graphs to solving real-life problems in our

present society?

2 Marks

Page 81: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

80

COVENANT UNIVERSITY

CANAANLAND, KM 10, IDIROKO ROAD

P.M.B. 1023, OTA, OGUN STATE, NIGERIA TITLE OF EXAMINATION: B.Sc EXAMINATION

COLLEGE: SCIENCE AND TECHNOLOGY

DEPARTMENT: COMPUTER & INFORMATION SCIENCES

SESSION: 2015/2016 SEMESTER: ALPHA

COURSE CODE: CSC 314 CREDIT UNIT: 2

COURSE TITLE: THEORY OF COMPUTING TIME: 2 HOURS

INSTRUCTION: ATTEMPT QUESTION 1 AND ANY OTHER TWO QUESTIONS

1(a) Giving W = 1n0m : n = 4, m=5; a =1203 and b=1302 such that a, b,w ={0,1}

determine the output for the following operations.

(8 marks)

(i) ||

(ii) |w|

(iii) w(3)o(4)

(iv) aowobR

(v) |aowobR|

(vi) (boa)R

1(b) Given the transition table below answer the following question

(i) Determine the type of automata machine it represents

(2marks)

Page 82: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

81

(ii) Represent the machine with transition diagram

(5marks)

(iii) Describe the language accepted by the machine

(3marks)

1c) When do you say that PDA machine is in Accept and Reject status?

(5marks)

1(d) Consider the grammar G where Vn = {A, B}, Vt = {1, 0, c, S} is the start symbol, and P

consists of:

1. A → 1BAc |10c

2. B1 →1B

4. B0 → 00

(i) Formulate a derivation of strings in L(G) = 1m0ncq : m = q=n and n = √16 from the

grammar G

(5marks)

(ii) Describe the rule path formed.

(2marks)

2(a) What are the language strings described by the following regular expressions?

(i) (0∪)(1∪). (ii) 0 ∪ (iii) 1*

(iv) 01* ∪ 1*.

(v) 1*∅

(vi) ∅* (6 marks)

(b) Give the regular expressions best describe the following languages. = {0, 1}.(8marks)

(i) {w : w contains at least two 1s and at most one 0},

(ii) {w : w contains an even number of 0s and exactly two 1s}.

(iii) {w : w contains exactly two 0s and at least one 1s}.

(iv) {w : w contains an even number of 0s and each 0 is followed by at least one 1}.

(v) {w : every odd position in w is 1}.

(vi) {{w : the length of w is odd}

(vii) {w : w begins with 1 and ends with 0}

(viii) {w : the length of w is even}

(c) What are the language descriptions that best describe the following regular expressions?

(i) 1*01*01*.

(ii) (0 ∪ 1)*0(0 ∪ 1)*0(0 ∪ 1)*

(iii) (0 ∪ 1)*1011(0 ∪ 1)*.

(iv) 1* ((0 ∪ 1)(0 ∪ 1))* (6marks)

3(a) Give a formal definition of NFA (3marks)

Page 83: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

82

3(b) Convert the following NFA to a DFA using the subset construction.

(i) Show the transition table for the NFA and the DFA (6marks)

(ii) Show the complete DFA (3marks)

(iii) Show the minimized DFA and state the reasons. (3marks)

3(c) Show a (possibly nondeterministic) Finite State Machine that accepts {w ∈{a, b}* : w

contains at least one instance of aaba, bbb or ababa}. (5marks)

4(a) Convert the regular expression (aba) to NFA using Thomson’s construction (6

marks)

4(b) b. Given a DFA M Q{1,2,3}, q ={q1}, F={1,2} = {a,b} that accepts L

(i) Convert M to a context-free grammar G whose language is equal to L. 5marks

(ii) Determine if string aaabbba is an element of M and show the derivation

for the string. 4marks

(iii) What are the states visited by the string in (ii) 2

marks

(iv) Is string bbbabb acceptable by the M ? Show the grammar derivation. 3

marks

5(a) Illustrate Push and Pop PDA Operations with explanation (7.5marks)

Page 84: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

83

5(b) (i) Construct a deterministic pushdown automaton that accepts the set L of all strings

in {0n1n : n ≥ 0} (5 marks)

(ii) Determine if language L = {0412n} is accepted by PDA machine wheren =1,2,3.

Illustrate the transition for each language and state the reason if not accepted

(7.5 marks)

Page 85: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

84

COVENANT UNIVERSITY

CANAANLAND, KM 10, IDIROKO ROAD

P.M.B. 1023, OTA, OGUN STATE, NIGERIA TITLE OF EXAMINATION: B.Sc EXAMINATION

COLLEGE: SCIENCE AND TECHNOLOGY

SCHOOL: APPLIED AND NATURAL SCIENCES

DEPARTMENT: COMPUTER & INFORMATION SCIENCES

SESSION: 2015/2016 SEMESTER: ALPHA

COURSE CODE: CSC 314 CREDIT UNIT: 2

COURSE TITLE: THEORY OF COMPUTING Marking Scheme TIME:

2 HOURS

INSTRUCTION: ATTEMPT QUESTION 1 AND ANY OTHER TWO QUESTIONS

1(a)

(vii) || = 0

(viii) |w| = 9

(ix) w(3)o(7) =10

(x) aowobR = 1100011110000000111

(xi) |aowobR| = |1100011110000000111|= 19

(xii) (boa)R = (1110011000)R = 0001100111

1(b)

(i) This is NFA machine

(ii)

q0 q2

q1

q3

q4

a

a

a

a

b

a

b b a

a

a a

b

b

b

Page 86: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

85

(iii) The language consists of any string containing at least 2 a's or 2 b's. 1(c)

• The PDA accepts when there exists a computation path such that: – The computation path ends in an accepts state – All the input are consumed – (no requirement for the stack)

• The PDA rejects when all the paths: – Either end in a non-accepting state – Or are incomplete (meaning that at some point there is no possible transition under the

current input stack symbols) 1(d) A → 1BAc → 1B1BAcc (1) → 1B1B1BAccc (1) → 1B1B1B10cccc (2) → 11BB1B10cccc (3) → 11B1BB10cccc (3) → 111BBB10cccc (3) → 111BB1B0cccc (3) → 111B1BB0cccc (3) → 1111BBB0cccc (3) → 1111BB00cccc (4) → 1111B000cccc (4) → 11110000cccc (4) 1(b) (ii) The rule path is sequential starting from (1 1 2 3 3 3 3 3 3 4 4 4) 2(a)

(i) The regular expression (0∪)(1∪) describes the language {01, 0, 1, }.

(ii) The regular expression 0 ∪ describes the language {0, },

(iii) the regular expression 1* describes the language {, 1, 11, 111, . . .}.

(iv) the regular expression (0 ∪)1* describes the language {0, 01, 011, 0111, . . . , , 1, 11, 111, . . .}. (v) The regular expression 1*∅ describes the language ∅.

(vi) The regular expression ∅* describes the language {}. (b)

(ix) {w : w contains at least two 1s and at most one 0}1*11(01)

(x) {w : w contains an even number of 0s and exactly two 1s}.(00)*11

(xi) {w : w contains exactly two 0s and at least one 1s}. 001+

(xii) {w : w contains an even number of 0s and each 0 is followed by at least one 1}.

(01+01+)*

Page 87: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

86

(xiii) {w : every odd position in w is 1}. (10)*1

(xiv) {{w : the length of w is odd} ((0+1)(0+1)(0+1))+

(xv) {w : w begins with 1 and ends with 0} (10)+

(xvi) {w : the length of w is even} ((0+1)(0+1))+

c) (i) 1*01*01*.= All sting of 0’s and 1’s containing at least two 0’s (ii) (0 ∪ 1)*0(0 ∪ 1)*0(0 ∪ 1)* = All sting of 0’s and 1’s containing at least two 0’s (iii) (0 ∪ 1)*1011(0 ∪ 1)*.= All sting of 0’s and 1’s containing a substring 1011 (iv) 1* ((0 ∪ 1)(0 ∪ 1))* = All sting of 0’s and 1’s start with 1 3(a)

A non-deterministic finite automaton (NFA) is a 5-tuple

M = (Q, , δ, q, F), where 1. Q is a finite set, whose elements are called states,

2. is a finite set, called the alphabet ; the elements of are called symbols,

3. δ : Q × → P(Q) is a function, called the transition function, 4. q is an element of Q; it is called the start state, 5. F is a subset of Q; the elements of F are called accept states. 3(b) For the DFA The start is 0 The accept state is {2, 12, 23, 123,}

The State Q =(, 1,2,3,12,13,23,124)

a b

0 {0,1} 0

1 2

*2 2 2

01 {0,1} {0,2}

*02 {0,1,2} {0,2}

*12 2 2

*012 {0,1,2} {0,2}

a b

0 0,1 0

1 2

*2 2 2

DFA

2 2

{0,1} {0,2}

{0,1,2} {0,2}

NFA

2 2

{0,1} {0,2}

{0,1,2} {0,2}

Page 88: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

87

(ii) (iii) 3(c)

c

c

b

0

2

1

c{0,1} {0,2}

{1,2}

{0,1,2}

a,b

b

a

a,b

a

b

b a

b

a

a,b a

0

c{0,1} {0,2}

{0,1,2}

b

a

a

b

b a

b

a

Page 89: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

88

(4a)

(aba) where the alphabet is {a,b}. We will prove that this regular expression describes a re gular language, by constructing an NFA that accepts the language described by this regular expression. This is how the regular expression is built.

or 4(b)

a

a

b

Page 90: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

89

(i) 1 A2|B2| Rule1,2,3

2 A2|B3 Rule4,5

3 A1| 2B| Rule 6,7,8

(ii) 1 A2 (1) AA2 (4) AAA2 (4) AAAB3 (5) AAABB2 (7) AAABBB3 (5) AAABBBA1 (4) AAABBBA (3) (iii) 1,2,2,2,3,2,3,1

(iv) 1 B2 BB3

BBB2 BBBA2 BBBAB3 BBBABB2 bbbabb is not accepted since at the right side there is still non-terminal

5(b) (i)

5(b) (ii)

, 0,

1, 0

1, 0 , $

q q

qq

Page 91: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

90

(iii)Determine if language L = {0412n} is accepted by PDA machine where n =1,2,3.

Illustrate the transition for each language and state the reason if not accepted

When n = 1 , therefore L = {0412} = 000011 This is rejected since the is still 00 in the stack, this indicate excess of zeros. When n = 2 , therefore L = {0414} = 00001111 This is accepted since all zeros pushed into the stack are pop out and the stack was made empty., this indicate excess of zeros. When n = 3 , therefore L = {0416} = 0000111111

$

0

0

0

0

q0q1; $ is push to the start

q1q1; 0 is push into the stack

q1q1; 0 is push into the stack

q1q1; 0 is push into the stack

q1q1; 0 is push into the stack

$

0

0

q0q1; $ is push to the start

q1q1; 0 is push into the stack

q1q1; 0 is push into the stack

q2q2; 0 is pop out of the stack

q1q2; 0 is pop out of the stack

q1q2; 0 is pop out of the stack

q2q2; 0 is pop out of the stack

q2q2; 0 is pop out of the stack

q2q2; 0 is pop out of the stack

q2q3; $ is pop out of the stack and

the stack is empty

$ $

0

0

0

0

q0q1; $ is push to the start

q1q1; 0 is push into the stack

q1q1; 0 is push into the stack

q1q1; 0 is push into the stack

q1q1; 0 is push into the stack

q1q2; 0 is pop out of the stack

q2q2; 0 is pop out of the stack

q2q2; 0 is pop out of the stack

q2q2; 0 is pop out of the stack

q2q3; 0 is pop out of the stack while

the stack is empty, the operation halt

$ $

0

0

0

0

q0q1; $ is push to the start

q1q1; 0 is push into the stack

q1q1; 0 is push into the stack

q1q1; 0 is push into the stack

q1q1; 0 is push into the stack

Page 92: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

91

This is rejected since there is halt in the operation, which indicate excess of ones. 5(a) Push Operation

(ii) Pop Operation

a, qq

b

h

e

$

t

Pus

Sta

. a .In

. a .

b

h

e

$

c

a, b qq

bhe$

to

PO

St

. a .In

. a .

he$

Page 93: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

92

COVENANT UNIVERSITY CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA. TITLE OF EXAMINATION: B.Sc DEGREE EXAMINATION COLLEGE: SCEINCE AND TECHNOLOGY SCHOOL: NATURAL AND APPLIED SCIENCES DEPARTMENT: COMPUTER AND INFORMATION SCIENCES SESSION: 2014/2015 SEMESTER: ALPHA COURSE CODE: CSC 314 CREDIT UNIT: 2 Units COURSE TITLE: THEORY OF COMPUTING INSTRUCTION: ANSWER QUESTION 1 AND ANY OTHER TWO Time: 2 Hours 1. (a) What is a regular grammar

(5marks) (b) Consider the grammar G where Vn = {S,B}, Vt = a, b, c, S is the start symbol, and P consists of : 1. S → aBSc 2. S → abc 3. Ba → aB 4. Bb → bb (i) Formulate a derivation of strings in L(G) = aaabbbccc from the grammar G (3 marks)

(ii) Describe the rule path for the expression (2 marks) (c) Determine the outcome of the following operations (5 marks) (i) |1001100|

(ii) || (iii) if w = computerscience, what is w(7) (iv) 11010 o 111011 (v) computerscienceR

(d) Draw a nondeterministic finite automaton for (01)*01(0110*)*11* (5marks)

(e) Give the regular expressions best describe the following languages. = {0, 1}. (5marks) (i) {w : w contains at least two 1s and at most one 0}, (ii) {w : w contains an even number of 0s and exactly two 1s}. (iii) {w : w contains exactly two 0s and at least one 1s}. (iv) {w : w contains an even number of 0s and each 0 is followed by at least one 1}. (v) {w : every odd position in w is 1}.

2. (a) Define a DFA machine (5 marks)

Page 94: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

93

(b) When a car arrives at the toll gate, the gate is closed. The gate opens as soon as the driver has

payed 25 naira. We assume that we have only four naira denominations: 5, 10, and 25 naira. We

also assume that no excess change is returned. After having arrived at the toll gate, the driver

inserts a sequence of coins into the machine which determine if is opened or not. In order to

decide this, the machine is in one of the following six states, at any moment during the process:

The machine is in state q0, if it has not collected any money yet.

The machine is in state q1, if it has collected exactly 5 naira.

The machine is in state q2, if it has collected exactly 10 naira.

The machine is in state q3, if it has collected exactly 15 naira.

The machine is in state q4, if it has collected exactly 20 naira.

The machine is in state q5, if it has collected 25 naira or more.

(i) Define a DFA machine for the specification (2 marks) (ii) Show the transition table (2

marks) (iii) Determine if the sequence of 5, 5, 10, 10 naira can open the gate (5

marks) (iii) Draw DFA transition graph (6

marks)

3. (a) Define NFA machine (5marks) (b) Given a Nondeterministic (NFA) machine shown below, answer the following: (i) Define a Non deterministic fine automaton for the machine (ii) Show the NFA transition table

(ii) Define a Deterministic finite automaton (DFA) for the machine, show the ,Q, q and F (iii) Show the DFA transition table

4. (a) Differentiate between the following pairs with an example each

(i) * and + (3marks) (ii) Prefix and Suffix (3marks)

Page 95: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

94

(b) Constructing an NFA that accepts the language described by this regular expression below to prove that the regular expression describes a regular language.

(i) (a* (ab)*)* (7marks) (ii) (a | b | c) * d (e+) f (7marks)

5. (a) Define a deterministic pushdown automaton (5marks)

(b) Consider the deterministic finite automaton M = (Q,, δ, q0, F), where Q ={q0, q1, q2}, =

{a, b}, q0 is the start state, F = {q2}, and δ is given in the state diagram below. Show how

to obtain the regular expression that describes the language accepted by M using this

lemma: Let be an alphabet, and let B,C and L be languages in * such that B and L =

BL C. Then L = B*C (15marks)

Page 96: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

95

MARKING SCHEME 1. (a) What is a regular grammar?

(5marks) (b) Consider the grammar G where Vn = {S, B}, Vt = a, b, c, S is the start symbol, and P consists of: 1. S → aBSc 2. S → abc 3. Ba → aB

Page 97: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

96

4. Bb → bb (i) Formulate a derivation of strings in L(G) = aaabbbccc from the grammar G (3 marks)

(ii) Describe the rule path for the expression (2 marks) (c) Determine the outcome of the following operations (5 marks) (i) |1001100|

(ii) || (iii) if w = computerscience, what is w(7) (iv) 11010 o 111011 (v) computerscienceR

(d) Draw a nondeterministic finite automaton for (01)*01(0110*)*11* (5marks)

(e) Give the regular expressions best describe the following languages. = {0, 1}. (5marks) (vi) {w : w contains at least two 1s and at most one 0}, (vii) {w : w contains an even number of 0s and exactly two 1s}. (viii) {w : w contains exactly two 0s and at least one 1s}. (ix) {w : w contains an even number of 0s and each 0 is followed by at least one 1}. (x) {w : every odd position in w is 1}.

2. (a) Define a DFA machine (5 marks)

(b) When a car arrives at the toll gate, the gate is closed. The gate opens as soon as the driver has

payed 25 naira. We assume that we have only three naira denominations: 5, 10 and 25 naira. We

also assume that no excess change is returned. After having arrived at the toll gate, the driver

inserts a sequence of coins into the machine which determine if is opened or not. In order to

decide this, the machine is in one of the following six states, at any moment during the process:

The machine is in state q0, if it has not collected any money yet.

The machine is in state q1, if it has collected exactly 5 naira.

The machine is in state q2, if it has collected exactly 10 naira.

The machine is in state q3, if it has collected exactly 15 naira.

The machine is in state q4, if it has collected exactly 20 naira.

The machine is in state q5, if it has collected 25 naira or more.

(i) Define a DFA machine for the specification (2 marks) (ii) Show the transition table (2

marks) (iii) Determine if the sequence of 5, 5, 10, 10 naira can open the gate (5

marks) (iv) Draw DFA transition graph (6

marks)

Page 98: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

97

3. (a) Define NFA machine (5marks) (b) Given a Nondeterministic (NFA) machine shown below, answer the following: (i) Define a Non deterministic fine automaton for the machine (ii) Show the NFA transition table

(iii) Define a Deterministic finite automaton (DFA) for the machine, show the , Q, q and F (iv) Show the DFA transition table

4. (a) Differentiate between the following pairs with an example each

(i) * and + (3marks) (ii) Prefix and Suffix (3marks) (b) Construct an NFA that accepts the language described by this regular expression below to prove

that the regular expression describes a regular language.

(i) (a* (ab)*)* (7marks) (ii) (a | b | c) * d (e+) f (7marks)

5. (a) Define a deterministic pushdown automaton (5marks)

Page 99: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

98

(b) Consider the deterministic finite automaton M = (Q,, δ, q0, F), where Q ={q0, q1, q2}, =

{a, b}, q0 is the start state, F = {q2}, and δ is given in the state diagram below. Show how

to obtain the regular expression that describes the language accepted by M using this

lemma: Let be an alphabet, and let B,C and L be languages in * such that B and L =

BL C. Then L = B*C (15marks)

Marking Guide 1(a) A regular grammar is a grammar whose production (rewrite rule) rules conform to the following restrictions:-

The left side of any production rule in a regular grammar must consist of a single nonterminal.

The right side must be a terminal followed by a nonterminal, or a single terminal, or an empty string.

1(b) (i) S → aBSc → aBaBScc (1) → aBaBabccc (2) → aaBBabccc (3) → aaBaBbccc (3) → aaaBBbccc (3) → aaaBbbccc (4) → aaabbbccc (4) 1(b) (ii) The rule path is sequential starting from (1) all the way through to (4) 1(c) (i) 7 (ii) 0 (iii) e

Page 100: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

99

(iv) 11010111011 (v) ecneicsretupmoc 1(d)

1(e) (i) 11+0 U 101+ U 011+ (ii) 1(00)*1 U 11(00)* U (00)*11 (iii) 001+ U 01+0 U 1+00 (iv) (01+01+)* (v) (10)* 2 (a) A DFA machine is a five-tuple M = (Q, Σ, δ, q0, F) where 1. Q is a finite set, whose elements are called states,

2. is a finite set, called the alphabet ; the elements of are called symbols, 3. δ : Q × ∑ → Q is a function, called the transition function, 4. q0 is an element of Q; it is called the start state, 5. F is a subset of Q; the elements of F are called accept states. 2 (b) (i) Q = {q0, q1, q2, q3, q4, q5}, ∑ = {5, 10, 25},

0 1

0 1 1

1

1

0, 1

0,

Page 101: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

100

q0 is the start state F = {q5}, and δ is given by the following table: 2 (b) (ii)

2 (b) (iii) The sequence 5, 5, 10, 10 has the following transition δ (q0, 5) = q1 δ (q1, 5) = q2 δ (q2, 5) = q4 δ (q4, 5) = q5 The sequence opens the gate because the final state after the transition is the accept state. 2 (b) (iv)

3 (a) A nondeterministic finite automaton (NFA) is a 5-tuple M = (Q, , δ, q, F), where 1. Q is a finite set, whose elements are called states,

Page 102: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

101

2. ∑ is a finite set, called the alphabet; the elements are called symbols, 3. δ : Q × ∑ → P(Q) is a function, called the transition function, 4. q is an element of Q; it is called the start state, 5. F is a subset of Q; the elements of F are called accept states. 3 (b) (i) Q = {1, 2, 3, 4, 5} ∑ = {0, 1} q is state 1 F = {4} 3 (b) (ii)

0 1

1 {5} {2, 5}

2 {2} {2, 3}

3 {4} {4}

4 {4} {3}

5 {3} {4}

3 (b) (iii) DFA M = (Q’, ∑, δ’, q’, F’) Q’ = P(Q) = {Ø, 1, 2, 3, 4, 5, {1,2}, {1,3}, {1,4}, {1,5}, {2,3}, {2,4}, {2,5}, {3,4}, {3,5}, {4,5}, {1,2,3}, {1,2,4}, {1,2,5}, {1,3,4}, {1,3,5}, {1,4,5}, {2,3,4}, {2,3,5}, {2,4,5}, {3,4,5}, {1,2,3,4}, {1,2,3,5}, {1,2,4,5}, {1,3,4,5}, {2,3,4,5}, {1,2,3,4,5}} ∑ = {0, 1} q’ = {1} F’ = {4, {1,4}, {2,4}, {3,4}, {4,5}, {1,2,4}, {1,3,4}, {1,4,5}, {2,3,4}, {2,4,5}, {3,4,5}, {1,2,3,4}, {1,2,4,5}, {1,3,4,5}, {2,3,4,5}, {1,2,3,4,5}}

0 1

Ø Ø Ø

1 {5} {2,5}

Page 103: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

102

2 {2} {2,3}

3 {4} {4}

4 {4} {3}

5 {3} {4}

{1,2} {2,5} {2,3,5}

{1,3} {4,5} {2,4,5}

{1,4} {4,5} {2,3,5}

{1,5} {3,5} {2,4,5}

{2,3} {2,4} {2,3,4}

{2,4} {2,4} {2,3}

{2,5} {2,3} {2,3,4}

{3,4} {4} {3,4}

{3,5} {3,4} {4}

{4,5} {3,4} {3,4}

{1,2,3} {2,4,5} {2,3,4,5}

{1,2,4} {2,4,5} {2,3,5}

{1,2,5} {2,3,5} {2,3,4,5}

{1,3,4} {4,5} {2,3,4,5}

{1,3,5} {3,4,5} {2,4,5}

{1,4,5} {3,4,5} {2,3,4,5}

{2,3,4} {2,4} {2,3,4}

{2,3,5} {2,3,4} {2,3,4}

{2,4,5} {2,3,4} {2,3,4}

{3,4,5} {3,4} {3,4}

Page 104: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

103

{1,2,3,4} {2,4,5} {2,3,4,5}

{1,2,3,5} {2,3,4,5} {2,3,4,5}

{1,2,4,5} {2,3,4,5} {2,3,4,5}

{1,3,4,5} {3,4,5} {2,3,4,5}

{2,3,4,5} {2,3,4} {2,3,4}

{1,2,3,4,5} {2,3,4,5} {2,3,4,5}

4 (a) (i) ∑* denotes the set of all sequences of strings that are composed of zero or more symbols of ∑. For example if ∑ = {a} then ∑* = {ε, a, aa, aaa, …} ∑+ denotes the set of all sequences of strings composed of one or more symbols of ∑. For example if ∑ = {a} then ∑+ = {a, aa, aaa, …} 4 (a) (ii) If w = vy for some y, then v is a prefix of w. For example “road” is a prefix of roadrunner If w = xv for some x, then v is a suffix of w. For example “road” is a suffix of abroad 4 (b) (i) (a* U (ab)*)*

ε

ε

ε

ε

a

a ε b

Page 105: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

104

5 (a)

A deterministic pushdown automaton is a 5-tuple M = (, , Q, , q), where

1. is a finite set, called the tape alphabet ; the blank symbol is not contained in ,

2. is a finite set, called the stack alphabet; this alphabet contains the special symbol $, 3. Q is a finite set, whose elements are called states, 4. q is an element of Q; it is called the start state, 5. δ is called the transition function, which is a function

δ : Q × ( U {} ) × → Q × {N,R} × *.

ε

a

b

c

d ε f

ε

ε

Page 106: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

105

5 (b)

In the third equation, Lq2 is expressed in terms of Lq0 and Lq1. Hence, if we substitute the third equation into the first equation, then we get Lq0 = a.Lq0 U b . ( U a · Lq1 U b · Lq0) = (a U bb) · Lq0 U ba · Lq1 U b. We obtain the following set of equations.

Let L = Lq1, B = b, and C = a · Lq0. Then ∈ B and the second equation reads L = BL U C. Hence, by the

Lemma, Lq1 = L = B*C = b*a · Lq0 If we substitute Lq1 into the first equation, then we get Lq0 = (a U bb) . Lq0 U ba · b*a · Lq0 U b = (a U bb U bab*a)Lq0 U b. Again applying the Lemma, this time with L = Lq0 , B = a U bb U bab*a and C = b, gives Lq0 = (a U bb U bab*a)*b. Thus, the regular expression that describes the language accepted by M is (a U bb U bab*a)* b.

Page 107: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

106

COVENANT UNIVERSITY

CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA.

B.Sc EXAMINATION

COLLEGE: Science & Technology

DEPARTMENT: Computer & Information Sciences

SESSION:2015/2016 SEMESTER:Alpha COURSE CODE:CSC315 CREDIT UNIT:2

COURSE TITLE: Computer Programming and Organisation

INSTRUCTION: Attempt Three (3) Questions in ALL, One (1) Question from section A

and Two (2) Questions from Section B. TIME: 2 HOURS

SECTION A

Question One 9 marks

a. For the assembly language program below, calculate how long it will take to execute on a regular

(non-pipelined) and (pipelined) architecture. Assume that: (i) Pipeline contains 5 stages: IF, ID,

EX, M and W; (ii) 1st stage requires 6 seconds to execute, 2nd stage= 1st stage minus 2, 3rd stage

=1st stage plus 2nd stage, 4th stage=1 stage plus 1, 5th stage=7 secs. Show timing diagram and

calculations.

LDA T1, A

LDA T2, B

SUB T1, T2

MUL T1, 2

b. i. List and explain the sequence of micro operations for the Fetch circle. 4 marks

ii. Convert the statement below to its equivalent assembly language code:

IF AL == CH THEN C=C+1 4 marks

iii. Define RISC and CISC. Give one type of system each that uses the RISC and CISC

technology. 4 marks

c. For 5 instruction program segment, calculate how long it will take to execute on a regular (non-

pipelined) and (pipelined) architecture. Assume that: (i) Pipeline contains 5 stages: FI, DI, CE,

EI and WI; (ii) First stage requires 6 seconds to execute and subsequent stages respectively

decreasing by minus 3 to execute. Show timing diagram and calculations. (9 mks)

Question Two

a. Use a one address, two address and three address instruction format to write a Pentium 4

assembly language program segment for the equation below: 9 marks

X = (W+X)(Y+Z)

Page 108: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

107

b. Use Table 1 to answer the questions in this section.

Memory

Address

Memory

Content

Memory

Address

Register

Content

2 16 4 2

4 300 6 60

6 10 8 54`

8 2 10 6

10 4 12 88

Table 1

i. LDA 670 ;670 is neither a memory address nor a register address (6 mks)

ii. ADD (Y2) ;assume Y2 = 6 and Y2 is address of memory (6 mks)

For each of the instruction(s) listed above, determine the:

(i) value of the operand (ii) addressing mode

c. For 5 instruction program segment, calculate how long it will take to execute on a regular (non-

pipelined) and (pipelined) architecture. Assume that: (i) Pipeline contains 5 stages: FI, DI, CE,

EI and WI; (ii) First stage requires 6 seconds to execute and subsequent stages respectively

decreasing by minus 3 to execute. Show timing diagram and calculations. (9 mks)

SECTION B

Question Three

a i. State the difference between Computer Architecture and Computer Organization? 3 marks

ii. Explain the stored program concept of John Von Neumann and state two significant aspects of it.

4 marks

b. Discuss the concept of Abstraction in understanding the architecture and organization of

a computer. Give examples of both hardware and software abstractions. 3 marks

c i. Use only NAND gates to represent expressions as circuit diagrams: 5 marks

i) x + y ii) x.y

ii. Find the minimum sum-of-products expression represented by the K-maps below. d =

‘don’t care’ That means take ‘d’ as 0 or 1 as convenient. 5 marks

i.

ii)

Question Four

1 d

1 1 d

1 1 d

d

X3X4

X1X2

00 01 11 10

00 01 11

10

Page 109: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

108

a. Use the following statement to discuss the various types or levels of computer memory -

“Cost of memory unit depends on its access time and proximity to the processor” 4 marks

b i. What do you understand by Overflow and Underflow in data representation? Give very

clear examples. 2 marks

ii. What value (decimal and binary) will be stored in an 8-bit register as the result of the

calculations below?

i) 154 + 143 ii) 35 X 16 (change all values to binary first) 5 marks

c.i Discuss the representation on signed integers in a computer. Give very clear examples. 6 marks

ii. State the range of values that can be stored using 8 bits for each representation in (i)

above 3 marks

Question Five

ai. What do you understand by End-Around Carry? Illustrate this concept using 28+ (-25)

in an 8-bit register. 3 marks

ii. State whether the following values are correct or not i) 11233 ii) 2345

iii)37589 iv) 12212 2 marks b. Perform the calculation below in Single Precision IEEE format. All bits after the first 12

bits of mantissa should be 0. Leave your answer in hexadecimal form. All calculations

must be in binary. 452.35 – 231.45 6 marks

ci. Calculate the memory requirement of an image whose dimension is 15.45 inches by

8.25 inches at resolution 300 dpi (dots per inch). Express your answer in megabyte

3 marks

ii. By using the reverse of the IEEE Single Precision procedure, determine the decimal value

of the following represented value: C4240266H 6 marks

Page 110: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

109

CSC315 MARKING SCHEME

SECTION A

Question One 15 marks

a. For the assembly language program below, calculate how long it will take to execute on a regular

(non-pipelined) and (pipelined) architecture. Assume that: (i) Pipeline contains 5 stages: IF, ID, EX,

M and W; (ii) 1st stage requires 5 seconds to execute, 2nd stage= 1st stage minus 2, 3rd stage =1st

stage plus 2nd stage, 4th stage=1 stage plus 1, 5th stage=15 secs. Show timing diagram and

calculations.

LDA T1, A

LDA T2, B

SUB T1, T2

JLZ K1

MUL T1, 2

MUL T2, 3

Solution

b. List and explain the sequence of micro operations for the Fetch circle. 5 marks

Solution

Let us look at the sequence of events for the fetch cycle from the point of view of its effect on

the processor registers. An example appears in figure 4.2.

At the beginning of the fetch cycle, the address of the next instruction to be executed is in the

PC, in this case, the address is 1100100. The first step is to move that address to the memory

address lines of the system bus. The second step is to bring the Control Unit, issues a READ

command on the control bus, and the result appears on the data bus and is copied into the

memory buffer register (MBR). We also need to increment the PC by 1 to get ready for the next

instruction. Because these two actions (read word from memory, add 1 to PC) do not interfere

with each other, we can do them simultaneously to save time.

The third step is to move the contents of the MBR to the instruction register (IR), this frees up

the MBR for use during a possible indirect cycle. Thus, the simple fetch cycle actually consists

of 3 steps and 4 micro-operations. Each micro-operations involves the movement of data into or

out of register. So long as these movements do not interfere with one another, several of them

can write this sequence of events as follows

T1:MAR (PC)

T2:MBR MEMORY

Page 111: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

110

PC PC + I

T3: IR (MBR)

Where I is the instruction length. We need to make several comments about this sequence. We

assume that a clock is available for timing purposes and that it emits regularly spaced clock

pulses. Each clock pulse defines a time unit. Thus, all time units are of equal duration. Each

micro-operation can be performed within the time of a single time unit. The notation (T1,T2,T3)

represents successive time units. In words, we have

First time unit: move contents of PC to MAR

Second time unit: move contents of memory location specified by MAR to MBR. Increment by I

the content of the PC.

Third time unit: move contents of MBR to IR.

MAR

MBR

PC 0000000001100100

IR

AC

(a) Beginning

MAR 0000000001100100

MBR

PC 0000000001100100

IR

AC

(b) First step

MAR 0000000001100100

MBR 0001000000100000

PC 0000000001100100

IR

AC

(c) Second step

MAR 0000000001100100

MBR 0001000000100000

PC 0000000001100100

IR 0001000000100000

AC

(d) Third step

c. i.) Convert the statement below to its equivalent assembly language code:

IF AL == CH THEN C=C+1; 5 marks

Solution

cmp( al, ch );

jne SkipIncCL;

Page 112: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

111

inc( c );

SkipIncCL:

ii) Define RISC and CISC. Give one type of system each that uses the RISC and CISC

technology. 5 marks

Solution

Definition of CISC:

— Large number of predefined instructions making high level programming

languages easy to design and implement.

— Supports microprogramming to simplify computer architecture

E.g. Intel Pentium Processor

Definition of RISC

— Limited and simple instruction set

— Large number of general purpose registers or use of compiler technology to

optimize register use.

— Emphasis on optimising the instruction pipeline

E.g. Motorola Processor

Question Two

a. Use a one address, two address and three address instruction format to write a Pentium 4

assembly language program segment for the equation below: 5 marks

K = (W+X)(Y+Z)

Solution

One address instruction

LDA W

ADD X

STA A

LDA Y

ADD Z

MUL A

STA K

Two address instruction

MOV T1, W

ADD T1, X

MOV K, Y

ADD X, Z

MUL X, T1

Three address instruction

ADD T1, W, X

ADD T2, Y, Z

MUL X, T1, T2

Page 113: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

112

b. Use Table 1.0 to answer the questions in this section.

Address Memory Address Register

2 16 4 2

4 300 6 60

6 20 8 54`

8 2 10 6

10 4 12 88

Table 1.0

i. LDA 670 ;670 is neither a memory address nor a register address (5 mks)

ii. ADD Y2 ;assume Y2 = 6 and Y2 is address of memory (5 mks)

For each of the instruction(s) listed above, determine the:

(i) value of the operand (ii) addressing mode

Solution

i. LDA 670 ;670 is neither a memory address nor a register address

Solution

Operand is 670, Addressing mode is Immediate addressing

ii. ADD Y2 ;assume Y2 = 6 and Y2 is address of memory

Solution

Operand is 20, Addressing mode is direct addressing

c. For 5 instruction program segment, calculate how long it will take to execute on a regular (non-

pipelined) and (pipelined) architecture. Assume that: (i) Pipeline contains 5 stages: IF, ID, EX,

M and W; (ii) First stage requires 5 seconds to execute and subsequent stages respectively

decreasing by minus 3 to execute. Show timing diagram and calculations. (15 mks)

Solution

IF= 5 secs, ID= 8 Secs, EX= 11 Secs, M = 14 secs, W= 17 secs

Non-

Pipelined

Sec 5 8

1

1

1

4

1

7 5 8

1

1

1

4

1

7 5 8

1

1

1

4

1

7 5 8

1

1

1

4

1

7 5 8

1

1

1

4

1

7

Instr

uctio

n 1

I

F

I

D

E

X M W

Instr

uctio

n 2

I

F

I

D

E

X M W

Instr

uctio

n 3

I

F

I

D

E

X M W

Page 114: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

113

Instr

uctio

n 4

I

F

I

D

E

X M W

Instr

uctio

n 5

I

F

I

D

E

X M W

Pipeline

d

Sec 5 8

1

1

1

4

1

7

1

7

1

7

1

7

1

7

Instr

uctio

n 1

I

F

I

D

E

X M W

Instr

uctio

n 2

I

F

I

D

E

X M W

Instr

uctio

n 3

I

F

I

D

E

X M W

Instr

uctio

n 4

I

F

I

D

E

X M W

Instr

uctio

n 5

I

F

I

D

E

X M W

Non pipelined = 275 secs

Pipelined = 123 secs

Page 115: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

114

COVENANT UNIVERSITY CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA. TITLE OF EXAMINATION: B.Sc DEGREE EXAMINATION

COLLEGE: SCEINCE AND TECHNOLOGY

SCHOOL: NATURAL AND APPLIED SCIENCES

DEPARTMENT: COMPUTER AND INFORMATION SCIENCES

SESSION: 2014/2015 SEMESTER:

ALPHA

COURSE CODE: CSC 315 CREDIT

UNIT: 2 Units

COURSE TITLE: COMPUTER ARCHITECTURE AND ORGANIZATION

INSTRUCTION: ATTEMPT QUESTION ONE AND ANY OTHER TWO Time:

2 Hours

1a. For 5 instruction program segment, calculate how long it will take to execute on a regular

(non-pipelined) and (pipelined) architecture. Assume that: (i) Pipeline contains 5 stages: IF,

ID, EX,

M and W; (ii) First stage requires 5 seconds to execute and subsequent stages respectively

decreasing by minus 3 to execute. Show timing diagram and calculations. (10 mks)

b. Convert each of the instruction to its equivalent assembly language code:

IF( AL == CH ) THEN C=C+1; ENDIF; (10 mks)

c. Use Table 1.0 to answer the questions in this section.

Address Memory

1

Address Memory

2

Address Register 1

0 16 2 16 4 2

2 2 4 300 6 60

4 20 6 20 8 54`

6 21 8 2 10 6

8 80 10 4 12 88

Table 1.0

i. LDA 670 ;670 is neither a memory address nor a register address (3 mks)

ii. ADD Y2 ;assume Y2 = 6 and Y2 is address of memory 1 (3 mks)

iii. LDA (A) ;assume A = 10 and A is address of register 1 (4 mks)

For each of the instruction(s) listed above, determine the:

(i) value of the operand (ii) addressing mode

2a) a. What is the logical expression shown by the following gate circuits? Fig 1.

Page 116: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

115

ii)

(3 mks) b. State the Boolean functions that can be used to describe the following situations.

(Assume “closed” means “true” or 1 and “open” means “false” or 0)

Provide answers for ii. to v. below

i) Example: There is an output Q when switch A is closed and either switch B or switch C is

closed.

Answer is: Q=A (B+C)

ii) There is an output Q when either switch A or switch B is closed and either switch C or switch

is closed. (½ mks)

iii) There is an output Q when either switch A is opened or switch B is closed. (½ mks)

iv) There is n output Q when switch A is opened and switch B is closed. (½ mks)

v) There is an output Q when either switch A or switch B is closed or either switch C or switch

D is open. (½ mks)

b. i) Describe the stored program concept of Von Neumann

(2½ mks) ii) Highlight the significant aspects of the stored-program concept. (2½

mks) c. Calculate the memory requirement of an image whose dimension is 13.3 inches by

7.5 inches at resolution is 250 dpi (dots per inch). Express your answer in MB (5 mks)

d. i) Explain with examples the various representations used for signed integers (2½

mks)

ii) Show how there are two representations of Zero in S-M and 1’s Complement (2½

mks)

3a. What is the range of POSITIVE and NEGATIVE numbers that can be represented in a

16-bit register using Sign-Magnitude, 1’s complement and 2’s complement.

(5 mks) b. Complete the table below. All values should be 10 – bits (show details of work) (5

mks)

Decimal Unsigned Sign-

Magnitude

1’s

Complement

2’s

Complement

170

-252

A

B C

D

Y

A

B

C

D

X

Page 117: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

116

c. What do you understand by End-Around Carry? Illustrate this concept using 15 + (-13)

in an 8-bit register.

(5 mks) d. i) How are Binary, Octal, and Hexadecimal numbers related? Use 1044.12510 to show

how they are related.

(5 mks)

4a. i) What do you understand by RTL? ii) What are Micro-operations? (5

mks)

b. Represent the decimal number -1630.03125 in the IEEE Single Precision Floating Point

format. Leave your final answer as Hexadecimal.

(5 mks) c. What are the major differences between DRAM and SRAM? (5

mks)

d. Discuss the characteristics of computer memory under the following

i) Access Methods ii) Performance iii) Physical characteristics (5

mks)

5a. i) What do you understand by functionally complete sets of gates in Digital logic? (2½

mks) ii) Use only NOR to draw the logic network for a 2-variable AND gate (2½

mks) b. Explain the following as they relate to cache memory i) Cache Miss ii) Cache Coherence

iii) Locality Principle iv) Mapping Function (5

mks) c. Express C2600606h as a floating point number based on the IEEE Single Precision

format(5 mks)

d. i) What do you understand by Overflow in an arithmetic operation? ii) What will be

displayed (in binary and decimal) as the sum of 214 and 65 using an 8-bit register? Show

details of work? (5 mks)

Page 118: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

117

COVENANT UNIVERSITY, OTA

COLLEGE OF SCIENCE AND TECHNOLOGY

DEPARTMENT OF COMPUTER & INFORMATION SCIENCES

Alpha Semester B.Sc (Hons) Examination 2014/2015 Academic Session

CSC 315: COMPUTER ARCHITECTURE AND ORGANIZATION (2

Units)

INSTRUCTIONS: ANSWER QUESTION ONE AND ANY OTHER TWO (2

Hrs)

MARKING SCHEME

2a) What is the logical expression shown by the following gate circuits? Fig 1.

ii)

3 mks

Solution

(i) A B+B C DX

(ii) A (B C) (C D) DY

b. State the Boolean functions that can be used to describe the following situations.

(Assume “closed” means “true” or 1 and “open” means “false” or 0)

Provide answers for ii. to v. below

Solution

i) There is an output Q when switch A is closed and either switch B or switch C is closed.

Solution: Q=A (B+C)

ii) There is an output when either switch A or switch B is closed and either switch C or switch D

is closed. .

(½ mks) Q=(A+B) (C+D)

iii) There is an output when either switch A is opened or switch B is closed. . (½

mks)

Q=A+B

iv) There is an output when switch A is opened and switch B is closed. . (½

mks)

Q=A B

A

B C

D

Y

A

B

C

D

X

Page 119: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

118

v) There is an output when either switch A or switch B is closed or either switch C or switch D

is open.

. (½ mks)

bi) Describe the stored program concept of Von Neumann (2 ½

mks)

A stored program concept is one in which first the program and data are stored in the Main

memory and then the processor fetches instructions and executes them, one after another.

bii) Highlight the significant aspects of the stored-program concept. (2½

mks)

1) It allows programs to be easily stored and loaded into the machine (processor) from

the main memory. Same set of control signal (s) for the instructions and data fetch. Once

a program has been developed and debugged, the numbers that represent its instructions

can be written out onto a storage device, allowing the program to be loaded back into

(main) memory at some point in the future

2) Allows programs to treat themselves or other programs as data. This aspect

facilitates compilers, debuggers and programming tools designing. Most computers in use

today are stored-program computers. They represent programs as numbers that are

stored in the same address space as data as in the case of von Neumann architecture.

c. Calculate the memory requirement of an image whose dimension is 15.36 inches by

10.24 inches at resolution is 250 dpi (dots per inch). Express your answer in MB (5

mks)

Solution:

Length: (15.36 x 250) pixels = 3840 pixels

Breadth: (10.24 x 250) pixels = 2560 pixels

Total no. of pixels = 3840 x 2560

= 9,830,400 pixels

But 1 bit = 1 pixel and 8 bits = 1 byte,

Page 120: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

119

9830400/ 8 = 1228800 bytes

1024 Bytes = 1 KB 1228800 / 1024 = 1200 KB

1024 KB = 1 MB 1200 / 1024 = 1.17 MB

d. i) Explain with examples the various representations used for signed integers (2 ½

mks)

Sign-Magnitude

Use 1 bit of integer to represent the sign of the integer

Sign bit of 0 for positive, 1 for negative.

The rest of the integer is a magnitude, using same encoding as unsigned integers.

The hardware that does arithmetic on sign magnitude integers is not fast. It is more

complex than the hardware that does arithmetic on 1's comp. and 2's comp. integers.

range: - (2(n-1)) + 1 to 2(n-1) -1, where n is the number of bits

Example:

o To write 57 and -38 using 8-bit register in sign-magnitude

representation.

57 in binary = 0 0 1 1 1 0 0 12

For -38, first find +38 in binary and then flip the last bit (sign bit)

38 in binary = 0 0 1 0 0 1 1 02

-38 in binary = 1 0 1 0 0 1 1 02

1’s complement

This is another method used in representing negative numbers.

The ones' complement form of a negative binary number is the bitwise NOT applied

to the "complement" of its positive counterpart. That is, negation (finding an

additive inverse) is done by taking a bitwise complement of the positive

representation.

Like sign-and-magnitude representation, ones' complement has two representations

of 0: 00000000 (+0) and 11111111 (−0).

positive integers use the same representation as unsigned.

The range of signed numbers using ones' complement is represented by

−(2N−1−1) to (2N−1−1) and ±0 where N is the number of bits

Example

The ones' complement form of 00101011 (4310) becomes 11010100 (−4310).

2’s complement

This solves the problems of multiple representations of 0 and the need for the end-

around carry found in One’s complement.

In 2's complement, negative numbers are represented by the bit pattern which is

one greater (in an unsigned sense) than the ones' complement of the positive

value.

Example:

Page 121: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

120

o What decimal value does the two's complement 110011 represent?

o It must be a negative number, since the most significant bit is a 1.

Therefore, find the additive inverse:

110011 (2's comp. ?)

001100 (after taking the 1's complement)

+ 1

----------

001101 (2's comp. +13)

Therefore, its additive inverse (110011) must be -13.

dii) Show how there are two representations of Zero in S-M and 1’s Complement (2 ½

mks)

In Sign Magnitude representation, because of the sign bit, there are 2 possible

representations for 0. This is a problem for hardware. For example given a 4-bit

representation of zero as follows:

In S-M, 0 sign bit (msb) signifies positive number and 1 sign bit (msb) signifies

negative number. So we have

0000 (+0)

1000 (-0) = 0

The computer must do all calculations such that they come out correctly and the same

whichever representation is used.

The same is obtained for 1’s complement. For example given 8-bit representation for

zero,

0 sign bit represents positive number and 1 represents negative number. However, the

sign bits are part of the magnitude of the number.

00000000 (+0)

11111111 (−0) when all the bits are complemented (1’s complement of Zero)

2b. What is the range of POSITIVE and NEGATIVE numbers that can be represented in a

16-bit register using Sign-Magnitude, 1’s complement and 2’s complement.

(5 mks)

i) Sign Magnitude

The range of integers for sign-magnitude is given by the formula

- (2(n-1)) + 1 to 2(n-1) -1, where n is the number of bits

So for 16 bits we have

Page 122: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

121

-(2(16-1)) + 1 to 2(16-1) – 1

-(2(15)) + 1 to 2(15) – 1

-32,768 + 1 to 32,768 – 1

-32767 to 32767

ii) 1’s Complement

The range of integers for 1’s complement is given by the formula

−(2n-1 −1) to (2n-1 −1) and ±0 where n is the number of bits

So for 16 bits we have

-(2(16-1)) - 1 to 2(16-1) – 1

-(2(15)) - 1 to 2(15) – 1

-32,768 - 1 to 32,768 – 1

-32769 to 32767

iii) 2’s Complement

The range of integers for 2’s complement is given by the formula

−(2n-1) to (2n-1 −1) where n is the number of bits

So for 16 bits we have

-(2(16-1)) to 2(16-1) – 1

-(2(15)) to 2(15) – 1

-32,768 to 32,768 – 1

-32768 to 32767

b. Complete the table below. All values should be 10 – bits (show details of work) (5

mks)

Page 123: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

122

Solution

Step1: Convert 170 and +252 to binary digits expressed in 10-bits

c. What do you understand by End-Around Carry? Illustrate this concept using 15 + (-13)

in an 8-bit register.

(5 mks)

Solution

This is a feature found in 1’s complement representation in which when adding two

numbers represented in the system, one does a conventional binary addition, but it is then

necessary to do an end-around carry by adding any resulting carry back into the resulting

sum.

Let consider the sum of 15 and (-13) using an 8-bit register.

1510 = 000011112

1310 =000011012 therefore (-13) in 1’s complement using 8-bit is 111100102

15 00001111 00000001

+(-13) 11110010 + 1

1 000000012 000000102 as required

15 + (-13) = 15 – 13 = 2

d. i) How are Binary, Octal, and Hexadecimal numbers related? Use 1044.12510 to show

how they are related.

(5 mks)

Decimal Unsigned Sign-Magnitude 1’s Complement 2’s Complement

170 00101011102 00101011102 00101011102 00101011102

-252 - 10101011102 11010100012 11010100102

170 /2 = 85 r 0

85/2 = 42 r 1

42/2 = 21 r 1

21/2 = 10 r 1

10/2 = 5 r 0

5/2 = 2 r 1

2/2 = 1 r 0

17010 = 00101011102 (in 10

bits)

252 /2= 126 r 0

126/2 = 53 r 0

53/2 = 26 r 1

26/2 = 13 r 0

13/2 = 6 r 1

6/2 = 3 r 0

3/2 = 1 r 1

25210 = 00010000012 (in 10 bits)

Page 124: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

123

Solution

Binary, Octal and Hexadecimal numbers are related in the following way:

i. To determine an octal number from a binary number, simply form groups of 3 bits

from

the binary number

ii. To determine an octal number from a binary number, simply form groups of 3 bits

from

the binary number

Given 1044.12510 express this first as Binary Number as follows:

Therefore 1044.12510 = 10000010100.0012

- For Octal value ( form groups of 3 bits from given binary value) as shown below:

010 000 010 100 . 001 = 2024.18

- For Hexadecimal value ( form groups of 4 bits from given binary value) as shown

below:

0100 0001 0100 . 0010 = 414.216

4a. i) What do you understand by RTL? ii) What are Micro-operations? (5mks)

Answer:

i) RTL (Register Transfer Language)

1044/2 = 522 r 0

522/2 = 261 r 0

261/2 = 130 r 1

130/2 = 65 r 0

65/2 = 32 r 1

32/2 = 16 r 0

16/2 = 8 r 0

8/2 = 4 r 0

4/2 = 2 r 0

2/2 = 1 r 0

104410 = 100000101002

0.125 x 2 = 0.25

0.25 x 2 = 0.5

0.5 x 2 = 1.0

0.12510 = .0012

Page 125: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

124

A symbolic notation to describe the micro-operation transfers among registers.

ii) Micro-operations

Operations executed on data stored in one or more registers. An example is a shift

right (shr) operation. For any function of the computer, a sequence of micro-

operations is used to describe it. The result of the operation may be:

• replace the previous binary information of a register or

• transferred to another register

b. Represent the decimal number -1630.03125 in the IEEE Single Precision Floating

Point format. Leave your final answer as Hexadecimal.

(5 mks)

Solution

Step 1: convert the absolute value of the given decimal value to binary

Therefore 1630.0312510 = 11001011110.000012

Step 2: Express in Standard form

1.100101111000001 x 210

Step 3: Determine true and biased exponent

True exponent e = 10

Biased exponent e + 127 = 10 + 127 = 137

13710 in binary =

137/2 = 68 r 1

68/2 = 34 r 0

34/2 = 17 r 0

17/2 = 8 r 1

8/2 = 4 r 0

4/2 = 2 r 0

2/2 = 1 r 0

13710 = 100010012

0.03125 x 2 = 0.0625

0.0625 x 2 = 0.125

0.125 x 2 = 0.25

0.25 x 2 = 0.5

0.5 x 2 = 1.0

0.0312510 = .000012

1630/2 = 815 r 0

815/2 = 407 r 1

407/2 = 203 r 1

203/2 = 101 r 1

101/2 = 50 r 1

50/2 = 25 r 0

25/2 = 12 r 1

12/2 = 6 r 0

6/2 = 3 r 0

3/2 = 1 r 1

163010 = 110010111102

Page 126: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

125

Step 4: express in the IEEE Single Precision format:

SignBit Exponent Mantissa (fractional part)

SignBit = 1 because original number is Negative

Exponent = 10001001 (137)

Mantissa = 23 binary digits of fractional part

Sign Exponent Mantissa

1 10001001 10010111100000100000000

Binary Representation = 11000100110000111100000100000000

For Hexadecimal, we form groups of 4bits from the right as shown below:

1100 0100 1100 0011 1100 0001 0000 0000

This gives C4C3C100h in base 16

c. What are the major differences between DRAM and SRAM? (5

mks)

DRAM SRAM

• Bits stored as charge in capacitors

• Charges leak

• Need refreshing even when powered

• Simpler construction

• Smaller per bit

• Less expensive

• Need refresh circuits

• Slower

• Used for Main memory

• Bits stored as on/off switches

• No charges to leak

• No refreshing needed when powered

• More complex construction

• Larger per bit

• More expensive

• Does not need refresh circuits

• Faster

• Used for Cache

• Digital - uses flip-flops

d. Discuss the characteristics of computer memory under the following

i) Access Methods ii) Performance iii) Physical characteristics (5

mks)

Answer

i) Access Methods

This is based on the hardware implementation of the storage device

Four types

– Sequential • Start at the beginning and read through in order

• Access time depends on location of data and previous location of read-write

mechanism

• Example: tape

Page 127: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

126

– Direct • Individual blocks have unique address

• Access is by jumping to vicinity then performing a sequential search

• Access time depends on location of data within "block" and previous

location of read-write mechanism

• Example: hard disk

– Random • Individual addresses identify locations exactly

• Access time is consistent across all locations and is independent of previous

access

• Any location can be selected at random and directly addressed and accessed.

• Example: RAM

– Associative • Addressing information must be stored with data in a general data location

• A specific data element is located by comparing desired address with

address portion of stored elements

• Access time is independent of location or previous access

• Example: cache

ii) Performance

- Access time: time between "requesting" data and getting it • Random Access Method

– Time between putting address on bus and getting data.

– It's predictable.

• Other types, Sequential, Direct, Associative

– Time it takes to position the read-write mechanism at the desired location.

– Not predictable.

- Memory cycle Time:

- Primarily a RAM phenomenon

- Adds "recovery" time to cycle time (i.e. time taken before the next access)

Cycle time = access time + recovery time

- Transfer Rate: rate at which data can be moved (in or out)

RAM – Predictable; equals 1/(cycle time)

Non-RAM– Not predictable; equals

TN = TA + (N/R)

where

TN = Average time to read or write N bits

TA = Average access time

N = Number of bits

R = Transfer rate in bits per second

iii) Physical characteristics

• In a volatile memory, information decays naturally or is lost when electrical power

is switched off.

Page 128: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

127

• In a nonvolatile memory, information once recorded remains without deterioration

until deliberately changed; no electrical power is needed to retain information.

• Magnetic-surface memories are nonvolatile

• Semiconductor memory may be either volatile or nonvolatile.

• Non-erasable memory cannot be altered, except by destroying the storage unit e.g.

ROM

5a. i) What do you understand by functionally complete sets of gates in Digital logic?(2

½mks)

Functionally complete sets of gates are gate sets for which any Boolean function can be

implemented using only the gates in the set. The following are functionally complete sets:

AND, OR,NOT

AND,NOT

AND,OR

OR,NOT

NAND

NOR

ii) Use only NOR to draw the logic network for a 2-variable AND gate (2 ½

mks)

b. Explain the following as they relate to cache memory i) Cache Miss ii) Locality of

Reference iii) Mapping Function

(5 mks)

Cache Miss:

When a program accesses a memory location that is not in the cache, it is called a cache miss. Since

the processor then has to wait for the data to be fetched from the next cache level or from main

memory before it can continue to execute, cache misses directly influence the performance of the

application.

Locality of Reference:

This is a phenomenon describing the same value, or related storage locations, being frequently

Page 129: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

128

accessed. There are two basic types of reference locality – temporal and spatial locality.

Temporal

locality refers to the reuse of specific data, and/or resources, within a relatively small time

duration.

Spatial locality refers to the use of data elements within relatively close storage locations.

Mapping Function:

Mapping functions are used as a way to decide which main memory block occupies which line

of cache. As

there are less lines of cache than there are main memory blocks, an algorithm is needed to decide

this. Three

techniques are used, namely direct, associative and set associative, which dictate the

organization of the cache.

c. Express C2600606h as a floating point number based on the IEEE Single Precision format

(5mks)

Solution

Step 1: Express C2600606h as groups of four (4) bits for each digit of the base 16

value

C2600606H = 1100 0010 0110 0000 0000 0110 0000 0110

Step 2: Express the separated value in the IEEE Single Precision format

1 1000 0100 110 0000 0000 0110 0000 0110

Sign(1st bit) Exponent(next 8 bits) Mantissa (last

23 bits)

1 10000100 110 0000 0000 0110 0000

0110

Step 3: Determine the exponent and mantissa

i) Sign bit = 1 means a negative value

ii) E = 10000100 = 132, but this was biased-127

True exponent e = 132 – 127 = 5

iii) 1.m x 25

1. 11000000000011000000110 x 25 =

111000.000000011000000110………

Step 4: Determine the decimal value of 111000.000000011000000110……

This is estimated to be 56.?????

Page 130: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

129

d. i) What do you understand by Overflow in an arithmetic operation? ii) What will be

displayed (in binary and decimal) as the sum of 214 and 65 using an 8-bit register? Show

details of work? (5mks)

i) Overflow in data representation occurs when attempting to store a value in memory

or storage device and the number of bits required for the storage is short. For

instance trying to store a value that requires 10 bits in 8-bit register will lead to an

overflow error.

ii )Solution

Step1: Convert 214 and 65 to binary digits expressed in 8-bits

Step2: Add the two Binary values

11010110

+ 01000001

1 00010111

It is clear that if 8-bits are used for the calculation it will result in an overflow situation as

only 8 bits of the 9 bits can be represented. This is shown below:

1 0 0 0 1 0 1 1 1

The shaded part covers the 8-bits required for storage by the register. Therefore the

decimal value to be displayed is 000101112 = 2310 instead of 279

214 /2 = 107 r 0

107/2 = 53 r 1

53/2 = 26 r 1

26/2 = 13 r 0

13/2 = 6 r 1

6/2 = 3 r 0

3/2 = 1 r 1

21410 = 110101102

65 /2 = 32 r 1

32/2 = 16 r 0

16/2 = 8 r 0

8/2 = 4 r 0

4/2 = 2 r 0

2/2 = 1 r 0

6510 = 010000012

Page 131: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

130

COVENANT UNIVERSITY

CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA. TITLE OF EXAMINATION: B.Sc EXAMINATION

COLLEGE: College of Science and Technology

DEPARTMENT: Department of Computer and Information Sciences

SESSION: 2015/2016 SEMESTER: ALPHA

COURSE CODE: CSC 317 CREDIT UNIT: 2

COURSE TITLE: System Analysis & Design TIME: 2 HOURS

INSTRUCTION: Answer 2 questions in SECTION A and 1 question in SECTION B

SECTION A

1. (a) A system analyst developed the diagrams below while working on a Cap & Gown Ordering

System. Are there any errors in the diagrams? If yes, list them. (7 marks)

DF3

Student

Ship

Cap & Gown

0

Cap & Gown Ordering System

1

Validate

Order

3

Update

Inventory

2

Order

Finalization

Inventory D1

Inventory

Data

Formatted

Inventory Data Inventory Status

Student Shipping Order Receipt Cap & Gown

Info

Inventory D1

Formatted Inventory Data

Place Order Cap & Gown Info

EE1 EE2

P0

DF1

DF2 DF4

Receipt

Level-0 DFD

Context Diagram

Page 132: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

131

(b) Draw the Entity- Relationship Diagram (ERD) for the following scenario:

A salesperson may manage many other salespeople. A salesperson is managed by only

one salesperson. A salesperson can be an agent for many customers. A customer is

managed by one salesperson. A customer can place many orders. An order can be placed

by one customer. An order lists many inventory items. An inventory item may be listed

on many orders. An inventory item is assembled from many parts. A part may be

assembled into many inventory items. Many employees assemble an inventory item from

many parts. A supplier supplies many parts. A part may be supplied by many suppliers.

The ERD should show the cardinality. (71

/3 marks)

(c) In a school grading system, a teacher can record and update grades. Recording grades includes

saving them while updating grades includes loading and saving the grades. The system

administrator can generate report cards however these are distributed by a teacher. A teacher,

and administrator and a student can view grades, which includes logging in the system. Sketch

a Use Case diagram to depict this scenario.

Hint: Make use of the uses relationship. (6 marks)

(d) In process modelling, state which of the following pairs of symbols you are NOT permitted

to connect together using a data flow: (3 marks)

• Entity – Process

• Data store – Data store

• Entity – Data store

• Process – Process

• Entity – Entity

• Process - Data store

2. (a). Use concrete examples and diagrams to explain the concept of an Object and a Class.

Mention the difference between object and class diagrams. (31

/3 marks)

(b) Draw the Class diagram showing the Relationships and Multiplicities for the following

analysis information: (10 marks)

A Course is made-up of one Course Details (Course details is Course Unit, Title and

Course Description)

A Student can either be an Undergraduate or a Postgraduate

A Student can only register a particular Course at a time

A Course can be registered by at most 100 Students per time

A Course can be taught by one or more Lecturers

A Lecturer can teach at least one Course

At least one Lecturer can prepare the only Course Compact for a particular course

A Course Compact is part of a Course

A Course has only one Course Compact

(c) With the aid of diagrams, explain the following class relationships and specify the advisable

frequency (>) of usage in system analysis: (a) Inheritance, (b) Composition, (c) Aggregation,

and (d) Association. (10 marks)

3. (a) Explain four(4) Interface methods that can be used with an Information System. (4 marks)

(b) Give two (2) differences between the expert and novice system user. Give two reasons why

system users should be involved in the User Interface Design process. (3 marks)

Page 133: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

132

(c) Discuss five fact finding techniques you know. Give one(1) advantage and disadvantage for

each (10 marks)

(d) You have been asked by the MD/CEO of Covenant University Microfinace Bank to develop

an Automated Teller machine System. Given the following requirements: CMFB logo must

be conspicuously displayed , Retrieve money operation shall be performed in less than 1

minute, check balance operation shall be performed in less than 1 second, Do bank transfer,

User friendly GUI (green and white color), Print receipt, Send Alarm when paper is low/ over,

Send Alarm when cash is low/over, Read card, Verify PIN, Ask PIN, Ask amount, the system

must be operable by a layman, a step by step pictorial guide may be included, The system

should be efficient. Classify them using a tabular format such as this: (61

/3 marks)

Functional Non_functional

SECTION B

4. (a) i. What is an Information System? (11

/3 marks)

ii. What is the purpose of an Information System? (2 marks)

(b) Explain with a diagram the relation of Information Systems to levels of organization control.

(4 marks)

(c) List four (4) advantages of using life cycle in the software development? (4 marks)

(d) Discuss with examples the criteria for selecting an appropriate software development

methodology. (6 marks)

(e) Robert was hired to create a new purchasing system. He completed the project in the following

order.

• analyzed the existing system

• designed a new system

• wrote the code

• bought the hardware

• built the system

After testing he presented the new system to the client. Explain the software development

methodology described above, stating its pros and cons. (6 marks)

5. (a) What is Encapsulation with respect to Object Orientation. (31

/3 marks)

(b) Explain the concept of Multiple Inheritance and discuss these two (2) shortcomings of multiple

inheritance; (1) Name Clashes and (2) Repeated Inheritance. (6 marks)

(c) Ivar Jacobson, James Rumbaugh and Grady Booch, created the UML notations and UML

diagrams are classified into Structural and Behavioural diagrams. Mention and define Two (2)

diagrams in each category. (4 marks)

(d) Actors, Boundaries, Controllers and Entities are the four elements of a Collaboration or

Communication diagram. Discuss each element and show the Icon used to depict them.

(8 marks)

(e) What kinds of Relationships exist between the following?

i. A Car and a Driver

ii. An Operating System and a Mobile Phone (2 marks)

Page 134: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

133

COVENANT UNIVERSITY

CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA. TITLE OF EXAMINATION: B.Sc EXAMINATION

COLLEGE: College of Science and Technology

DEPARTMENT: Department of Computer and Information Sciences

SESSION: 2015/2016 SEMESTER: ALPHA

COURSE CODE: CSC 317 CREDIT UNIT: 2

COURSE TITLE: System Analysis & Design TIME: 2 HOURS

INSTRUCTION: Answer 2 questions in SECTION A and 1 question in SECTION B

MARKING SCHEME

SECTION A

1 (a) (7 marks)

Context diagram:

- D1 inventory illegal – eliminate

- Place Order illegal name of DF1 – should be Order

- Shipp Cap & Gown illegal name EE2 – should be Shipping

-

Level-0 diagram:

- Shipp Cap & Gown data flow wrongly goes to Student – should go to Shipping

- Receipt data flow wrongly goes to Shipping – should go to Student

- Process 2 uses illegal name (noun) – should be Finalize Order

- Process 1 is black hole (no output)

- Process 2 creates outputs out of nothing (no input) (b) (71

/3 marks)

Page 135: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

134

(c) (6 marks)

(d) (3 marks)

• Data store – Data store

• Entity – Data store

• Entity – Entity

2.

a. Use concrete examples and diagrams to explain the concept of an Object and a Class. Mention

the difference between object and class diagrams. [3.33Marks]

Page 136: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

135

1.33Mks for Definition

An Object is instance of a class, while a class is a group of objects with similar characteristics.

2Mks for Example, Correct Diagram and Distinction

Concrete Example:

A person Object

o Attributes (Name, Address, and Date of Birth)

o Operations (Change Name, Compute Age and Change Address)

Object Diagram (Object Name is Underline)

Class Diagram (Class Name is not Underlined and Begins with Capital letter)

b. Draw the Class diagram showing the Relationships and Multiplicities for the following analysis

information [10Marks]

i. A Course is made-up of one Course Details (Course details is Course Unit, Title and Course

Description)

ii. A Student can either be an Undergraduate or a Postgraduate

iii. A Student can only register a particular Course at a time

iv. A Course can be registered by at most 100 Students per time

v. A Course can be taught by one or more Lecturers

vi. A Lecturer can teach at least one Course

vii. At least one Lecturer can prepare the only Course Compact for a particular course

viii. A Course Compact is part of a Course

ix. A Course is has only one Course Compact

Page 137: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

136

1Mk For Each Class relationship denoted correctly

c. With the aid of diagrams, explain the following class relationships and specify the advisable

frequency (>) of usage in system analysis: (a) Inheritance, (b) Composition, (c) Aggregation, and

(d) Association. [10 Marks]

1Mk each

Inheritance: in an Inheritance relationship, a subclass inherits all of the attributes and

behaviour of its superclass. Other concepts in inheritance include:

Generalization/specialization, Parent/child, Superclass/subclass, Base/derived

Association: Association is a weak relationship in which the objects of one class are

related to but not completely dependent on each other.

Aggregation: Strong connection between objects, such that an instance of one class is

made up of instances of another class. Aggregation usually forms a part–whole hierarchy

and implies strong or close dependency.

Composition: Strong aggregation, in which an object is bond to another object. The

composed object can’t be shared by other objects and dies with its composer.

1Mk for Correct Diagram depiction

Page 138: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

137

0.5Mk for each relationship placed correctly

Advisable frequency of Usage: Association > Aggregation > Inheritance > Composition

3.

a. Some Methods used to interact with IS includes: <1 mark for each answer>

Command line

Users enter explicit statements into a system to invoke operations.

There are no options to choose from.

Example from MS DOS:

o COPY C:PAPER.DOC A:PAPER.DOC

o This copies a file from the C: drive to the A: drive

Includes keyboard shortcuts and function keys

This method requires the user to have some fundamental knowledge about the IS.

Menu

This involves a list of several options provided for the user to select from. User’s selection

then determines the action carried out on the IS system.Two common menu types:

o Pop-up: menu is placed near current cursor position

o Drop-down: access point to menu placed at top line of display, menu drops down

when access point is clicked.

Form

The user is given a form to fill. The headings of each sub-section guides the user on what

to fill into the blank spaces provided. This method does not restrict a user to limited options.

Page 139: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

138

Object/Symbols

Symbols can also be used to interact with an Information System. They use graphical

symbols to represent the commands or functions they carry out. They occupy little screen

spaces. The users must be familiar with the symbols used.

Common GUI controls. Eg in Windows

b. Differences between Expert and novice System User <1 mark for each>

Expert User – an experienced computer user

– Spends considerable time using specific application programs.

– Use of a computer is usually considered non-discretionary.

– In the mainframe computing era, this was called a dedicated user.

Novice User – a less experienced computer user

– Uses computer on a less frequent, or even occasional, basis.

– Use of a computer may be viewed as discretionary (although this is becoming less

and less true).

– Sometimes called a casual user.

Two Reason for involving the System User in Interface Design <0.5 marks for each>

The User uses it to interact with the IS

It can be a training process for a novice user

It can be used as a feedback to harvest new requirement for a better system.

c. Fact finding techniques are: <1 mark for each technique, 0.5 marks for advantage, 0.5 marks for

disadvantage>

Sampling of existing documentation, forms, and databases.

the process of collecting a representative sample of documents, forms, and records. These

records includes but not limited to :Organization chart, Memos and other documents that

describe the problem, Standard operating procedures for current system, Completed forms,

Manual and computerized screens and reports, Samples of databases, Flowcharts and other

system documentation, etc. sampling techniques includes Randomization and stratification.

Advantage

It is very easy to get

Disadvantage

It is very tasking.

Page 140: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

139

Research and site visits.

This involve going to the site to see how things are done.

Advantage

It gives a real life view of the problem

Disadvantage

It may involve several site visits

Observation of the work environment.

a fact-finding technique wherein the systems analyst either participates in or watches a person

perform activities to learn about the system.

Advantage

Data gathered this way is very reliable

It is relatively inexpensive

Disadvantages

People observed can perform differently under a watchful condition (they let you see what you

want to see).

Questionnaires.

a special-purpose document that allows the analyst to collect information and opinions from

respondents. The two types are

Free-format questionnaire – a questionnaire designed to offer the respondent greater latitude

in the answer. A question is asked, and the respondent records the answer in the space

provided after the question.

Fixed-format questionnaire – a questionnaire containing questions that require selecting an

answer from predefined available responses.

Advantages

It can be answered quickly

Individuals maintain anonymity. animosity

It is relatively inexpensive

Disadvantages

It is inflexible

The analyst cannot observe or analyse

No means of clarifying vague or incomplete answers.

Interviews.

a fact-finding technique whereby the systems analysts collect information from individuals

through face-to-face interaction. It Can be used to: find facts, verify facts, clarify facts, generate

enthusiasm, get the end-user involved, Identify requirements, solicit ideas and opinions. There

are two types of types of interviews: unstructured and structured interview.

Advantage

The interviewee can be motivated to be free and open to questions.

The interviewer can probe to get more feedback.

The interviewer can observe for non-verbal communication

Disadvantage

Page 141: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

140

It is time consuming

It is costly

The success is dependent on the system analyst human relations skills

Prototyping

the act of building a small-scale, representative or working model of the users’ requirements in

order to discover or verify those requirements.

Advantage

The users and developers can interact with the system

May reduce the time spent in fact finding

Disadvantage

It can extend the development schedule

Joint requirements planning (JRP).

a process whereby highly structured group meetings are conducted for the purpose of analyzing

problems and defining requirements. JRP is a subset of a more comprehensive joint application

development or JAD technique that encompasses the entire systems development process.

Advantage

The requirement gathering process is contributed by all parties

Disadvantage

It takes time

The success of the meeting is dependent on the human relation skills of the members.

d There are 10 functional requirements <10 = 3.5 marks, 9 = 3 marks, 7-8 = 2.5 marks, 5-6

= 2 marks, 3-4 answers=1.5 marks, 2 answer=1 mark, 1 answer=0.5 marks>

There are 7 non-functional requirements <7= 3 marks, 6 = 2.5 marks, 5 =2 marks, 4=1.5

marks, 2- 3=1 mark, 1 answer = 0.5 mark >

You have been asked by the MDCEO of Covenant University Microfinace Bank to develop

an Automated Teller machine System. Given the following requirements, classify them

under the subheads given below:

Functional Non_functional

Retrieve money CMFB logo must be conspicuously displayed

check balance Retrieve money operation shall be performed in less

than 1 minute

bank transfer check balance operation shall be performed in less

than 1 second

Print receipt User friendly GUI (green and white color)

Page 142: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

141

Send Alarm when paper is

low/ over

the system must be operable by a layman

Send Alarm when cash is

low/over

, a step by step pictorial guide may be included

Read card The system should be efficient

Verify PIN

Ask PIN

Ask amount

4a. what is an Information System? (11

/3 marks)

Information system deals with data of the organizations. It can be described as an arrangement of

data, processes, and technology that interact to support the operations and the decision making

needs in an organization.

What is the purpose of an Information System? (2 marks)

The purposes of Information system are to

process input

maintain data

produce reports

handle queries

handle on line transactions

generate reports, and other output.

4b. Explain the relation of Information Systems to levels of organization control. (4marks)

Page 143: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

142

The information needs are different at different organizational levels. Accordingly the information

can be categorized as: strategic information, managerial information and operational

information.

Strategic information is the information needed by top most management for decision making. For

example the trends in revenues earned by the organization are required by the top management for

setting the policies of the organization. The information systems that provide these kinds of

information are known as Decision Support Systems.

The second category of information required by the middle management is known as managerial

information. The information required at this level is used for making short term decisions and

plans for the organization. Information like sales analysis for the past quarter or yearly production

details etc, fall under this category. Management information system (MIS) caters to such

information needs of the organization

The third category of information is relating to the daily or short term information needs of the

organization such as attendance records of the employees. This kind of information is required at

the operational level for carrying out the day-to-day operational activities. Due to its capabilities

to provide information for processing transaction of the organization, the information system is

known as Transaction Processing System or Data Processing System. Some examples of

information provided by such systems are processing of orders, posting of entries in bank,

evaluating overdue purchaser orders etc.

4c. (4marks)

i. It facilitates project review

ii. It provides a more efficient/effective system

iii. It guides systems development

iv. It improves communication

v. It improves management and control

vi. It provides computer based support.

4d. Criteria for selecting appropriate technology (6 marks)

Clear user requirements e.g. waterfall model, V-shaped model, RAD

Familiar technology e.g. waterfall model, V-shaped model

Complexity e.g incremental model, Spiral model

Reliability e.g. V-shaped model

Time schedule e.g. RAD, Incremental model, spiral model

Schedule visibility e.g. RAD, Incremental model

4e.

Page 144: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

143

The software development technology used is waterfall model (6marks)

• Requirements – defines needed information, function, behavior, performance and

interfaces.

• Design – data structures, software architecture, interface representations, algorithmic

details.

• Implementation – source code, database, user documentation, testing.

Pros

• Easy to understand, easy to use

• Provides structure to inexperienced staff

• Milestones are well understood

• Sets requirements stability

• Good for management control (plan, staff, track)

• Works well when quality is more important than cost or schedule

Cons

• All requirements must be known upfront

• Deliverables created for each phase are considered frozen – inhibits flexibility

• Can give a false impression of progress

• Does not reflect problem-solving nature of software development – iterations of phases

• Integration is one big bang at the end

• Little opportunity for customer to preview the system (until it may be too late)

When to use the Waterfall Model

• Requirements are very well known

• Product definition is stable

• Technology is understood

• New version of an existing product

• Porting an existing product to a new platform. 5.

a. What is Encapsulation with respect to Object Orientation? Give Example [3.33Marks]

1.5Mks for Explanation and 1.33Mks for Example, and 0.5Mk for Diagram

Encapsulation refers to an object hiding its attributes behind its operations. Objects are black-

boxes to other objects, and relate via prescribed interfaces. The operations serve as the edge or

interfaces to hidden attributes.

For example, giving a person Object, the Attributes include Name, Address, Date of Birth; while

the Operations are: Change Name, Compute Age, Change Address:

Page 145: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

144

b. Explain the concept of Multiple Inheritance and discuss two (2) shortcomings of Multiple

Inheritance presented below: (1) Name Clashes and (2) Repeated Inheritance [6Marks]

Multiple Inheritance

This is the complexity introduced when an object or class inherits characteristics and features

from more than one parent object or parent class (2Mks).

The Shortcomings of Multiple Inheritance include:

Name clashes: Name clashes occur when elements with the same name, but different

implementations, are inherited via different routes or from different parent object or class

(2Mks).

Repeated inheritance: Repeated inheritance means inheriting the same element from

more than one route or from different parent object or class (2Mks).

c. Ivar Jacobson, James Rumbaugh and Grady Booch, created the UML notations and UML diagrams

are classified into Structural and Behavioural diagrams. Mention and define Two (2) diagrams in

each category. [4Marks]

2Mks for any of the Following (1 Mk if mentioned, and 1Mk for definition):

Structural Diagrams

Use case diagram – used to show actors, use cases, and their relationships.

Class diagram – used to show classes, their attributes, operations and their relationships

with other classes.

Component diagram – used to show system components and their relationships.

Deployment diagram – used to show system components, nodes, and their relationships.

Behavioural Diagrams

Activity diagram & Object flow diagram –Both are used to show activities, object states,

states, state transitions, and events.

Collaboration or Communication diagram – used to shows objects and their relationships,

including their spatially structured message exchange.

Page 146: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

145

Sequence diagram – used to show objects and their relationships, including their

chronologically structured message exchange.

State diagram – used to show states, state transitions, and events.

d. Actors, Boundaries, Controllers and Entities are the four elements of a Collaboration or

Communication diagram. Discuss each element and show the icon used to represent them.

[8Marks]

2Mks Each (1Mk for explanation and 1Mk for Icon)

Based on the use case narration and diagram,

Actor: A person existing outside the system, and sometimes could also be a ‘system’

Boundary: An object (or class) at the edge of the system, between the system and the

actors. Boundaries to provides a communication paths to ‘system’ actors; while for

human actors, a boundary means a user interface, that is used to capture commands,

queries and displaying feedback and results.

Entity: An object inside the system, representing a business concept such as a customer,

a car or a car model and containing useful information. Entities are manipulated by

boundary and controller elements

Controller: Is an object inside the system that encapsulates a complex or untidy

processes. E.g. creates new entities, retrieve existing entities etc.

e. What kinds of Relationships exist between the following?

iii. A Car and a Driver

iv. An Operating System and a Mobile Phone [2Marks]

1Mk each for Correct Answer

A Car and a Driver = Association Relationship

An Operating System and a Mobile Phone = Composition Relationship

Page 147: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

146

COVENANT UNIVERSITY

CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA.

B.Sc (Hons) Examination

COLLEGE: Science & Technology SCHOOL: Natural & Applied Sciences

DEPARTMENT: Computer & Information Sciences

SESSION: 2014/2015 SEMESTER: Alpha

COURSE CODE/TITLE: CSC 317/ System Analysis and Design CREDIT UNIT: 2

INSTRUCTION: Answer any three questions TIME: 2 HOURS _______________________________________________________________________________________________________________________________

1) a. Explain the difference between predictive and adaptive SDLC (4mks)

b. Explain 3 ways of identifying business use case and give example for each (15mks)

c. Identify three (3) types of events and differentiate between them (6mks)

d. What do you understand by Function Decomposition? Relate it with DFD (5mks)

2) a. Describe the required skills of system analyst (3mks)

b. Using a suitable diagram, describe the system analysis approach to solving problems

(6mks)

c. Using a brief illustration, explain four DFD Diagramming Rule (4mks)

d. Given that you are to develop a food ordering system for Covenant University Cafeteria2,

draw process 0 and level 0 DFD of the proposed system (7mks)

3) a. Describe the stages involved in system development (7.5mks)

b. With a good illustration, discuss the prototyping software development approach. (5mks)

c. Compare and contrast the following: i) model, ii) tools and iii) methodology (3mks)

d. Using Gane Sarson’s notation, explain the elements of Data Flow Diagram (DFD)

(4.5mks)

4) a. Describe the elements of an entity relationship diagram (6mks)

b. RMO schools have one or more annexe. Each annexe may have one or more teachers, but

a teacher is assigned to only one annexe. Each teacher may coordinate one or more

classes but each class is coordinated by only one teacher. Also each teacher may submit

one or more class assessment but each assessment is submitted by only one teacher. Each

class may have many assessments and an assessment may be for more than one class.

Create an ERD for this narrative. (10mks)

c. Given appropriate example, explain the following:

i) Relationship link phrase ii) Participation iii) Cardinality and iv) Modality.(4mks)

Page 148: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

147

5) a. What is the purpose of the Object Management Group? (2mks)

b. What do you understand about the following terms:

(i) Use case model (ii) Use case diagram (iii) Sequence diagram (6mks)

c. What are the techniques for identifying use cases? (6mks)

d. Provide the use case diagram for an ATM system. Also design a sequence diagram for its

“Transfer Funds” use case. (6mks)

Page 149: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

148

CSC317 2014/2015 SESSION Marking Scheme

1)a. A predictive approach is an approach that assumes that the development process can be

planned and organized in advance and that the new information system can be developed

according to the plan. Predictive SDLCs are useful for building systems that are well

understood and defined.

Adaptive approach an SDLC approach that is more flexible, assuming that the project

cannot be planned out completely in advance but must be modified as it progresses.

(4mks)

b) i. User goal technique: this approach involves talking to all users to get them to describe

their goals in using the system.

User/Actor User goal and resulting use

cases

Order clerk Look up item

availability

Create new order

Update order

Shipping clerk Record order fulfilment

Record back order

Merchandising manager Create special promotion

Produce

catalog activity

report

ii. CRUD is an acronym for Create, Read or Report, Update, and Delete. The analyst

starts by looking at the types of data stored by the system, which are modelled as data

entities or domain classes.

CRUD technique is an approach in which an analyst looks at each type of data and

includes use cases that create the data, read or report on the data, update the data, and

delete the data.

Data

entity/class

CRUD Resulting use case

Create Add new customer

Read/report Look up customer

Produce customer list

List customer orders

Page 150: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

149

Update Update customer information

Delete Delete inactive customer

iii. Event decomposition, the third technique.

This technique focuses on identifying the events to which a system must respond and

then determining how a system must respond. When defining the requirements for a

system, it is useful to begin by asking, “What events occur that will require the system to

respond?”

Focusing on events gives you a way to divide (or decompose) the system requirements

into use cases so that you can study each separately

(3 x 5mks)

c) External event is an event that occurs outside the system, usually initiated by an

external agent or actor. An external agent (or actor) is a person or organizational unit that

supplies or receives data from the system.

A classic example of an external agent is a customer.

Temporal event: an event that occurs as a result of reaching a point in time. Temporal

events do not have to occur on a fixed date. They can occur after a defined period of time

has elapsed.

For example, a bill might be given to a customer when a sale has occurred. If the bill has

not been paid within 15 days, the system might send a late notice. The temporal event

Time to send late notice might be defined as a point 15 days after the billing date.

State event: an event that occurs when something happens inside the system that triggers

the need for processing. State events are also called internal events. For example, if the

sale of a product results in an adjustment to an inventory record and the inventory in

stock drops below a reorder point, it is necessary to reorder. The state event might be

named Reorder point reached. Often state events occur as a consequence of external

events. (2 x 3mks)

d) Functional decomposition is the act of breaking a system into its component subsystems,

processes and sub processes. It is the iterative act of going from one single system to

many component processes. Each level of abstraction reveals more or less details.

Decomposition diagram shows hierarchy; it shows the top-down, functional

decomposition of a system, using a numbering scheme. When decomposing a DFD, you

must conserve inputs and outputs from processes at the next level of decomposition.

This is called Balancing.

Page 151: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

150

(5mks)

2)

• First, they need to be able to understand how to build information systems, which requires

quite a bit of technical knowledge.

• Second, they have to understand the business they are working for and how the business

uses each of the types of systems.

• Finally, the analysts need to understand quite a bit about people and the way they work.

People are the source of information about requirements, the labour that builds systems,

and the ultimate users of the information system. (1 x 3mks)

b. How does an analyst solve problem?

Page 152: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

151

1. The analyst must first understand the problem and learn everything possible about

it— who is involved, what business processes come into play, and what other systems

would be affected by solving the problem.

2. Then the analyst needs to confirm for management that the benefits of solving the

problem outweigh the costs. If solving the problem is feasible, the analyst defines in

detail what is required to solve it—

3. What specific objectives must be satisfied,

4. What data needs to be stored and used,

5. What processing must be done to the data, and what outputs must be produced.

6. What needs to be done must be defined first. How it will be done is not important yet.

(1 x 6mks)

c) i). Process

No process can have only outputs or only inputs…processes must have both outputs and inputs.

Process labels should be verb phrases.

Page 153: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

152

ii) Data Store

iii) Source/Sink

Data store labels should be noun phrases.

All flows to or from a data store must move through a process.

Page 154: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

153

iv) Data Flow

No data moves directly between external entities without going through a process.

Interactions between external entities without intervening processes are outside the system and therefore not represented in the DFD.

Source and sink labels should be noun phrases.

Page 155: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

154

(4marks)

d)

(2marks)

Bidirectional flow between process and data store is represented by two separate arrows.

Forked data flow must refer to exact same data item (not different data items) from a common location to multiple destinations.

Page 156: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

155

(5mark)

3) PROJECT PLANNING: The primary objectives of project planning are to identify the

scope of the new system, ensure that the project is feasible, and develop a schedule,

resource plan, and budget for the remainder of the project. We identify five activities in

project planning:

Define the problem (business problem & scope)

Produce the project schedule.

Confirm project feasibility (Feasibility analysis investigates economic, organizational,

technical, resource, and schedule feasibility).

Staff the project

ANALYSIS ACTIVITIES: The primary objective of the analysis activities is to understand

and document the business needs and the processing requirements of the new system. Analysis

is essentially a discovery process. The key words that drive the activities during analysis are

discovery and understanding.

Six primary activities are considered part of this phase:

Gather information

Define system requirements (Analysts must review, analyze, and structure the

information obtained so that they can develop an overall understanding of the new

system’s requirements).

Prioritize requirements.

Build prototype model for discovery of requirements

Generate and evaluate alternatives.

Review recommendations with management.

Page 157: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

156

DESIGN ACTIVITIES

• The objective of the design activities is to design the solution system based on the

requirements defined and decisions made during analysis. High-level design consists of

developing an architectural structure for the software components, databases, user

interface, and operating environment. Low-level design entails developing the detailed

algorithms and data structures that are required for software development.

• Seven major activities must be completed during the design phase:

Design the application architecture.

Design and integrate the network.

Design the user interfaces.

Design the system interfaces.

Design and integrate the database.

Prototype for design details.

Design and integrate the system controls.

IMPLEMENTATION ACTIVITIES result in the final system being built, tested, and installed.

The objective is not only to produce a reliable, fully functional information system, but also to

ensure that the users are all trained and that the organization is ready to benefit as expected from

use of the system. All the prior activities must come together to culminate in an operational system.

Five major activities make up the implementation phase:

Construct software components.

Verify and test.

Convert data.

Train users and document the system.

Install the system.

SUPPORT ACTIVITIES

• The objective of the support activities is to keep the system running productively during

the years following its initial installation. The support activities begin only after the new

system has been installed and put into production, and it lasts throughout the productive

life of the system.

• The expectation for most business systems is that the system will last for years. During

support, upgrades or enhancements may be carried out to expand the system’s capabilities,

and they will require their own development projects.

b. The Prototype Model: A prototype is a model that contains the essential elements of an

object to be produced in the future, and is used as a pattern. Prototyping is an iterative

SDM and it actively promotes system design changes. Quickly builds an

Page 158: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

157

experimental and inexpensively system for demonstration and evaluation so that end

users can better determine information requirements.

Prototyping involves less formal requirement gathering

Requirements are determined dynamically as the prototype is constructed. Users define a

set of general objectives for software but do not identify detailed input, processing, or

output requirements. The developer may be unsure of the efficiency of an algorithm, the

adoptability of such system, or the form that human/machine interaction should take.

c) A model is a representation of an important aspect of the real world. Models used in

system development include representations of inputs, outputs, processes, data, objects,

object interactions, locations, networks, and devices, among other things. Most of the

models are graphical models, which are drawn representations that employ agreed-upon

symbols and conventions.

A tool in the context of system development is software support that helps create models

or other components required in the project. Tools might be simple drawing programs for

creating diagrams. Tool is a software support that helps create models or other

components required in the project.

A technique in system development is a collection of guidelines that help an analyst

complete a system development activity or task. A technique often includes step-by-step

instructions for creating a model, or it might include more general advice for collecting

information from system users. Some examples include data-modeling techniques,

software-testing techniques, user-interviewing techniques, and relational database design

techniques.

A methodology includes a collection of techniques that are used to complete activities

within each phase of the systems development life cycle. The activities include

Page 159: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

158

completion of a variety of models as well as other documents and deliverables. Like any

other professionals, system developers use software tools to help them complete their

activities.

d) i) External Agent/Entity: it is depicted as a rectangle.

– This represents the data source or sink from outside the scope being modeled.

– Nouns are usually used to name external agents.

– Note that the external agent does not perform processing. Examples: Student,

Customer, Client.

ii) Data Flows: they are directed arrows.

– They can also be described as pipes.

– Data flows in packet through the pipes. One flow arrow represents movement of

multiple data items.

– Data flow names should connote the actual information rather than the way in which

iii) Process: it is depicted by a rectangle with round edges.

– Data flows into the process, the “process” works on

the data flowing in it.

– The data flowing out has more value after it has

been worked on by the process.

A process is always active. Examples: Create Student Record,

iv) Data store: A dead, lifeless place to hold data over time.

– The data in the data store never changes in any way.

– In naming data stores, avoid verbs and physical

description of how the data is stored.

Examples: Student Master, Client List.

4)

Page 160: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

159

b)

4a. i. Entity: an entity is a person, place or thing. It has a singular name, has an identifier

and contains more than one instance of data. It is a real world object distinguishable from

other objects. An instance of an entity is an object in the class represented by the entity.

Example an entity is Student and instances of student are Toyin Ojo, Kemi Olumide, Seyi

Martins, etc.

ii. Attributes: Information captured about an entity. They are properties of entities. Only

those used by the organization should be included in the model. Attribute names are

nouns. Sometimes entity name is added at the beginning of the attribute name. Attributes

of Student include: student_name, student_level, student_programme, etc

iii. Identifier: The identifier consists of one or more attributes that can uniquely identify

each instance of the entity. It is also known as the Primary key/keys.

iv. Relationship: Associations between entities. Connected by a line. It is given active

verb names. One verb can describe relationship in both directions. Two verbs can

describe each relationship. (6mks)

RMO SCHOOL Name HQ_Address Phone Proprietor

Generate For

Class Class_Teacher Class_Name No_of_Pupils Term

Annex Annexe_No Location Phone Head_master

H

H

coordinat

Assessment Assess_No Date Term Teacher

Teacher Annexe_No HQ_Address Phone Proprietor

Submit

Page 161: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

160

4c) Relationship Link phrase: This should be a short description of the nature of the relationship,

typically between three and five words long. It is always read clockwise with respect to the

entities that it links. Example: 'Manager is responsible for department', and 'Department is

the responsibility of the manager'. If the same relationship were to be drawn with department

on the left hand side then the positions of the link phrases would have to be reversed.

Participation: A solid line shows that an entity occurrence must be associated with each

occurrence of the other entity. It implies that the relationship is mandatory.

A dotted line shows that an entity occurrence may be associated with each occurrence of the

other entity, (optional),

• Relationship Cardinality and Modality: Cardinality refers to the number of times

instances in one entity can be related to instances in another entity.

Cardinality can be One or Many and the symbol is placed on the outside ends of the

relationship line, closest to the entity. For a cardinality of 1 a straight line is drawn. For a

cardinality of Many a foot with three toes is drawn.

• Modality refers to the minimum number of times that an instance in one entity can be

related to an instance in another entity. Modality can be One or Zero and the symbol is

placed on the inside next to the cardinality symbol. For a modality of One a straight line is

drawn. For a modality of zero, a circle is drawn.

One instance in an entity refers to one and only one instance in the related entity (1:1)

5) a.

(i) Promote theory and practice of object-oriented technology for development of distributed

systems (ii) Provide common architectural framework for OO. (2mks)

Page 162: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

161

b.

(i) Use case model – a collection of models to capture system requirements

(ii) Use case diagram – identify actors and their roles and how the actor roles utilize the system

(iii) Systems sequence diagrams (SSDs) – define inputs and outputs and sequence of interactions

between user and system for a use case (2 x 3mks)

c.

-> Identify user goals

-> Each goal at the elementary business process (EBP) level is a use case

EBP – task performed by one user in one place and in response to business event that adds

measurable business value, and leaves system and data in consistent state

Event decomposition technique (event table)

-> CRUD analysis technique (create, read/report, update, delete) to ensure coverage

(2 x 3mks)

d.

Page 163: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

162

Figure: ATM Use case diagram (3mks)

Page 164: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

163

Figure: Sequence diagram for the Transfer Funds use case (3mks)

Page 165: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

164

COVENANT UNIVERSITY

CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA. TITLE OF EXAMINATION: B.Sc EXAMINATION

COLLEGE: SCIENCE & TECHNOLOGY

DEPARTMENT: COMPUTER & INFORMATION SCIENCES

SESSION: 2015/2016 SEMESTER: ALPHA

COURSE CODE: CSC318 CREDIT UNIT: TWO (2)

COURSE TITLE: COMPILER CONSTRUCTION I

INSTRUCTION: ATTEMPT ANY THREE (3) QUESTIONS TIME: 2 HOURS

1a. (i) What are regular expressions? [0.5 mark]

(ii) Is compiler construction an engineering science? Provide justification for

your answers. [1 mark]

1b. (i) Why is it very difficult to track down program faults caused by incorrect compiler

behaviour? [3 marks]

(ii) Mention five (5) functions of Run time diagnostics. [2.5 marks]

1c. (i) Provide a formal definition of Context-free Grammars? [2.5 marks]

(ii) What is the advantage of organizing a compiler into a sequence of passes?[2 marks]

(iii) Mention five (5) types of grammars [2.5 marks]

1d. (i) Mention four (4) different ways a compiler can recover from errors. [2 marks]

(ii) What is a decompiler? [0.5 mark]

(iii) What is a hash table? [1 mark]

1e.How will a Java compiler syntactically represent the following expression: 70* qzyx

[2.5 marks] 1f. (i) Mention at least 3 kinds of information associated with an identifier in a source

program that you can find in a symbol table? [3 marks]

(ii) What are the architectural “master pieces” that form the bedrock of compiler

construction? [1 mark]

2a. Describe the whole process of a compiler from the first stage to the last stage of producing an

object code. Support your description with detail diagrams. [10 marks]

2b. What are the secondary creators of a symbol table entries? [1 mark]

2c. State the various uses of a symbol table. [3 marks]

2d. Describe in English, the language defined and specified by }0:{ 2 icb ii [4 marks]

2e. Show that {λ}| b+ = b* [1 mark]

2f. Show that (b+)? = b* [1 mark]

2g. The following non-left-recursive variant of the expression grammar will be used for top-

down parsing: E -> T E’

Page 166: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

165

E’-> + T E’ | ϵ

T -> F T’

T’ -> * F T’| ϵ

F -> (E) | id

Can this grammar be useful for illustrating techniques for handling ambiguities during compiler

parsing? (True or False) Provide an example to justify your choice of answer. [1mark].

[1.5 marks]

2i. Mention three (3) algorithms that decide whether and how a given regular expression matches

a string. [1.5 marks]

3a. Suppose a source program contains the assignment statement

FinalResult = Startpoint + multiplierfactor * 60,

Describe how this statement will be processed and represented from the first stage of a

compiler to the last stage of a compiler. [8 marks]

3b. Describe the interactions between a lexical analyzer, parser and a symbol table.

Support with a suitable diagram. [3 marks]

3c. (i) What is the common implementation technique to use in a symbol table? [0.5 mark]

(ii) Explain why modeling in compiler design and implementation is a significant aspect worth

studying. [2.5 marks]

3d. Mention four (4) functions of a compiler. [2 marks]

3e. Grammars have significant benefits for both language designers and compiler writers.

Mention and discuss five (5) of them. [5 marks]

3f. One method of representing a set is simply to list its elements in any order.

Given that AB is the set of all strings that can be formed by concatenating a string A with a string

B. For example, if A= {bb, ccc} and B = {d, cde}, then derive

(i) AB [1.5 marks]

(ii) BA [1.5 marks]

4a.What is syntax analysis? [3 marks]

4b. Express in a diagram the front end of a compilation process. [3 marks]

4c. Explain the LALR table construction method by a detailed pseudocode [6 marks]

4d. Explain five (5) common programming errors a good compiler must identify [7.5 marks]

4e. Explain the traumatic nature of semantic errors. [1 mark]

4f. What are the contents of a parse tree? [3 marks]

5a.Enumerate four expected goals of the error handler in the compilation process [4 marks]

5b.List and explain four error recovery strategies. [4 marks]

5c. Write an algorithm to eliminate left recursion in a parsing process. [5 marks]

5d.Express a recursive descent parsing procedure for a non-terminal in a top-down parser

[4.5 marks] 5e.Explain the following: (i) LL (1) grammars (ii) Predictive parsers [2 marks]

5f.Write the predictive parsing algorithm as related to the predictive parsing table [4 marks]

Page 167: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

166

Marking Scheme For CSC318

1a. (i) In theoretical computer science and formal language theory, a regular

expression (abbreviated regex or regexp) and sometimes called a rational expression is a

sequence of characters that forms a search pattern, mainly for use in pattern matching with strings,

or string matching, i.e. "find and replace"-like operations. [0.5 Mark]

(ii) YES, Compiler Construction is an Engineering Science. [0.5 Mark]

Justification – This is because with this science, we can methodically - almost routinely –

design and implement fast, reliable, and powerful compilers. [0.5 Mark]

1b. (i) It is very difficult to track down program faults caused by incorrect compiler behaviour

because it takes more time, energy, thoroughness, careful and significant effort to detect such

faults. Using a compiler that generates wrong results could either imply that the codes run on the

compiler are faulty or if the codes are correct, then the compiler may be faulty.

Program faults caused by incorrect compiler behavior can be very difficult to track down and work

around; therefore, compiler implementers invest significant effort to ensure compiler correctness.

[3 Marks]

1b. (ii) Mention five (5) functions of Run time diagnostics. [0.5Mark awarded for each point]

Reviewing critical messages in the log [0.5 Mark]

Analyzing contention [0.5 Mark]

Examining address spaces with high central processing unit (CPU) usage [0.5 Mark]

Looking for an address space that might be in a loop [0.5 Mark]

Evaluating local lock conditions [0.5 Mark]

[Total=2.5 Marks]

1c. (i) Provide a Formal definition of Context-free Grammars?

(i)The productions of a grammar specify the manner in whicht the terminals and non-terminals can

be combined to form strings.

Each production consists of:

(a)A nonterminal called the head or left side of the production; this production defines some of the

strings denoted by the head [1 Mark]

(b)The symbol ->. Sometimes::= has been used in place of the arrow. [0.5 Mark]

(c) A body or right side consisting of zero or more terminals and non-terminals. The components

of the body describe one way in which strings of the nonterminal at the head can be constructed

[1 Mark]

[Total=2.5 Marks]

(ii) What is the advantage of organizing a compiler into a sequence of passes?

(a) It promotes efficiency [1 Mark]

(b) It promotes effectiveness during compilation processes [1 Mark]

[Total=2 Marks]

Page 168: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

167

(iii) Mention Five (5) types of grammars [0.5Mark awarded for any five (5) point]

Context free Grammars

•Context sensitive Grammars

•LL(1) Grammars

•Bad Grammar

•Non-LL (1) Grammar

•Grammar with Lambda productions

•Ambiguous Grammar

•Left-Recursive Grammars

•Regular Grammars [Total = 2.5 Marks]

1d. (i) Mention Four (4) different ways a compiler can recover from errors.

[0.5 Marks for each point]

Panic-mode Recovery [0.5 Mark]

Phrase level [0.5 Mark]

Error – productions [0.5 Mark]

Global correction [0.5Mark]

[Total = 2 Marks]

(ii) What is a decompiler?

A decompiler is a program that translates from a low level programming language to a higher

level one

[0.5 Mark]

(iii) What is a hash table? A hash table is a datastructure used to implement an associative array,

a structure that can map keys to values . A hash table uses a hash function to compute an index

into an array of buckets or slots from which desired values can be found

[1.5 Marks]

1e. How will a Java compiler syntactically represent this expression: 70* qzyx

[2.5 Marks]

1f. . (i) Mention at least 3 kinds of information associated with an identifier in a source

Page 169: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

168

program that you can find in a symbol table?

[Any five (5) of these carries 0.5 Mark each]

The Symbol type [0.5 Mark]

The Symbol address [0.5 Mark]

The Symbol Scope [0.5 Mark]

The Symbol level [0.5 Mark]

The Symbol location [0.5 Mark]

[Total = 3 marks]

(ii) What are the architectural “master pieces” that form the bedrock of compiler

construction?

The Front End [0.3 Mark]

The Middle End [0.2 Mark]

The Back End [0.5 Mark]

[Total = 1 mark]

2a. Describe the whole process of a compiler from the first stage to the last stage of producing an

object code. Support your description with detail diagrams.

Lexical Analysis

The first phase of a compiler is called lexical analysis or scanning. The lexical analyzer reads the

stream of characters making up the source program and groups the characters into meaningful

sequences called lexemes. For each lexeme, the lexical analyzer produces as output a token of the

form

(token-name, attribute-value)

That it passes on to the subsequent phase, syntax analysis.

In the token, the first component token-name is an abstract symbol that is used during syntax

analysis, and the second component, attribute-value points to an entry in the symbol table for this

token. Information from the symbol-table entry is needed for semantic analysis and code

generation [1 Mark]

Syntax Analysis

The second phase of the compiler is the syntax analysis or parsing. The parser uses the first

components of the tokens produced by the lexical analyzer to create a tree-like intermediate

representation that depicts the grammatical structure of the token stream.

A typical representation is a syntax tree in which each interior node represents an operation and

the children of the node represent the arguments of the operation. [1 Mark]

Semantic Analysis

The semantic analyzer uses the syntax tree and the information in the symbol table to check the

source program for semantic consistency with the language definition. It also gathers type

information and saves it in either the syntax tree or the symbol table, for subsequent use during

intermediate-code generation.

Type checking implies that the compiler checks that each operator has matching operands.

Page 170: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

169

For example, many programming language definitions require an array index to be an integer;

the compiler must report an error if a floating-point number is used to index an array.

The language specification may permit some type conversions called coercions. For example, a

binary arithmetic operator may be applied to either a pair of integers or to a pair of floating-point

numbers. If the operator is applied to a floating-point number and an integer, the compiler may

convert or coerce the integer in to a floating-point number. [1 Mark]

4 Marks

Intermediate Code Generation

In the process of translating a source code into a target code, a compiler may construct one or

more intermediate representations, which can have a variety of forms. Syntax trees are a form of

intermediate representation; they are commonly used during syntax and semantic analysis.

Page 171: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

170

After syntax and semantic analysis of the source program, many compilers generate an explicit

low-level or machine-like intermediate representation, which we can think of as a program for an

abstract machine. [1 Mark]

Code Optimization

The machine-independent code-optimization phase attempts to improve the intermediate code so

that better target code will result. Usually better means faster, but other objective may be desired,

such as shorter code, or target code that consumes less power.

A simple intermediate code generation algorithm followed by code optimization is a reasonable

way to generate good target code.

There is a great variation in the amount of code optimization different compilers perform. In

those that do the most, the so-called “ optimizing compilers”, a significant amount of time is

spent on this phase. There are simple optimizations that significantly improve the running time

of the target program without slowing down compilation too much. [1 Mark]

Code Generation

The Code generator takes as input an intermediate representation of the source program and

maps it into the target language. If the target language is machine code, registers or memory

locations are selected for each of the variables used by the program. Then, the intermediate

instructions are translated into sequences of machine instructions that perform the same task. A

crucial aspect of code generation is the judicious assignment of registers to hold variables.

[1 Mark]

2b. What are the secondary creators of a symbol table entries?

Lexical analyzer [0.3 Mark]

Syntax analyzer [0.2 Mark]

Semantic analyzer [0.5 Mark]

[Total = 1 Mark]

2c. State the various uses of a symbol table. [1 Mark for each of any 3 of the 4 points]

An object file will contain a symbol table of the identifiers it contains that are externally

visible. During the linking of different object files, a linker will use these symbol tables to

resolve any unresolved references. [1 Mark]

A symbol table may only exist during the translation process, or it may be embedded in the

output of that process for later exploitation, for example, during an interactive debugging

session, or as a resource for formatting a diagnostic report during or after execution of a

program. [1 Mark]

While reverse engineering an executable, many tools refer to the symbol table to check

what addresses have been assigned to global variables and known functions. If the symbol

table has been stripped or cleaned out before being converted into an executable, tools will

find it harder to determine addresses or understand anything about the program. [1 Mark]

At that time of accessing variables and allocating memory dynamically, a compiler should

perform many works and as such the extended stack model requires the symbol table [1

Mark]

[Total = 3 Marks]

Page 172: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

171

2d. Describe in English, the language defined and specified by }0:{ 2 icb ii [4 marks]

The set of all strings consisting of b’s followed by c’s in which the number of c’s is twice the

numbers of b’s . This set is { λ, bcc, bbcccc, bbbcccccc,…..} [4 Marks]

2e. Show that {λ}| b+ = b* [1 mark]

{λ}| b+= {λ}| {b,bb,bbb,….}={λ, b,bb,bbb,…..} = b*

2f. Show that (b+)? = b*

(b+)? = {λ}| b+ = {λ}|{b,bb,bbb,…..} = b* [1 mark]

2g. The following non-left-recursive variant of the expression grammar will be used for top-

down parsing: E -> T E’

E’-> + T E’ | ϵ

T -> F T’

T’ -> * F T’| ϵ

F -> ( E ) | id

Can this Grammar be useful for illustrating techniques for handling ambiguities during compiler

parsing? (Answer = YES) [1Mark]

Provide an example to justify your choice of answer. The following non-left-recursive variant of

the expression grammar will be used for top-down parsing:

E -> T E’

E’-> + T E’ | ϵ

T -> F T’

T’ -> * F T’| ϵ

F -> ( E ) | id

The following Grammar be useful for illustrating techniques for handling ambiguities during

parsing because it treats + and * alike, so it is useful for illustrating techniques for handling

ambiguities during parsing:

E -> E + E | E * E | ( E )| id

Here, E represents expressions of all types.

[1.5 Marks]

2i. Mention Three (3) algorithms that decide whether and how a given regular expression matches

a string.

(i) nondeterministic finite automaton [0.5 mark]

(ii) deterministic finite automation [0.5 mark]

Page 173: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

172

(iii) backtracking [0.5 mark] [1.5 Marks]

3a. Suppose a source program contains the assignment statement

FinalResult = Startpoint + multiplierfactor * 60,

Describe how this statement will be processed and represented from the first stage of a

compiler to the last stage of a compiler. [8 Marks]

1. Lexical Analysis

The characters in this assignment could be grouped into the following lexemes and mapped into

the following tokens passed on to the syntax analyzer:

(i) position is a lexeme that would be mapped into a token <id, 1>, where id is an abstract symbol

standing for identifier and 1 points to the symbol-table entry for position. The symbol-table entry

for an identifier holds information about the identifier, such as its name and type.

(ii) The assignment symbol = is a lexeme that is mapped into the token < = > . Since this token

needs no attribute-value, we have omitted the second component. We could have used any abstract

symbol such as assign for the token-name, but for notational convenience we have chosen to use

the lexeme itself as the name of the abstract symbol.

(iii) initial is a lexeme that is mapped into the token < id, 2 > , where 2 points to the symbol-table

entry for initial.

(iv) + is a lexeme that is mapped in to the token < + >.

Rate is a lexeme that is mapped into the token < id, 3 > , where 3 points to the symbol-table entry

for rate.

* is a lexeme that is mapped into the token < * > .

60 is a lexeme that is mapped into the token < 60 >

Figure 2. shows the representation of the assignment statement after the lexical analysis as the

sequence of tokens

< id, 1> < = > <id, 2> <+> <id,3> <*> <60> (Equa.2)

In this representation, the token names =,+, and * are abstract symbols for the assignment, addition,

and multiplication operators, respectively.

< id, 1> < = > <id, 2> <+> <id,3> <*> <60> (Equa.2) [2 Marks]

Syntax Analysis

This tree shows the order in which the operations in the assignment

position = initial + rate * 60

Are to be performed; The tree has an interior node labeled * with <id, 3> as its left child and the

integer 60 as its right child. The node <id, 3> represents the identifier rate. The node labeled *

makes it explicit that we must first multiply the value of rate by 60. The node labeled + indicates

that we must add the result of this multiplication to the value of initial. The root of the tree, labeled

Page 174: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

173

=, indicates that we must store the result of this addition into the location for the identifier position.

This ordering of operations is consistent with the usual conventions of arithmetic which tells us

that multiplication has higher precedence than addition, and hence that the multiplication is to be

performed before addition. [1 Mark]

Semantic Analysis

The semantic analyzer uses the syntax tree and the information in the symbol table to check the

source program for semantic consistency with the language definition. It also gathers type

information and saves it in either the syntax tree or the symbol table, for subsequent use during

intermediate-code generation.

Type checking implies that the compiler checks that each operator has matching operands.

For example, many programming language definitions require an array index to be an integer; the

compiler must report an error if a floating-point number is used to index an array.

The language specification may permit some type conversions called coercions. For example, a

binary arithmetic operator may be applied to either a pair of integers or to a pair of floating-point

numbers. If the operator is applied to a floating-point number and an integer, the compiler may

convert or coerce the integer in to a floating-point number [0.5 Mark]

Intermediate Code generation

In the process of translating a source code into a target code, a compiler may construct one or more

intermediate representations, which can have a variety of forms. Syntax trees are a form of

intermediate representation; they are commonly used during syntax and semantic analysis.

[0.5 Mark]

Code Optimization

Expressn 3. consists of the three-address code sequence (an intermediate form which consists of a

sequence of assembly-like instructions with three operands per instruction). Each operand can act

like a register.

t1 = inttofloat (60)

t2 = id3 *t1

t3 = id2 + t2

id1 =t3

(Expressn 3)

The optimizer can deduce that the conversion of 60 from integer to floating point can be done once

and for all at compile time, so the inttofloat operation can be eliminated by replacing the integer

60 by the floating-point number 60.0. Moreover, t3 is used only once to transmit its value to id1

so the optimizer can transform (Expressn 3.) into the shorter sequence

t1 = id3 * 60

id1 = id2 + t1 (Expressn 4.) [2 Marks]

Code Generation

For example, using registers R1 and R2, the intermediate code in Expression 4 might get

translated into the machine code

Page 175: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

174

LDF R2, id3

MULF R2, R2, #60.0

LDF R1, id2

ADDF R1, R1, R2

STF id1, R1 (Expressn 5) [2 Marks]

3b. Describe the interactions between a lexical analyzer, parser and a symbol table. If possible

support with a suitable diagram.

A simple way to build lexical analyzer is to construct a diagram that illustrates the structure of the

tokens of the source language, and then to hand-translate the diagram into a program for finding

tokens. Efficient lexical analyzers can be produced in this manner.

Role of a Lexical Analyzer

The lexical analyzer is the first phase of compiler. Its main task is to read the input characters and

produces output a sequence of tokens that the parser uses for syntax analysis. As in the figure,

upon receiving a get next token command from the parser the lexical analyzer reads input

characters until it can identify the next token. 1 Mark

Tokens, interactions btw lexical analyzer and the parser

Diagram = 3 Marks

Page 176: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

175

Since the lexical analyzer is the part of the compiler that reads the source text, it may also perform

certain secondary tasks at the user interface. One such task is stripping out from the source program

comments and white space in the form of blank, tab, and new line character. Another is correlating

error messages from the compiler with the source program. 1 Mark

The lexical analyzer returns to the parser a representation for the token it has found. The

representation is an integer code if the token is a simple construct such as a left parenthesis,

comma, or colon .The representation is a pair consisting of an integer code and a pointer to a table

if the token is a more complex element such as an identifier or constant .The integer code gives

the token type, the pointer points to the value of that token .Pairs are also retuned whenever we

wish to distinguish between instances of a token. 1 Mark

[Total = 3 Marks]

3c. (i) What is the common implementation technique to use in a symbol table?

Hashing

[0.5 mark]

(ii) Explain why modeling in compiler design and implementation is a significant aspect worth

studying.

The study of compilers is mainly a study of how we design the right mathematical models and

choose the right algorithms, while balancing the need for generality and power against simplicity

and efficiency. Some of the most fundamental models are finite-state machines and regular

expressions. These models are useful for describing the lexical units of the program s(keywords,

identifiers, and such) and for describing the algorithms used by the compiler to recognize those

units.

Also, among the most fundamental models are context-free grammars, used to describe the

syntactic structure of programming languages such as nesting of parentheses or control

constructs. Similarly, trees are an important model for representing the structure of programs

and their translation into object code. [Total = 2.5 marks]

3d. Mention four (4) functions of a compiler. [0.5 mark for any of the four points]

The primary function of a compiler is that it is used for programs that translate source codes

from a high-level programming language to a lower level language (e.g., assembly

language or machine code).

Furthermore, compiler is likely to perform many or all of the following operations or

functions, namely:

lexical analysis

preprocessing

parsing

semantic analysis (Syntax-directed translation),

code generation

code optimization [Total = 2 Marks]

Page 177: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

176

3e. Grammars have significant benefits for both language designers and compiler writers.

Mention and discuss five (5) of them.

Grammars have significant benefits for both language designers and compiler writers.

Mention and discuss five (5) of them.

A grammar gives a precise, yet easy-to-understand, syntactic specification of a

programming language. [1 Mark]

From certain classes of grammar, we can construct automatically an efficient parser that

determines the syntactic structure of a source program. [1 Mark]

As a side benefit, the parser-construction process can reveal syntactic ambiguities and

trouble spots that might have slipped through the initial design phase of a language.

[1 Mark]

The structure imparted to a language by a properly designed grammar is useful for

translating source programs into correct object code and for detecting errors. [1 Mark]

A grammar allows a language to be evolved or developed iteratively, by adding new

constructs to perform new tasks. These new constructs can be integrated more easily into

an implementation that follows the grammatical structure of the language [1 Mark]

[Total = 5 marks]

3f. One method of representing a set is simply to list its elements in any order.

Given that AB is the set of all strings that can be formed by concatenating a string A with a string

B. For example, if A= {bb, ccc} and B = {d, cde}, then derive

(i) AB

AB = {bbd, bbcde, cccd, ccccde} [1.5 marks]

(ii) BA

BA = {dbb,dccc,cdebb,cdeccc} [1.5 marks]

4a. Syntax analysis is the second phase of the compilation process. It is done by the parser. It

detects whether the program is written following the grammar rules or not and reports syntax

errors. It produces a parse tree from which intermediate code can be generated.

(3marks)

4b.

Page 178: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

177

Figure1: The front end of a compilation process. (3 marks)

4c. The LALR table construction method:

1. Construct C= {I0, I1,…,In} the collection of LR(1) items.

2. For each core among the set of LR (1) items, find all sets having that core, and replace

these sets by their union.

3. Let C’= {J0,J1,…,Jm} be the resulting sets. The parsing actions for state i, is constructed

from Ji as before. If there is a conflict grammar, is not LALR (1).

4. If J is the union of one or more sets of LR (1) items, that is J = I1, I2…Ik then the cores of

GoTo(I1,X), …, GoTo(Ik,X) are the same and is a state like K, then we set GoTo(J,X) =k.

(6 marks)

4d. A good compiler should assist in identifying and locating the following errors:

Lexical errors: Important, compiler can easily recover and continue.

Syntax errors: Most important for compiler, can almost always recover.

Static semantic errors: Important, can sometimes recover.

Dynamic semantic errors: Hard or impossible to detect at compile time, runtime checks are

required.

Logical errors: Hard or impossible to detect. (71/2 marks)

4e. Semantic errors: These are based on contrary meaning to the intention of the programmer

and products of wrong logic. To the compiler, an instruction has been given, it cannot read the

mind of a user. The answer could be correct but wrong for the actual task intended, while the

compiler cannot discover such, the user might not notice too. It causes much havoc, for example,

giving an addition operation to the compiler instead of a multiplication gives answers but against

actual intention. (1 mark)

4f. A parse tree shows the grammatical structure of a statement. It includes all of the grammar

symbols (terminals and non-terminals) that were encountered during parsing.

(3 marks)

5a. The error handler goals are to:

Report the presence of errors clearly and accurately.

Recover from each error quickly enough to detect subsequent errors.

Add minimal overhead to the processing of correct programs. (3 marks)

Page 179: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

178

5b. The four error recovery strategies with explanations are below:

• Panic mode: Discard input until a token in a set of designated synchronizing tokens is

found.

• Phrase-level recovery: Perform local correction on the input to repair the error.

• Error productions: Augment grammar with productions for erroneous constructs.

• Global correction: Choose a minimal sequence of changes to obtain a global least-cost

correction. (4 marks)

5c. Left recursion elimination algorithm:

Arrange the non-terminals in some order A1, A2,…,An.

For (each i from 1 to n) {

For (each j from 1 to i-1) {

Replace each production of the form Ai-> Aj γ by the production Ai -> δ1 γ | δ2 γ | … |δk γ where

Aj-> δ1 | δ2 | … |δk are all current Aj productions

}

Eliminate left recursion among the Ai-productions

} (5 marks)

5d. Recursive descent parsing consists of a set of procedures, one for each non-terminal

Execution begins with the procedure for start symbol

A typical procedure for a non-terminal is below:

void A() {

choose an A-production, A->X1X2..Xk

for (i=1 to k) {

if (Xi is a nonterminal

call procedure Xi();

else if (Xi equals the current input symbol a)

advance the input to the next symbol;

else /* an error has occurred */

}

} (41/2 marks)

5e

(i) Grammars for which we can create predictive parsers are called LL(1) grammars

The first L means scanning input from left to right

The second L means leftmost derivation

And 1 stands for using one input symbol for look ahead

A grammar G is LL(1) if and only if whenever A-> α|βthere are two distinct productions

of G, the following conditions hold:

For non-terminal a do αandβ both derive strings beginning with a

At most one of α or β can derive empty string

If α=> ɛ then β does not derive any string beginning with a terminal in Follow(A).

Page 180: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

179

(ii) Predictive parsers are those recursive descent parsers needing no backtracking.

(2 marks)

5f. Set ip point to the first symbol of w;

Set X to the top stack symbol;

While (X<>$) { /* stack is not empty */

if (X is a) pop the stack and advance ip;

else if (X is a terminal) error();

else if (M[X,a] is an error entry) error();

else if (M[X,a] = X->Y1Y2..Yk) {

output the production X->Y1Y2..Yk;

pop the stack;

push Yk,…,Y2,Y1 on to the stack with Y1 on top;

}

set X to the top stack symbol;

} (4 marks)

Page 181: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

180

COVENANT UNIVERSITY

CANAANLAND, KM 10, IDIROKO ROAD

P.M.B 1023, OTA, OGUN STATE, NIGERIA. TITLE OF EXAMINATION: B.Sc EXAMINATION

COLLEGE: SCIENCE AND TECHNOLOGY

SCHOOL: NATURAL AND APPLIED SCIENCES

DEPARTMENT: COMPUTER & INFORMATION SCIENCES

SESSION: 2014/2015 SEMESTER: ALPHA

COURSE CODE: CSC 318 CREDIT UNIT: 2

COURSE TITLE: COMPILER CONSTRUCTION I TIME: 2HOURS

INSTRUCTION: ATTEMPT ANY THREE (3) QUESTIONS

1a. Why is it very difficult to track down program faults caused by incorrect compiler

behaviour? [3 Marks]

1b. (i) Explain the meaning of Run time diagnostics. [1.5 Marks]

(ii) Mention Five (5) functions of Run time diagnostics. [2.5 Marks]

1c. (i) Provide a Formal definition of Context-free Grammars? [2.5 Marks]

(ii) What is the advantage of organizing a compiler into a sequence of passes? [2 Marks]

(iii) Mention Five (5) types of grammars [2.5 Marks]

1d. (i) Mention Four (4) different ways a compiler can recover from errors. [2 Marks]

(ii) What is a Kleen star? [0.5 Mark]

(iii) How do you prevent redundancy in regular expressions? [1.5 Mark]

1e. Formal languages are syntactic in nature; Is it possible to make them semantic? How?

[2.5 Marks] 1f. (i) Mention Four (4) applications of regular expressions. [2 Marks]

(ii) How does Python make use of regular expressions? [1 Mark]

(iii) Can regular expressions be used in databases? [0.5 Mark]

2a. Describe the whole process of a compiler from the first stage to the last stage of producing an

object code. Support your description with detail diagrams. [10 Marks]

2b. What is an alphabet in the context of formal languages? [1 Mark]

2c. State the various uses of a symbol table. [3 Marks]

2d. What are fuzzy regular expressions? [2 Marks]

2e. What are the disadvantages of applying regular expressions in search engines?[2 Marks]

2f. What are the applications of delimiters in regular expressions? [1 Mark]

2g. How does Java implement regular expressions? [1 Mark]

2h. The following non-left-recursive variant of the expression grammar will be used for top-

down parsing: E -> T E’

E’-> + T E’ | ϵ

Page 182: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

181

T -> F T’

T’ -> * F T’| ϵ

F -> ( E ) | id

Can this Grammar be useful for illustrating techniques for handling ambiguities during compiler

parsing? (True or False) [1Mark]. Provide an example to justify your choice of answer.

[1.5 Marks]

2i. Mention Three (3) algorithms that decide whether and how a given regular expression matches

a string. [1.5 Marks]

3a. Suppose a source program contains the assignment statement

Position = initial + rate * 60,

Describe how this statement will be processed and represented from the first stage of a

compiler to the last stage of a compiler. [8 Marks]

3b. Describe in English, the language defined and specified by }0:{ 2 icb ii [3.5 Marks]

3c. (i) In a symbol table, a common implementation technique to use is called ____ [0.5 Mark]

(ii) Regular expressions can be used as ____________ in text editors. [0.5 Mark]

(iii) Regular expressions can be used as ____________ in a compiler. [0.5 Mark]

3d. What is a formal language? [2 Marks]

3e. Grammars have significant benefits for both language designers and compiler writers.

Mention and discuss five (5) of them. [5 Marks]

3f. (i) When is a set of languages said to be closed under a certain operation? [1 Mark]

(ii) Mention any application of languages in computer science? [1 Mark]

(iii) Mention any application of regular expressions in real life? [1 Mark]

(iv) What is Formal semantics? [1 Mark]

4a. Describe the interactions between a lexical analyzer, parser and a symbol table. If possible

support with a suitable diagram. [6 Marks]

4b. (i) Mention Four (4) Functions of a compiler. [2 Marks]

(ii) Discuss the relevance of modeling to compiler design and implementation.[4 Marks]

4c. Explain the equivalence of regular expressions. [2 Marks]

4d. Mention Three (3) software libraries that work with fuzzy regular expressions. [1.5 Marks]

4e. Mention Five (5) scripting languages that support regular expressions. [2.5 Marks]

4f. What is a symbol table? [1 Mark]

4g. At the most basic conceptual level, what are the functions of a parser? [2 Marks]

4h. What is an empty language? [1 Mark]

4i. (i) Describe in English the set defined by b* ({c} | {d}) e* [1.5 Marks]

(ii) Show that {λ}| b+ = b* [1.5 Marks]

(iii) Show that (b+)? = b* [1.5 Marks]

5a. Draw the structure of a compiler and its corresponding components [10 Marks]

5b. Since languages are sets of strings, it is actually appropriate at this point to review some basic

set theory. One method of representing a set is simply to list its elements in any order.

Given that, AB is the set of all strings that can be formed by concatenating a string A with a string

B. For example, if A= {b, cc} and B = {d, dd}, then derive

(i) AB [1.5 Marks]

Page 183: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

182

(ii) BA [1.5 Marks]

5c. Derive the possible strings that can be obtained from

(i) (bcd)* [2 Mark]

(ii) bcc* [2 Mark]

5d. (i) List all the strings of length 3 in {b,cc}* [2 Marks]

(ii) Is ccbcc ϵ {b,cc}* [2 Marks]

(iii) List all strings in b* cb* of length less than 3. [2 Marks]

Page 184: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

183

Marking Scheme

1a. Program faults caused by incorrect compiler behavior can be very difficult to track down and

work around; therefore, compiler implementers invest significant effort to ensure compiler

correctness. It’s difficult because it takes more time and significant effort to detect. [3 Marks]

1b. (i) Runtime Diagnostics is an MVS™ subsystem (component name HZR) designed to help you

analyze a system that has potential soft failures. In contrast to catastrophic failures, a soft failure

is defined as the combination of typical and abnormal behavior that causes the software to withhold

a requested service. Soft failures are often difficult or impossible to detect and can slowly lead to

the degradation of the solution that is using z/OS® [1.5 Marks]

(ii) Mention Five (5) functions of Run time diagnostics. [0.5Mark awarded for each point]

Reviewing critical messages in the log

Analyzing contention

Examining address spaces with high central processing unit (CPU) usage

Looking for an address space that might be in a loop

Evaluating local lock conditions [2.5 Marks]

1c. (i) Provide a Formal definition of Context-free Grammars?

(i)The productions of a grammar specify the manner in whicht the terminals and non-terminals can

be combined to form strings.

Each production consists of:

(a)A nonterminal called the head or left side of the production; this production defines some of the

strings denoted by the head

(b)The symbol ->. Sometimes::= has been used in place of the arrow.

(c) A body or right side consisting of zero or more terminals and non-terminals. The components

of the body describe one way in which strings of the nonterminal at the head can be constructed.

[2.5 Marks]

(ii) What is the advantage of organizing a compiler into a sequence of passes?

It promotes efficiency and effectiveness during compilation processes [2 Marks]

(iii) Mention Five (5) types of grammars [0.5Mark awarded for each point]

Context free Grammars

•Context sensitive Grammars

•LL(1) Grammars

•Bad Grammar

•Non-LL(1) Grammar

•Grammar with Lambda productions

•Ambiguous Grammar

•Left-Recursive Grammars

•Regular Grammars [2.5 Marks]

1d. (i) Mention Four (4) different ways a compiler can recover from errors.

Page 185: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

184

[0.5 Marks for each point]

Panic-mode Recovery

Phrase level

Error – productions

Global correction [2 Marks]

(ii) What is a Kleen star?

In computer science, the Kleene star (or Kleene operator or Kleene closure) is a unary operation,

either on sets of strings or on sets of symbols or characters. [0.5 Mark]

(iii) How do you prevent redundancy in regular expressions?

By applying a representation such as the Kleene star and Set Union to find an interesting subset

of regular expressions that is still fully expressive, but perhaps their use can be restricted.

[1.5 Marks]

1e. Formal languages are syntactic in nature; Is it possible to make them semantic? How?

Formal languages are entirely syntactic in nature but may be given semantics that give meaning to

the elements of the language. For instance, in mathematical logic, the set of possible formulas of

a particular logic is a formal language, and an interpretation assigns a meaning to each of the

formulas—usually, a truth value.

[2.5 Marks]

1f. (i) Mention Four (4) applications of regular expressions. [0.5 Mark for each point]

Regular expressions can be used in the followings:

pattern matching in a text editor

and lexical analysis in a compiler

lexical analysis in compiler design

In writing libraries for scripting languages, e.g Tcl, Perl etc. [2 Marks]

(ii) How does Python make use of regular expressions?

Regular expression support is part of the standard library of many programming languages,

including Java and Python [1 Mark]

(iii) Can regular expressions be used in databases?

Yes, regular expressions can be used in databases, especially in database modeling. [0.5 Mark]

2a. Describe the whole process of a compiler from the first stage to the last stage of producing an

object code. Support your description with detail diagrams.

Lexical Analysis

The first phase of a compiler is called lexical analysis or scanning. The lexical analyzer reads the

stream of characters making up the source program and groups the characters into meaningful

sequences called lexemes. For each lexeme, the lexical analyzer produces as output a token of the

form

(token-name, attribute-value)

Page 186: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

185

That it passes on to the subsequent phase, syntax analysis.

In the token, the first component token-name is an abstract symbol that is used during syntax

analysis, and the second component, attribute-value points to an entry in the symbol table for this

token. Information from the symbol-table entry is needed for semantic analysis and code

generation [1 Mark]

Syntax Analysis

The second phase of the compiler is the syntax analysis or parsing. The parser uses the first

components of the tokens produced by the lexical analyzer to create a tree-like intermediate

representation that depicts the grammatical structure of the token stream.

A typical representation is a syntax tree in which each interior node represents an operation and

the children of the node represent the arguments of the operation. [1 Mark]

Semantic Analysis

The semantic analyzer uses the syntax tree and the information in the symbol table to check the

source program for semantic consistency with the language definition. It also gathers type

information and saves it in either the syntax tree or the symbol table, for subsequent use during

intermediate-code generation.

Type checking implies that the compiler checks that each operator has matching operands.

For example, many programming language definitions require an array index to be an integer;

the compiler must report an error if a floating-point number is used to index an array.

The language specification may permit some type conversions called coercions. For example, a

binary arithmetic operator may be applied to either a pair of integers or to a pair of floating-point

numbers. If the operator is applied to a floating-point number and an integer, the compiler may

convert or coerce the integer in to a floating-point number. [1 Mark]

Page 187: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

186

4 Marks

Intermediate Code Generation

In the process of translating a source code into a target code, a compiler may construct one or

more intermediate representations, which can have a variety of forms. Syntax trees are a form of

intermediate representation; they are commonly used during syntax and semantic analysis.

After syntax and semantic analysis of the source program, many compilers generate an explicit

low-level or machine-like intermediate representation, which we can think of as a program for an

abstract machine. [1 Mark]

Code Optimization

The machine-independent code-optimization phase attempts to improve the intermediate code so

that better target code will result. Usually better means faster, but other objective may be desired,

such as shorter code, or target code that consumes less power.

A simple intermediate code generation algorithm followed by code optimization is a reasonable

way to generate good target code.

There is a great variation in the amount of code optimization different compilers perform. In

those that do the most, the so-called “ optimizing compilers”, a significant amount of time is

spent on this phase. There are simple optimizations that significantly improve the running time

of the target program without slowing down compilation too much. [1 Mark]

Code Generation

The Code generator takes as input an intermediate representation of the source program and

maps it into the target language. If the target language is machine code, registers or memory

locations are selected for each of the variables used by the program. Then, the intermediate

Page 188: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

187

instructions are translated into sequences of machine instructions that perform the same task. A

crucial aspect of code generation is the judicious assignment of registers to hold variables.

[1 Mark]

2b. What is an alphabet in the context of formal languages?

An alphabet, in the context of formal languages, can be any set, although it often makes sense to

use an alphabet in the usual sense of the word, or more generally a character set such as ASCII or

Unicode. Alphabets can also be infinite; e.g. first-order logic is often expressed using an alphabet

which, besides symbols such as ∧, ¬, ∀ and parentheses, contains infinitely many elements x0, x1,

x2, … that play the role of variables. [1 Mark]

2c. State the various uses of a symbol table. [1 Mark for each of any 3 of the 4 points]

An object file will contain a symbol table of the identifiers it contains that are externally

visible. During the linking of different object files, a linker will use these symbol tables to

resolve any unresolved references.

A symbol table may only exist during the translation process, or it may be embedded in the

output of that process for later exploitation, for example, during an interactive debugging

session, or as a resource for formatting a diagnostic report during or after execution of a

program.

While reverse engineering an executable, many tools refer to the symbol table to check

what addresses have been assigned to global variables and known functions. If the symbol

table has been stripped or cleaned out before being converted into an executable, tools will

find it harder to determine addresses or understand anything about the program.

At that time of accessing variables and allocating memory dynamically, a compiler should

perform many works and as such the extended stack model requires the symbol table

[3 Marks]

2d. What are fuzzy regular expressions?

Variants of regular expressions can be used for working with text in natural language, when it is

necessary to take into account possible typos and spelling variants. In such cases the mechanism

implements some fuzzy string matching algorithm and possibly some algorithm for finding the

similarity between text fragment and pattern. This task is closely related to both full text search

and named entity recognition. [2 Marks]

2e. What are the disadvantages of applying regular expressions in search engines?

While regular expressions would be useful on Internet search engines, processing them across the

entire database could consume excessive computer resources depending on the complexity and

design of the regex. [2 Marks]

2f. What are the applications of delimiters in regular expressions?

When entering a regular expression in a programming language, they may be represented as a

usual string literal, hence usually quoted; this is common in C, Java, and Python for instance, where

the regular expression re is entered as "re". However, they are often written with slashes as

delimiters, as in /re/ for the regular expression re. This originates in ed, where / is the editor

Page 189: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

188

command for searching, and an expression /re/ can be used to specify a range of lines (matching

the pattern), which can be combined with other commands on either side, most famously g/re/p as

in grep ("global regex print") [1 Mark]

2g. How does Java implement regular expressions?

Regular expression support is part of the standard library of many programming languages,

including Java and Python [1 Mark]

2h. The following non-left-recursive variant of the expression grammar will be used for top-

down parsing: E -> T E’

E’-> + T E’ | ϵ

T -> F T’

T’ -> * F T’| ϵ

F -> ( E ) | id

Can this Grammar be useful for illustrating techniques for handling ambiguities during compiler

parsing? (Answer = YES) [1Mark]

Provide an example to justify your choice of answer. The following non-left-recursive variant of

the expression grammar will be used for top-down parsing:

E -> T E’

E’-> + T E’ | ϵ

T -> F T’

T’ -> * F T’| ϵ

F -> ( E ) | id

The following Grammar be useful for illustrating techniques for handling ambiguities during

parsing because it treats + and * alike, so it is useful for illustrating techniques for handling

ambiguities during parsing:

E -> E + E | E * E | ( E )| id

Here, E represents expressions of all types.

[1.5 Marks]

2i. Mention Three (3) algorithms that decide whether and how a given regular expression matches

a string.

(iv) nondeterministic finite automaton

(v) deterministic finite automation

(vi) backtracking [1.5

Marks]

3a. Suppose a source program contains the assignment statement

Page 190: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

189

Position = initial + rate * 60,

Describe how this statement will be processed and represented from the first stage of a

compiler to the last stage of a compiler. [8 Marks]

1. Lexical Analysis

The characters in this assignment could be grouped into the following lexemes and mapped into

the following tokens passed on to the syntax analyzer:

(i) position is a lexeme that would be mapped into a token <id, 1>, where id is an abstract symbol

standing for identifier and 1 points to the symbol-table entry for position. The symbol-table entry

for an identifier holds information about the identifier, such as its name and type.

(ii) The assignment symbol = is a lexeme that is mapped into the token < = > . Since this token

needs no attribute-value, we have omitted the second component. We could have used any abstract

symbol such as assign for the token-name, but for notational convenience we have chosen to use

the lexeme itself as the name of the abstract symbol.

(iii) initial is a lexeme that is mapped into the token < id, 2 > , where 2 points to the symbol-table

entry for initial.

(iv) + is a lexeme that is mapped in to the token < + >.

Rate is a lexeme that is mapped into the token < id, 3 > , where 3 points to the symbol-table entry

for rate.

* is a lexeme that is mapped into the token < * > .

60 is a lexeme that is mapped into the token < 60 >

Figure 2. shows the representation of the assignment statement after the lexical analysis as the

sequence of tokens

< id, 1> < = > <id, 2> <+> <id,3> <*> <60> (Equa.2)

In this representation, the token names =,+, and * are abstract symbols for the assignment, addition,

and multiplication operators, respectively.

< id, 1> < = > <id, 2> <+> <id,3> <*> <60> (Equa.2) [2 Marks]

Syntax Analysis

This tree shows the order in which the operations in the assignment

position = initial + rate * 60

Are to be performed; The tree has an interior node labeled * with <id, 3> as its left child and the

integer 60 as its right child. The node <id, 3> represents the identifier rate. The node labeled *

makes it explicit that we must first multiply the value of rate by 60. The node labeled + indicates

that we must add the result of this multiplication to the value of initial. The root of the tree, labeled

=, indicates that we must store the result of this addition into the location for the identifier position.

This ordering of operations is consistent with the usual conventions of arithmetic which tells us

that multiplication has higher precedence than addition, and hence that the multiplication is to be

performed before addition. [1 Mark]

Page 191: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

190

Semantic Analysis

The semantic analyzer uses the syntax tree and the information in the symbol table to check the

source program for semantic consistency with the language definition. It also gathers type

information and saves it in either the syntax tree or the symbol table, for subsequent use during

intermediate-code generation.

Type checking implies that the compiler checks that each operator has matching operands.

For example, many programming language definitions require an array index to be an integer; the

compiler must report an error if a floating-point number is used to index an array.

The language specification may permit some type conversions called coercions. For example, a

binary arithmetic operator may be applied to either a pair of integers or to a pair of floating-point

numbers. If the operator is applied to a floating-point number and an integer, the compiler may

convert or coerce the integer in to a floating-point number [0.5 Mark]

Intermediate Code generation

In the process of translating a source code into a target code, a compiler may construct one or more

intermediate representations, which can have a variety of forms. Syntax trees are a form of

intermediate representation; they are commonly used during syntax and semantic analysis.

[0.5 Mark]

Code Optimization

Expressn 3. consists of the three-address code sequence (an intermediate form which consists of a

sequence of assembly-like instructions with three operands per instruction). Each operand can act

like a register.

t1 = inttofloat (60)

t2 = id3 *t1

t3 = id2 + t2

id1 =t3

(Expressn 3)

The optimizer can deduce that the conversion of 60 from integer to floating point can be done once

and for all at compile time, so the inttofloat operation can be eliminated by replacing the integer

60 by the floating-point number 60.0. Moreover, t3 is used only once to transmit its value to id1

so the optimizer can transform (Expressn 3.) into the shorter sequence

t1 = id3 * 60

id1 = id2 + t1 (Expressn 4.) [2 Marks]

Code Generation

For example, using registers R1 and R2, the intermediate code in Expression 4 might get

translated into the machine code

LDF R2, id3

MULF R2, R2, #60.0

LDF R1, id2

ADDF R1, R1, R2

Page 192: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

191

STF id1, R1 (Expressn 5) [2 Marks]

3b. Describe in English, the language defined and specified by }0:{ 2 icb ii

The set of all strings consisting of b’s followed by c’s in which the number of c’s is twice the

numbers of b’s . This set is { λ, bcc, bbcccc, bbbcccccc,…..} [3.5 Marks]

3c. (i) In a symbol table, a common implementation technique to use is called hashing

[0.5 Mark] (ii) Regular expressions can be used as pattern matching in text editors. [0.5 Mark]

(iii) Regular expressions can be used as lexical analysis in a compiler. [0.5 Mark]

3d. What is a formal language? A formal language L over an alphabet Σ is a subset of Σ*, that

is, a set of words over that alphabet. Sometimes the sets of words are grouped into expressions,

whereas rules and constraints may be formulated for the creation of 'well-formed expressions'.

[2 Marks]

3e. Grammars have significant benefits for both language designers and compiler writers.

Mention and discuss five (5) of them.

A grammar gives a precise, yet easy-to-understand, syntactic specification of a

programming language. 1 Mark

From certain classes of grammar, we can construct automatically an efficient parser that

determines the syntactic structure of a source program. 1 Mark

As a side benefit, the parser-construction process can reveal syntactic ambiguities and

trouble spots that might have slipped through the initial design phase of a language.

1 Mark

The structure imparted to a language by a properly designed grammar is useful for

translating source programs into correct object code and for detecting errors. 1 Mark

A grammar allows a language to be evolved or developed iteratively, by adding new

constructs to perform new tasks. These new constructs can be integrated more easily into

an implementation that follows the grammatical structure of the language 1 Mark

3f. (i) When is a set of languages said to be closed under a certain operation?

[1 Mark]

(ii) Mention any application of languages in computer science?

It can be used for rewriting strings on formal grammars.

It can also be useful in compiler construction [1 Mark]

(vii) Mention any application of regular expressions in real life?

The use of regular expressions in structured information standards for document

It can also be used for database modeling [1 Mark]

(viii) What is Formal semantics? The study of interpretations of formal languages is called

formal semantics [1 Mark]

4a. Describe the interactions between a lexical analyzer, parser and a symbol table. If possible

support with a suitable diagram.

Page 193: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

192

A simple way to build lexical analyzer is to construct a diagram that illustrates the structure of the

tokens of the source language, and then to hand-translate the diagram into a program for finding

tokens. Efficient lexical analyzers can be produced in this manner.

Role of a Lexical Analyzer

The lexical analyzer is the first phase of compiler. Its main task is to read the input characters and

produces output a sequence of tokens that the parser uses for syntax analysis. As in the figure,

upon receiving a get next token command from the parser the lexical analyzer reads input

characters until it can identify the next token. 1 Mark

Tokens, interactions btw lexical analyzer and the parser

Diagram = 3 Marks

Since the lexical analyzer is the part of the compiler that reads the source text, it may also perform

certain secondary tasks at the user interface. One such task is stripping out from the source program

comments and white space in the form of blank, tab, and new line character. Another is correlating

error messages from the compiler with the source program. 1 Mark

The lexical analyzer returns to the parser a representation for the token it has found. The

representation is an integer code if the token is a simple construct such as a left parenthesis,

comma, or colon .The representation is a pair consisting of an integer code and a pointer to a table

if the token is a more complex element such as an identifier or constant .The integer code gives

the token type, the pointer points to the value of that token .Pairs are also retuned whenever we

wish to distinguish between instances of a token. 1 Mark

4b. (i) Mention Four (4) Functions of a compiler. [0.5 mark for any of the four points]

The primary function of a compiler is that it is used for programs that translate source codes

from a high-level programming language to a lower level language (e.g., assembly

language or machine code).

Page 194: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

193

Furthermore, compiler is likely to perform many or all of the following operations or

functions, namely:

lexical analysis

preprocessing

parsing

semantic analysis (Syntax-directed translation),

code generation

code optimization [2 Marks]

(ii) Discuss the relevance of modeling to compiler design and implementation

The study of compilers is mainly a study of how we design the right mathematical models and

choose the right algorithms, while balancing the need for generality and power against simplicity

and efficiency. Some of the most fundamental models are finite-state machines and regular

expressions. These models are useful for describing the lexical units of the program s(keywords,

identifiers, and such) and for describing the algorithms used by the compiler to recognize those

units.

Also, among the most fundamental models are context-free grammars, used to describe the

syntactic structure of programming languages such as nesting of parentheses or control constructs.

Similarly, trees are an important model for representing the structure of programs and their

translation into object code. [4 Marks]

4c. Explain the equivalence of regular expressions.

It is possible to write an algorithm which for two given regular expressions that decides whether

the described languages are essentially equal, reduces each expression to a minimal deterministic

finite state machine, and determines whether they are isomorphic (equivalent) [2 Marks]

4d. Mention Three (3) software libraries that work with fuzzy regular expressions.

(0.5 marks each) Some software libraries work with fuzzy regular expressions:

TRE – well-developed portable free project in C, which uses syntax similar to POSIX

FREJ – open source project in Java with non-standard syntax (which utilizes prefix, Lisp-

like notation), targeted to allow easy use of substitutions of inner matched fragments in

outer blocks, but lacks many features of standard regular expressions.

agrep – command-line utility (proprietary, but free for non-commercial usage).

[1.5 Marks]

4e. Mention Five (5) scripting languages that support regular expressions.

(0.5 marks for each answer)

Python, Perl, Tcl, PCRE (Perl Compatible Regular Expressions), PHP, ECMAScript

[2.5 Marks] 4f. What is a symbol table?

Symbol Tables are data structures that are used by compilers to hold information about source-

program constructs. The symbol table is a data structure containing a record for each variable name

Page 195: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

194

with fields for the attributes of the name. The data structure should be designed to allow the

compiler to find the record for each name quickly and to store or retrieve data from that record

quickly. [1 Mark]

4g. At the most basic conceptual level, what are the functions of a parser?

At the most basic conceptual level, a parser, usually generated by a parser generator like yacc,

attempts to decide if the source program is valid, that is if it belongs to the programming language

for which the compiler was built. [2 Marks]

4h. What is an empty language?

An empty language is a language which contains no words at all (L = ∅). [1 Mark]

4i. (i) Describe in English the set defined by b* ({c} | {d}) e*

The set of all strings consisting of zero or more b’s , followed by either c or d, followed

by zero or more e’s [1.5 Marks]

(ii) Show that {λ}| b+ = b*

{λ}| b+= {λ}| {b,bb,bbb,….}={λ, b,bb,bbb,…..} = b* [1.5 Marks]

(iii) Show that (b+)? = b*

(b+)? = {λ}| b+ = {λ}|{b,bb,bbb,…..} = b* [1.5 Marks]

5a. Draw the structure of a compiler and its corresponding components

[10Marks]

Page 196: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

195

5b. Given that, AB is the set of all strings that can be formed by concatenating a string A with a

string B. For example, if A= {b, cc} and B = {d, dd}, then derive

(i) AB={bd,bdd, ccd,ccdd} [1.5 Marks]

(ii) BA= {db,dcc, ddb,ddcc} [1.5 Marks]

5c. (i) (bcd)* = {λ, bcd,bcdbcd,bcdbcdbcd,……..} [2 Marks]

(ii) bcc* = { bb λ, = bb, bbc, bbcc,bbccc,…..} [2 Marks]

5d.(i) Describe in English the language defined and specified by }0:{ 2 icb ii

The set of all strings consisting of b’s followed by c’s in which the number of c’s is twice the

numbers of b’s . This set is { λ, bcc, bbcccc, bbbcccccc,…..}

[2.5 Marks]

(ii) List all the strings of length 3 in {b,cc}*

bbb, bcc, ccb [2 Marks]

(iii) Is ccbcc ϵ {b,cc}*

Yes, To confirm this, subdivide ccbcc into cc, b and cc, all of which are elements of {b,cc}.

[2 Marks]

(iv) List all strings in b* cb* of length less than 3.

c, bc, cb. [2 Marks]

5e. (i) Write an expression using the star operator which defines the same set as

}.2,1,0:{ rqpdcb rqp

b* cc* ddd* [3 Marks]

(1 x 5 marks)

Page 197: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

196

COVENANT UNIVERSITY

CANAANLAND, KM 10, IDIROKO ROAD

P.M.B. 1023, OTA, OGUN STATE, NIGERIA TITLE OF EXAMINATION: B.Sc EXAMINATION

COLLEGE: SCIENCE AND TECHNOLOGY

SCHOOL: APPLIED AND NATURAL SCIENCES

DEPARTMENT: COMPUTER & INFORMATION SCIENCES

SESSION: 2015/2016 SEMESTER: ALPHA

COURSE CODE: CSC 319 CREDIT UNIT: 2

COURSE TITLE: OPERATION RESEARCH TIME: 2 HOURS

INSTRUCTION: ATTEMPT QUESTION 1 AND ANY OTHER TWO QUESTIONS

1(a) Glapetto’s wooden soldiers and trains. Each soldier sells for N27, uses N10 of raw materials and

takes N14 of labour& overhead cost. Each train sell for N21, uses N9 of raw materials, and takes

N10 of overhead cost. Each soldier needs 2 hours finishing and 1 hour carpentry; each train need

1 hour finishing and 1 hour carpentry. Raw materials are unlimited, but only 100 hours of finishing

and 80 hours of carpentry are available each week. Demand for trains is unlimited; but at most

40 soldiers can be sold each week.

(i) Identify each component of Linear programming model from this scenario above

(6marks)

(ii) Formulate the problem as a linear programming problem.

(5marks)

1(b) A timber processing factory requests that a construction supplies on daily basis a minimum of 10

units of mahogany and 8 units of Teakwood and 6 units of man Sonia wood. the contractor

services the factory from his sources R and S. If the cashier makes two daily trips for R and S cost

N10,000 and N16, 000 respectively, determine the minimum cost of transporting the units of

wood to the factory using graphical solution approach. The table below shows the unit delivered.

(7marks)

Page 198: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

197

1(c) Suppose an auto company has three plants in cities A, B and C and two major distribution centers

in D and E. The capacities of the three plants during the next quarter are 1000, 1500 and 1200

cars. The quarterly demands of the two distribution centers are 2300 and 1400 cars. The

transportation costs (which depend on the mileage, transport company etc) between the plants

and the distribution centers is as follows: (7marks)

Which plant should supply how many cars to which outlet so that the total cost is minimum use.

Determine the initial BF solution using North west method criterial

1(d) Given the network below Use the prim’s algorithm to determine the minimum spanning tree.

(5marks)

2(a) State how to determine Pivot column, Pivot row and pivot number?

(6Marks)

2(b) An industry manufactures for sale two products- Plates and Sandals, from the materials-

bem, tem, and pem, which are the short supply. The supply of each raw material is limited

Sources Mahogany Teak Man Sonia

R 4 2 2

S 2 4 2

1

2

4

5

5

8

8

6

6

7 8

6

3

Page 199: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

198

to 240, 120 and 200 respectively. The contribution per product is N100 per plate and N160

per sandal. The usage of these raw materials per product is as follows

Material/Unit Plate Sandal

Bem 6 2

Tem 2 2

Pem 2 4

(i) Formulate the problem in Linear Programming problem by introducing slack variables

(

3marks)

(ii) Use Simplex method to determine optimum solution

(8marks)

(iii) How many units of plates and sandal should be produced to maximized profit? (2

marks)

(iv) What is the total profit for the company?

(1marks)

3(a) State the Prim’s algorithm. (5marks)

3(c) Using the network below

(i) Formulate the problem in LP model (5marks)

(ii) Find the shortest path (show the path and determine the weight) for the directed network below using Dijkstra’s algorithm (5marks)

Page 200: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

199

(ii) Determine the optimality of the solution using the Dual visible solution by inspection. (5marks)

(4a) Turkish national swimming team coach is putting together a relay team for the 400 meter relay.

Each swimmer must swim 100 meters of breaststroke, backstroke, butterfly, or free style. The

coach believes that each swimmer will attain the times (seconds) given in the Table below. To

minimize the team’s time for the race, assign each swimmer for a stroke.

(10mar

ks)

4(b) A publishing store transfers supplies from four principal manufacturers to four regional stores.

The manufacturers are located at Oyo, Osun, Lagos,Abia. The regional stores are located in PH,

Kano, Ogun, and Benue. In order to reduce the cost of meeting demand for suppliers, The

company has decided to allocate its books according to the standard transportation model. An

analysis of daily transferring records reveals that the following costs per unit are typical for the

current operation. (10marks)

1

20

15

3

4

6

7

20

15

20

2 5 25 1

0

30

20

10

15

Page 201: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

200

(i)

Formulate the appropriate parameter table for the scenario above

(ii) Use least Cost Method to determine the initial transfering solution.

5 An electronics manufacturing company also produces speakers for the manufactured television sets. It does a continuous assembly production of 8000 sets per month; speakers are produced in batches (large quantity, short time) and put in inventory till the needed time. The expenses to initiate each production is $12000, the unit speaker production cost is $10 independent of batch size. Keeping each speaker before usage is $0.30 per month. Each unavailable speaker when needed is of $1.10 disadvantage per month to the company.

a. Calculate the optimized quantity and optimized production time. (4.5 marks) b. If planned shortages are permitted in this question, the shortage cost p is estimated at $1.10.

i. Calculate the optimized shortage cost (4 marks) ii. Calculate the optimized quantity of production (3 marks) iii. Calculate the optimal interval of production (4 marks) iv. Calculate the maximum shortage (2 marks)

5(c) Mention five (5) products or services that require a stochastic single-period model for perishable

products for their inventories. (2.5 marks)

PH Kano Ogun Benue Transfers

Oyo 30 30 26 21.50 140

Osun 23 25 26 15.50 100

Lagos 30.5 35 30.5 42 160

Abia 32 21.50 21.50 24.50 140

Needs 110 70 170 90

Page 202: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

201

COVENANT UNIVERSITY

CANAANLAND, KM 10, IDIROKO ROAD

P.M.B. 1023, OTA, OGUN STATE, NIGERIA TITLE OF EXAMINATION: B.Sc EXAMINATION

COLLEGE: SCIENCE AND TECHNOLOGY

SCHOOL: APPLIED AND NATURAL SCIENCES

DEPARTMENT: COMPUTER & INFORMATION SCIENCES

SESSION: 2015/2016 SEMESTER: ALPHA

COURSE CODE: CSC 319 CREDIT UNIT: 2

COURSE TITLE: OPERATION RESEARCH MARKING SCHEME TIME: 2 HOURS

INSTRUCTION: ATTEMPT QUESTION 1 AND ANY OTHER TWO QUESTIONS

1(a) Solution

(i) Decision variables Chair andTable as Parameter (x1 and x2 respectively) The Constrains are Finishing time per week Carpentry time per week Weekly demand for Chair Objective function Max z = 3x1 + 2x2

(ii) Max z = 3x1 + 2x2 Subjected to

2x1 +x2 100 (Finishing constraint)

x1 +x2 80 (Carpentry constraint)

x1 40 (Constraint on demand for Chair)

x1,x2 0 (sign restriction)

1(b)

Page 203: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

202

let x1 = number of trip made from R

let x2 = number of trip made from S

.

minimize C = 10000x1 + 16000x2

subject to 4x1 +2x2 10

2x1 + 4x2 8

2x1 +2x2 6

and x1 0, x2 0

1st Constraint 4x1 +2x2 10

→ 4x1 +2x2 =10. the points are (0,5) and (2.5,0)

2nd Constraint 2x1 + 4x2 8

→ 2x1 + 4x2 = 8. the points are (0,2) and (4,0)

3rd Constraint 2x1 + 2x2 6

→ 2x1 + 2x2 = 6. the points are (0,3) and (3,0)

The equilibrium point (the intercession point of the three graphs) is determine by solving simultaneous equation

4x1 +2x2 =10 (1)

2x1 + 4x2 = 8 (2)

We have B (2,1)

Similar solution for

2x1 + 4x2 = 8 and 2x1 + 2x2 = 6 or

Page 204: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

203

4x1 +2x2 =10 and 2x1 + 2x2 = 6

The feasible solution occurs at points bounded outwardly by points A(0,5); B (2, 1) and G(4,0)

So, using the Objective function

C = 10000x1 + 16000x2 for the three feasible solution coordinates we have:

A(0,5) we have C= 80,000

B(2,1) we have C= 36,000

G(4,0) we have C = 40,000

The optimal point is the point with the least value since is a minimization problem.

So, (2,1) is the optimum point with cost of N36,000 at x1 = 2 and x2 = 1.

Recommendation

2 trips from R and just 1 trip from S should be made to minimize cost

1(c)

Dist Center

D

Dist Center

E

Capacity

Plant A 80 215 1000 1000 0 0 0

A(

D(

E(

G(

0

D

B(

Fea

4

x

2

x

C(

F(

2

x

1000

Page 205: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

204

Plant B 100 108 1500 1500 1500 200 0

Plant C 102 68 1200 0 0 0 0

Demands 2300 1400

2300 200

1300 200

0 200

0 0

The least Distance is 68 found in Plant C, Dist Center E

The next is 80 found in Plant A Dist Center D

The next is 100 found in Plant B Dist Center D

The next is 108 found in Plant B Dist Center E

Initial BF = 80*1000 + 100*1300+ 108*200+68*1200 = 80000+130000+21600+81600 =313200

1(d)

1. Find out which arc has minimum weight.

2. Put this arc into the spanning tree

3. Separate the node into two sets

eg S1.{1,2}

S2{3,4,5} .. Not yet come into the spanning tree.

4. Find out the connectivity between S1 and S2

Chose the one with minimum weight

If there is a tie take either of them

5. Update the S1 and S2

S1{1,2,3}

s2{4,5}

• S1{1,2,3,5}

1200

1300 200

2

1

5

2

1

5

3 6

2

1

5

3 6

5

6

Page 206: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

205

• S2{4}

• S1{1,2,3,5,4}

• S2{}

w=25

2(a)

Select the pivot column. The column with the largest positive number in the bottom row (P)

Determine the pivot row. We use Minimum Ratio Rule(MRR) by dividing each amount in the quantity

column by the corresponding number in the pivot column selected in step 3. The row with the smallest

nonnegative number calculated is the pivot row.

Therefore, the number at the intersection of the pivot row and pivot column is the pivot number.

2(b)

Let x rep. plate and y rep. sandal

Objective function (Max) P = 100x + 160y

Constraints 6x +2y 240

2x + 2y 120

2x + 4y 200

Introducing slack variables, we have

6x +2y + s1 =240

2x + 2y + s2 = 120

2x + 4y + s3 =200

First Initial simplex table

x y s1 s2 s3 b basic

6 2 1 0 0 240 s1

2 2 0 1 0 120 s2

2 4 0 0 1 200 s3

-100 -160 0 0 0 0 P

2

1

5

3 6

5

4

8

6

Page 207: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

206

Determine the pivot column, row and number

Pivot column is 2nd column because it has the largest negative profit

The pivot row

Using the Minimum Ratio Rule(MRR) by dividing each amount in the quantity column by the corresponding number in the pivot column

240/2 = 120; 120/2 = 60 and 200/4 = 50

Therefore the pivot row is row 3 since it has the smallest nonegative ratio

The pivot is 4 being the intercession of column 2 and row 3

x y s1 s2 s3 b basic

6 2 1 0 0 240 s1

2 2 0 1 0 120 s2

2 4 0 0 1 200 s3

-100 -160 0 0 0 0 P

Determine the pre simplex table

Divide every element in pivot row by pivot number to make pivot number = 1

Page 208: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

207

Determine the optimality of the solution

Since column P is still has negative value therefore we have to improve the solution.

x y s1 s2 s3 b basic

5 0 1 0 -1/2 140 s1

1 0 0 1 -1/2 20 s2

1/2 1 0 0 1/4 50 y

-20 0 0 0 40 8000 P

Determine the new pivot column, row and number

The pivot column is the 1st column, containing the largest negative value of p

The pivot row is calculated thus: 140/5 = 24; 20/1 = 20; 50/(1/2) = 100

Therefore the pivot row is row 2 with smallest non negative ratio

The pivot number is 1 being the intercession of row 2 and column 1

x y s1 s2 s3 b basic

5 0 1 0 -1/2 140 s1

1 0 0 1 -1/2 20 s2

1/2 1 0 0 1/4 50 y

-20 0 0 0 40 8000 P

Determine the pre simplex table

Divide every element in pivot row by pivot number to make pivot number = 1

Page 209: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

208

Determine the new simplex table

Compute new values for each remaining row so as to make the remaining element on pivot column zero.

Determine the optimality of the solution

Page 210: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

209

Since column P is has positive values therefore we have found an optimal solution and the maximum profit value is the absolute value of the quantity constant for P. = N8, 400.00K.

Decision/ Recommendation

For the company to maximize its profit, it must produce 20 plates and 40 chairs for the total profit of N8, 400.00K.

Note: P = N100(x) + N160 (y) = 100(20) + 160(40)

= N(2000 + 6400)

= N8400

3(a) State the Prim’s algorithm.

1. Find out which arc has minimum weight.

2. Put this arc into the spanning tree

3. Separate the node into two sets

4. Find out the connectivity between S1 and S2

Chose the one with minimum weight

If there is a tie take either of them

5. Update the S1 and S2

Page 211: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

210

3(b)(i)

3(b)(ii)

1

20

15

3

4

6

7

20

15

20

2 5 25 1

0

30

20

10

15

Ist Pass

1-2

15

1-3

20

2nd

Pass

1-3 20

4th

Pass

1-2-5

40

1-3-6

40

1-2-4-5

Page 212: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

211

3(b) (iii)

Dual:

Max w1-w7

Constraints

w1 – w2 15 eqn

w1 – w3 20 ineq

w2 – w4 10 ineq

Let w7=0 ,

w6=20,

w5=10,

w4=30,

w3=40,

w2=35,

w1=50

Dual Visible solution by inspection

Page 213: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

212

(4a)

1 2 3 4

1 4 2 0 2

2 0 4 0 0

3 0 2 3 5

4 4 0 2 0

1 2 3 4

1 54 54 51 53

2 51 57 52 52

3 50 53 54 56

4 56 54 55 53

1 2 3 4

1 3 3 0 2

2 0 6 1 1

3 0 3 4 6

4 3 1 2 0 1 2 3 4

1 3 2 0 2

2 0 5 1 1

3 0 3 4 6

4 3 0 2 0 1 2 3 4

1 4 2 0 2

2 0 4 0 0

3 0 2 3 5

4 4 0 2 0

Row reduction

Colum reduction

Add the smallest uncovered to the intercession and subtract from every uncovered

Allocation of the swimming assignment to swimmers

Page 214: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

213

51+52+50+54 =207

4(b)

Total Cost = 30*10 + 26*130 +23*10 +15.50*90 +30.5*100 + 35*60 + 21.50*40 +0*100 =

300+3380+230+1395+3050+2100 +860+0 = 11,315

5(a)

The value of Q, say Q*, that minimizes T(total cost per unit time) is found by :

Q*=√2aK/h……………………………………………………i

The corresponding cycle time, say t* is found by:

t*=Q*/a==√2K/ah………………………………….ii

Q* = √(2)(8000)(12000)/0.30=25298…………..using i

t* = 25298/8000 = 3.2months……………………..using ii (4.5 marks)

5b

i) If planned shortages are permitted in the speaker example, the shortage cost is estimated as p

= 1.10.

As before, K=12000, h=0.30, a=8000

S* =√2aK/h. √ p/ p+h

S*= (√(2)(8000)(12000)/0.30).(√1.1/1.1+ 0.3) = 22,424. (4marks)

PH Kano Ogun Benue Extra Transfers

Oyo 30 30 26 21.50 0 140,10,0

Osun 23 25 26 15.50 0 100,10,0

Lagos 30.5 35 30.5 42 0 160,60,0

Abia 32 31 21.50 24.50 0 140,40,0

Needs 110,100,0 70,60,0 170,130,0 90,0 100,0

100

90

40

10

130 10

60 100

Page 215: COVENANT UNIVERSITY · algebra, computer algebra, cryptography, computer science, chemistry and the visual and musical arts. It is one of the foundations of number theory, touching

214

ii Q* = √2aK/h. √p+h/p

= (√(2)(8000)(12000)/0.30) . (√1.1+0.3/1.1) = 28,540 (3marks)

iii t*= Q*/a = 28540/8000 = 3.6months. (4 marks)

iv Maximum Shortage = Q*- S* = 28540 – 22424 = 6116 (2 marks)

5(c)

1. Periodicals, such as newspapers and magazines.

2. Flowers being sold by a florist. 3. Seasonal greeting cards.

4. The makings of fresh food to be prepared in a restaurant.

5. Produce, including fresh fruits and vegetables, to be sold in a grocery store.

6. Christmas trees. 7. Airline reservation 8.Fashion goods that will be out of style soon.

9. Seasonal clothing, such as winter coats, where any goods remaining at the end of the season

must be sold at highly discounted prices to clear space for the next season.