Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
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.
COVENANT UNIVERSITY
ALPHA SEMESTER TUTORIAL KIT (VOL. 2)
P R O G R A M M E : C I S
200 LEVEL
2
LIST OF COURSES
CSC213: Structured Programming
CSC214: High Performance and Database Management System
*CSC215: Mathematical Methods I
CSC216: Foundations of Parallel and Sequential Programming
*Not included
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: 2015/2016 SEMESTER: ALPHA
COURSE CODE: CSC 213 CREDIT UNIT: 3
COURSE TITLE: STRUCTURED PROGRAMMING
INSTRUCTION: ANSWER ANY FOUR QUESTIONS Time: 2 1
/2 Hours
1. a) What is Structured Programming? 1.5 marks
b) A program is Structured if it uses ______ and ______. 2 marks
c) Give Three (3) differences between Structured and Object Oriented Programming.
3 marks
d) What is an Algorithm. Mention the fundamental properties of a good Algorithm.
4 marks
f) Write the algorithm and draw the flow chart to compute the GPA for a student using the formula GPA
=Total_GP/Total_Credit 7 marks
2. a) Given;
>>> a = set (’abracadabra’)
>>> b = set (’alacazam’)
What is
i. >>> a – b
ii. >>> a | b
iii. a & b
iv. >>> a ^ b 2Marks
4
b) Give the syntax and examples of the following statements in python;
i. If statement
ii. The if statement with alternative execution
iii. Chained conditional statements
iv. While statements 6Marks
c) Write a program that converts Fahrenheit to centigrade using the formula c=(5/9)*(F-32) and stores the result
in a file like this
7Marks
d) Write the python program to display the following interface;
21/2Marks
3. a) Explain the following and give examples
i. Tuples
ii. Dictionary
iii. Sets 41/2Marks
b) Write a program in python to check if a number is even. (input 2 output true, input 3 : output false). Make sure your
program takes care of invalid inputs 4Marks
c) Implement the linear search algorithm in python such that you can search for members of the following array,
declared and initialized in your program 13,0,1,7,4 9Marks
4. a) Given;
tuple= (‘abcd’, 786, 2.23, ‘john’, 70.2)
tinytuple =(123 , ‘john’)
5
What is the output of;
i. print tuple[0]
ii. print tuple[1:3]
iii. print tuple[2:]
iv. print tuple*2
v. print tuple + tinytuple 21/2Marks
b) Write a python program to calculate the sum of the first 10 terms of the series.
1/1 + ¼ + 1/9 + 1/16………………….. 4Marks
c) Write a program that generates a table of factorials FROM 0 TO 10 like this
0! =0
1!=1
2!=2
3!=6
4!=24 5Marks
d) The following are used for what in Tkinter;
i. The pack Method
ii. The grid Method
iii. The place Method. 6 Marks
5. a) Write a python program to design a GUI like this
i. To receive two numbers
ii. Add, subtract, multiply or divide them
iii. Displays the result of any action taken by clicking any of the buttons.
10 Marks
6
b) Explain in details the concept of Modularity in structured programming. 31/2Marks c) Give a detailed
overview of python programming State four application domains with examples of Python programming language.
4 Marks
6. a) Create a file object in Python, and write “Covenant University is Great” to a file named output.txt
1.5Marks
b) What is the output of the program below?
4 Marks
c) Given the List Below:
What would be the outputs of the following print statements? 8 Marks
i. print (myList)
ii. print (len(myList))
iii. print (len(myList[2]))
iv. print (len(myList[2][0]))
v. print (myList[1])
vi. print (myList[2])
vii. print (myList[1][1])
viii. print (myList[2][0]+ myList[2][1]+myList[2][2])
d) Convert the following mathematical expression to a function called ‘EUD’ in Python.
√∑(𝑥𝑖 − 𝑦𝑖)2
𝑛
𝑖=1
7
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: CSC213
CREDIT UNIT: 3 COURSE TITLE: Structured Programming
INSTRUCTION: Instruction(s): Answer ANY FOUR Questions
TIME: 3 HOURS
1. a) Briefly explain the main problem of computer programming addressed by Structured Programming
31/2 Marks
b) State the three main features of structured programming. Describe the fundamental ideas in each
of them. 9 Marks c)
Compare and contrast between the Structured Programming and Object Oriented Programming.
5Marks
2. a. Explain in details the concept of Modularity in structured programming.
3½ Marks
b. Give a detailed overview of python programming State four application domains with examples
of Python programming language. 8 Marks.
c. Briefly state with appropriate examples, the types of Control Structures in Python
Programming. 6 Marks
3. a) Write a python program to calculate the factorial of a positive integer quantity. The program should
call another function called factorial. 7½ Marks
b) What does the following function do?
def find (strng, ch):
index = 0
while index < len (strng):
if strng [index] == ch:
return index
index += 1
return -1 3Marks
c) Define a string S of four characters: S = "spam". Write an assignment that changes the string
to "slam", using only slicing and concatenation.
8
4Marks
d) Fill in the blank spaces;
>>> s = "Peter, Paul, and Mary"
>>> print s [0:5]
……..
>>> print s [7:11]
…….
>>> print s [17:21]
……. 3Marks
4. a) Write a python program that adds two values gotten from two different functions.
– The first function should calculate the sum of even numbers between 1 and100.
– The second function should calculate the sum of odd numbers between 1 and 100
– In the main function, calculate and print the sum of the results from the first two functions.
7½Marks
b) Find the error in the following code segment and provide the correct code segment:
def username_pin()
database = [
['adesuwa', '1234'],
['innocent', '4242'],
['smith', '7524'],
username = rawinput('User name: ')
pin = rawinput('PIN code: ')
if [usernme, pin] in database
Print 'Access granted'
else:
print 'Access denied') 6Marks
c) Explain and give examples of the following;
i. Lists
ii. Strings 4Marks
5. a) Write a function named is_divisible_by_3 that takes a single integer as an argument and prints “This
number is divisible by three.” if the argument is evenly divisible by 3 and “This number is not divisible
by three.” otherwise.
Now write a similar function named is_divisible_by_5. 7½ Marks
b) Give examples of the following statements in python;
i. If statement
ii. The if statement with alternative execution
iii. Chained conditional statements
9
iv. While statements 6Marks
c) What will be the output of the following programs?
i. .>>> a_list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> a_list[1:3] = [ ]
>>> print a_list
ii. >>> fruit = ["banana", "apple", "quince"]
>>> fruit[0] = "pear"
>>> fruit[-1] = "orange"
>>> print fruit
iii. >>> range(10)
iv. >>> range(1, 10, 2) 4Marks
6. a) Write a python program that will accept the students score in a course and print the letter grade as
follows:
• 70 and above: A
• 60-69 B
• 50-59 C
• 45-49 D
• Below 45 F
Note: make sure you take care of scores less than 0 and greater than 100
5Marks
b) i. What two common syntaxes are required in a C-like language, but omitted in Python?
2Marks
ii. How are the statements in a nested block of code normally associated in Python?
2Marks
c) What does the following program do.
infile = open('test2.txt', 'r')
outfile = open('test.txt', 'w')
while True:
text = infile.read()
if text == "":
break
outfile.write(text)
infile.close()
outfile.close()
3½Marks
d) Write a python program to calculate the sum of the first 10 terms of the series.
1/1 + ¼ + 1/9 + 1/16………………….. 5 Marks
10
MARKING SCHEME
1. (a) State and explain the main problem of computer
programming addressed by structured programming?
To minimize Program complexity. (1.5Marks)
Most programs that do anything significant in the real world are rather long .i.e. word processor, OS,
Compiler, Enterprise software- banking software. They have complicated interrelated parts and
contain several thousand or even millions lines of codes which makes them very difficult to
understand, maintain and reuse. (2Marks)
1. (b) State the three main features of structured programming?
Describe the fundamental ideas in each of them.
Three main aspects:
Top-down analysis for problem solving
Modularization for program structure and organization,
Structured code for the individual modules. (3Marks)
Description:
Top down analysis is a method of problem solving. The essential idea is to subdivide a large problem
into several tasks or parts. Top down analysis, therefore, simplifies or reduces the complexity of the
process of problem solving.
Modular programming is a method of organizing these instructions. Large programs are broken
down into separate, smaller sections called modules, subroutines, or subprograms. Each module has
a specific job to do and is relatively easy to write.
Structured codes: In SP, are organized within various control structures. A control structure
represents a unique pattern of execution for a specific set of instructions. It determines the precise
order in which that set of instructions is executed. (6Marks)
1.(c) Compare and contrast between the Structured Programming
and Object Oriented Programming (5Marks)
Structured Programming Object Oriented Programming
Structured or procedural
programming is a programming
paradigm that attempts to divide
the problem into smaller blocks or
OOP is a programming paradigm that
program is written as a collection of
interacting objects.
11
procedures which interact with
other.
In structured programs the blocks
are pieces of code which are
executed as the program is run
In object-oriented programs objects have
lives of their own – they can be created,
copied, destroyed or even lost!
Structured programming is a
programming technique in which
the programmer divides the source
code into logical chunks of code.
Using structured programming
techniques, programs are typically
organized around code. This
approach can be thought of as
“code acting on data.”
Object-oriented programming is a
programming technique in which programs
work the other way around. They are
organized around data, with the key
principle being “data controlling access to
code.” In an object-oriented language, you
define the data and the routines that are
permitted to act on that data. Thus, a data
type defines precisely what sort of
operations can be applied to that data.
In Structured programming, the
program is built around functions
and /or modules which are nothing
but reusable pieces of programs.
Typically it follows a top-down
design approach with block-
oriented structures.
The object-oriented programming paradigm
is built on the foundation laid by the
structured programming concept. Object-
oriented programming took the best ideas of
structured programming and combined them
with several new concepts. In object-
oriented programming, the program is built
around objects which combine data and
functionality.
In Structured programming, the
program is built around
functions and /or modules
which are nothing but reusable
The object-oriented programming paradigm is
built on the foundation laid by the structured
programming concept. Object-oriented
programming took the best ideas of structured
12
pieces of programs. Typically it
follows a top-down design
approach with block-oriented
structures.
programming and combined them with several
new concepts. In object-oriented programming,
the program is built around objects which
combine data and functionality.
In structured programming large
programs are broken into
smaller pieces called
subprograms. Each subprogram
can have it own data and logic.
The base composition of any
type of structured programming
includes three fundamental
elements: sequencing, selection
and repetition.
OOP provide a new way of organizing data and
code that promises increased control over the
complexity of the software development
process. The major difference is that OOP treat
data as critical elements (as it should be) in the
program development and do not allow it to
flow freely around the system.
In OOP the focus is not on the code but on
what you want the code to do. Basic concepts
of OOP: object, class, inheritance, methods,
Encapsulation and polymorphism.
2. (a) Explain in details the concept of Modularity.
(3.5Marks)
It is a method of organizing computer instructions. Large programs are broken down into
separate, smaller sections called “Modules, Subroutines, or Subprograms”. Each module has
a specific task/operation to execute which is relatively less complexity to achieve.
2. (b) Give a detailed overview of Python Programming. State four
application use cases of python, stating two (2) examples in
each case. (8Marks)
A versatile, interpreted, high-level, & dynamic programming language.
Multi-paradigm: Simple procedural programming, OOP & Functional programming.
Easy to Learn: Automatic mememory mgt, high-level built-in data structures & libraries.
Highly Readable: Intuitive syntax, Interpreted language, dynamic typing, etc.
13
Portable Language: Many Versions-CPython, Jython, IronPython, PyPy
Extensibility: Reusable Codes-Module & Packages, Open Source, Modularity.
Application Areas:
Application development, e.g 3D games, GUI-based applications, etc
Web development, e.g Youtube, Reddit, Yelp, etc
Scientific computing, e.g Bioinformatics, NLP, machine learning, etc.
Scripting, e.g OpenOffice, Games, Emacs, Blender, etc.
2. (c) Briefly state with appropriate examples the types of Control
Structures in Python Programming. (6Marks)
Conditionals: if Stmts, elseIf/elif Stmts, *No Switch Stmt in Python.
Loop: while Stmts.
Continue and Break Statements.
Examples:
if & elseif Stmts.
if conditionExpr1: statement1
elif conditionExpr2: statement2
elif conditionExpr2: statement2
… …
else: statement4
Examples:
while Stmt.
while conditionExpr: statement
Examples:
continue & break Stmts.
Expr while conditionExpr: statement
if conditionExpr1: continue statement1
if conditionExpr2: break
3. .a) Python program to display the Fibonacci
# sequence up to n-th term using
14
# recursive functions
def recur_fibo(n):
"""Recursive function to
print Fibonacci sequence"""
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
# take input from the user
nterms = int(input("How many terms? "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
b) find is the opposite of the [ ] operator. Instead of taking an index and extracting the
corresponding character, it takes a character and finds the index where that character
appears. If the character is not found, the function returns -1.
c)
>>> S = "spam"
>>> S = S[0] + 'l' + S[2:]
>>> S
'slam'
>>> S = S[0] + 'l' + S[2] + S[3]
>>> S
'slam'
d)
>>> s = "Peter, Paul, and Mary"
>>> print s [0:5]
Peter
>>> print s [7:11]
Paul
>>> print s [17:21]
Mary
4. a)
15
b)
def username_pin():
database = [
['adesuwa', '1234'],
['innocent', '4242'],
['smith', '7524'],
]
username = raw_input('User name: ')
pin = raw_input('PIN code: ')
if [username, pin] in database:
print 'Access granted'
else:
print 'Access denied'
c) Lists: The Python list object is the most general sequence provided by the language. Lists
are positionally ordered collections of arbitrarily typed objects, and they have no
fixed size. They are also mutable—unlike strings, lists can be modified in-place by
assignment to offsets as well as a variety of list method calls.
Strings: strings are immutable in Python—they cannot be changed
in-place after they are created. For example, you can’t change a string by assigning to one of its
positions, but you can always build a new one and assign it to the same
name. Strings are qualitatively different from the other four because they are made up of smaller
pieces — characters.
5. a)
16
def is divisible_by_3(n):
if (n%3==0):
print("This number is not divisible by 3")
else:
print("This number is not divisible by 3")
def is_divisible_by_5(m):
if (m%5==0):
print("This number is divisible by 5")
else:
print("This number is not divisible by 5")
b)
i.
if BOOLEAN EXPRESSION:
STATEMENTS
e.g. if x > 0:
print (“x is positive”)
ii.
A second form of the if statement is alternative execution, in which there are two possibilities and the
condition determines which one gets executed. The syntax looks like this:
if x % 2 == 0:
print (“x is even”)
else:
print (“x is odd”)
iii
Sometimes there are more than two possibilities and we need more than two branches. One way to express a
computation like that is a chained conditional:
if x < y:
print x, "is less than", y
elif x > y:
print x, "is greater than", y
else:
print x, "and", y, "are equal“
iv.
17
While Statement
def sequence(n):
while n != 1:
print n,
if n % 2 == 0: # n is even
n = n / 2
else: # n is odd
n = n * 3 + 1
c)
i. ['a', 'd', 'e', 'f'] ii. ['pear', 'apple', 'orange']
iii. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] iv. [1, 3, 5, 7, 9]
6. a)
d) i. C-like languages require semicolons at the end of each statement, and braces around a nested
block of code.
ii. The statements in a nested block are all indented the same number of tabs or spaces.
c)
The following function copies a file, reading and writing up to fifty characters at a time. The first argument
is the name of the original file; the second is the name of the new file:
18
This functions continues looping, reading characters from infile and writing the same charaters to outfile
until the end of infile is reached, at which point text is empty and the break statement is
executed.
d)
19
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: 2015/2016 SEMESTER: ALPHA
COURSE CODE: CSC 214 CREDIT UNIT: 3
COURSE TITLE: HIGH PERFORMANCE AND DATABASE MANAGEMENT SYSTEM
INSTRUCTION: ANSWER QUESTION ONE AND ANY OTHER THREE QUESTIONS
TIME: 3HOURS
1(a) State in maximum of 10 short sentences the step by step process of connecting SQL Server Database Management System to Visual Studio programming languages environment. (5marks)
1(b) Show the Functional dependency diagram for Table 1: Patient _Appointment Table in question (3) (5marks)
1(c) Explain five limitation of file-Based Approach (5marks)
1(d) Convert the following ER diagram into a set of tables. (10marks)
2(a) What is the relationship between Candidate key and Foreign keys (5marks)
Project Organisation Employee
StatusRepor
LocalGovt College SmallBusiness
d
WorksFor
ReportFor
Executes N
1 1 N
1
N
ProjectID
Title
Cost
Purpose
StartDate EndDate
State
Name
OrgID
City
Address
State
Name
SSN
City
Address
Payment DOB
CorpStatus
NoOfFaculty NoOfStudent Population
OrgLevel
MoneySpent Comment
DateofIn
c
ReportDate
20
2 (b) Use the following business rules to create the ERD for a small consulting company named
ConsultCo. Show all entities, relationships, optionalities, connectivities and cardinalities.
A client can contract many projects, but each project is contracted by one client. Some clients in the company
client list have not (yet) contracted any project(s). A project may have many (consulting company)
employees assigned to it, and each employee may be assigned to many projects. Some employees are not
assigned to any project. One employee leads each project. An employee may lead more than one project at
a time. One employee coordinates each project. An employee may coordinate more than one project at a
time. Some employees never lead or coordinate projects. Many of the consulting company employees have
multiple job skills that are applicable to the consulting work. Each job description- system analyst, database
designer, accountant and so on- can fit many employees. Some job descriptions are not yet filled. Some
employees do not have a specific job classification. 10marks)
3 . Given the Patient _Appointment Table below
(i) Determine the candidate keys for the table (3marks)
(ii) Normalizing the table below to Boyce-Codd Normal form and Show the final decomposed relations with the data. (12marks)
Functional dependency
PNo, ADate, → StaffNo , ATime, DentistName, SurgeonNo (pk)
PNo → PName (pd)
StaffNo → DentistName Td
StaffNo , ADate → SurgeonNo
Date, ATime, SurgeonNo → PNo , PName, StaffNo, DentistName (ck)
StaffNo, ADate, ATime → PNo , PName (ck)
4. (a) Discuss each of the following concepts in the context of the relational data model
(i) attribute and turple
(ii) domain
(iii) degree and cardinality. (5marks) (b) Hotel (hotelNo, hotelName, City)
Room (roomNo, hotelNo, type, price) Booking (hotelNo, guestNo, dateFrom, dateTo, roomNo) Guest (questNo, guestName,questAddress)
Using the schema above to answer the following questions:
Table 1: Patient _Appointment Table
StaffNo DentistName PNo PName Appointment Date Time
SurgeonNo
S011 Tony Smith P100 James White 12-Sep-08 10.00 S15
P105 Jill Bell 12-Sep-08 12.00 S15
S024 Hellen Chris P108 Tom Fred 12-Sep-08 10.00 S10
P108 Tom Fred 14-Sep-98 14.00 S10
S032 Rose Kelvin P105 Jill Bell 14-Sep-98 16.00 S15
P110 John Stone 15-Sep-08 18.00 S13
21
(i) Identify the foreign keys in this schema (2marks)
(ii) Explain how the entity integrity and referential integrity rules apply to these relations (4marks)
(iii) Produce some sample tables for these relations that observe the relational integrity. (4marks)
5. (a) Define the 3 basic relational algebra operation (4marks) (a) Using the schema in 4(c), generate the relational Algebra for the following queries:
(i) List all hotels (ii) List all single rooms with a price below N2000 per night (iii) List the names and Address of all quests (3maks)
(b) Using the schema in 4(c), generates SQL statement for the following queries: (8marks)
(i) How many hotels are there?
(ii) List full details of all hotels in London
(iii) List number of rooms in each hotel
(iv) List the names and address of all quests living in London, alphabetically ordered by name.
use pattern matching operator.
6(a) What is data mining? (3marks)
(b) With diagram representation show data mining as the core component of knowledge discovery process. (3marks)
(c) What is concurrency control (3marks)
(d) Explain some of the potential problems caused by concurrency (4.5marks)
(e) What is dead lock? (1.5marks)
22
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 214 CREDIT UNIT: 3
COURSE TITLE: HIGH PERFORMANCE AND DATABASE MANAGEMENT
SYSTEM
INSTRUCTION: Marking scheme
1(a)
1. Install SqL Server and Visual Studio
2. Create a database under sql Server and Save it with a unique name
3. Open to Visual Studio environment
4. Under tool Menu, click Connect to database, this will prompt you to Add Connection form where
5. Identify your DBM under data source as Microsoft SQL Server
6. supply the server name by Type the server name inside the server name text box
7. Select or enter the database name created under SQL Server
8. Click text connection
9. If connection is successful, then click OK.
1(b)
PNo ADate ATime StaffNo PName DentistName SurgeonNo
(Pri. Key) (partial dependency) (transitive dependency) (ck) (ck) Figure: Dependency Diagram for the Patient_Appointment Relation
1(c) Separation and isolation of data
Each program maintains its own set of data and users of one program may be unaware of potentially useful data held by other programs.
Duplication of data
23
The same data is held by different programs. Wasted space and potentially different values and/or different formats for the same item.
Data dependence
File structure is defined in the program code.
Incompatible file formats
Programs are written in different languages, and so cannot easily access each other’s files.
Fixed Queries/Proliferation of application programs
Programs are written to satisfy particular functions and any new requirement needs a new program.
1(e)
Project (ProjectID, Title, Purpose, Cost, StartDate, EndDate, OrgID) Organisation ( OrgID, Name, Address, City, State, ZipCode) StatusReport( ProjectID, ReportDate, MoneySpent, Comment) Employee(SSN, Name, DOB, Payment, Address, City, State, ZipCode) LocalGovt(OrgID, Population, OrgLevel) College(OrgID, NoOfFaculty, NumberStudent) SmallBusiness(OrgID, CorpStatus, DataOfInc) WorksFor(SSN, OrgID)
2(a) Candidate Key:a subset of superkey (K) such that no proper subset is a superkey within the relation.
– Uniqueness (In each tuple of R, values of K uniquely identify that tuple) – Irreducibility no proper subset of K has the uniqueness property
Foreign Key Attribute, or set of attributes, within one relation that matches candidate key of some (possibly same) relation. Relationship: Foreign keys are candidate keys. 2(b)
24
3. (i) Candidate keys: (3marks)
PNo, ADate (Primary key)
ADate, Atime, SurgeonNo
StaffNo, ADate, Atime
(ii) 11marks
Functional dependency:
PNo, ADate, → StaffNo ,ATime, DentistName, SurgeonNo
PNo → PName
StaffNo → DentistName
StaffNo, ADate → SurgeonNo
ADate, ATime, SurgeonNo → PNo, PName, StaffNo, DentistName
StaffNo, ADate, ATime → PNo, PName
Solution Functional dependencies of the Patient_Appointment relation with PNo, ADate as the primary key
fd1: PNo, ADate, → StaffNo ,ATime, DentistName, SurgeonNo (pk)
Client Project Contr
Lea
Employee
Coo
Ass
Job Has
N 1
0, 1,
0,
N
N 0,
0, 1
N
0, N
1, N
0,
1,
1
N N
0,
d
System Analyst
Database
Accountant
....
d
System
Database
Accountant
....
Patient _Appointment Table
StaffNo DentistName PNo PName ADate ATime SurgeonNo
S011 Tony Smith P100 James White 12-Sep-08 10.00 S15
S011 Tony Smith P105 Jill Bell 12-Sep-08 12.00 S15
S024 Hellen Chris P108 Tom Fred 12-Sep-08 10.00 S10
S024 Hellen Chris P108 Tom Fred 14-Sep-98 14.00 S10
S032 Rose Kelvin P105 Jill Bell 14-Sep-98 16.00 S15
S032 Rose Kelvin P110 John Stone 15-Sep-08 18.00 S13
25
fd2: PNo → PName (pd)
fd3: StaffNo → DentistName (td)
fd4: StaffNo, ADate → SurgeonNo (not – candidate key)
fd5: ADate, ATime, SurgeonNo → PNo, PName, StaffNo, DentistName(ck)
fd6: StaffNo, ADate, ATime → PNo, PName (ck)
1NF to 2NF To decompose the Patient_Appointment relation to 2nd Normal form all the partial dependencies have to be removed on separate tables. So as to have all non-key attribute to be fully dependent on their determinant key. Appointment (StaffNo, DentistName, PNo, ADate, ATime, SurgeonNo) Patient (PNo, PName)
StaffNo DentistName PNo ADate ATime SurgeonNo
S011 Tony Smith P100 12-Sep-08 10.00 S15
S011 Tony Smith P105 12-Sep-08 12.00 S15
S024 Hellen Chris P108 12-Sep-08 10.00 S10
S024 Hellen Chris P108 14-Sep-98 14.00 S10
S032 Rose Kelvin P105 14-Sep-98 16.00 S15
S032 Rose Kelvin P110 15-Sep-08 18.00 S13
2NF to 3NF In other to transform the decomposed relation to 3rd Normal form, we have to identify transitive dependency, if it exists in any of the decomposed relations.
fd3: StaffNoDentistName (Td) So, to decompose Appointment relation to 3rd Normal form the transitive dependency attribute has to be removed as a separate relation with a copy of StaffNoas the Primary Key, to have Appointment (StaffNo, PNo, ADate, ATime, SurgeonNo) Patient (PNo, PName) Staff (StaffNo, DentistName)
StaffNo PNo ADate ATime SurgeonNo
S011 P100 12-Sep-08 10.00 S15
S011 P105 12-Sep-08 12.00 S15
S024 P108 12-Sep-08 10.00 S10
S024 P108 14-Sep-98 14.00 S10
S032 P105 14-Sep-98 16.00 S15
S032 P110 15-Sep-08 18.00 S13
PNo PName
P100 James White
P105 Jill Bell
P108 Tom Fred
P108 Tom Fred
P105 Jill Bell
P110 John Stone
StaffNo DentistName
S011 Tony Smith
S011 Tony Smith
S024 Hellen Chris
S024 Hellen Chris
S032 Rose Kelvin
S032 Rose Kelvin
PNo PName
P100 James White
P105 Jill Bell
P108 Tom Fred
P108 Tom Fred
P105 Jill Bell
P110 John Stone
26
3NF to BCNF
In other to transform the decomposed relation to BoyceCodd Normal form, we have to identify if there is any case where a determinant is not a candidate key. So we have
fd4: StaffNo, ADate → SurgeonNo (not – candidate key)
To resolve this, a new relation has to be created for fd4 from fd1, so we have Appointment (StaffNo, PNo, ADate, ATime,)
Staff_Surgeon (StaffNo, ADate, SurgeonNo) Patient (PNo, PName) Staff_Dentist (StaffNo, DentistName) Appointment Relation Staff_Surgeon Relation
StaffNo PNo ADate ATime
S011 P100 12-Sep-08 10.00
S011 P105 12-Sep-08 12.00
S024 P108 12-Sep-08 10.00
S024 P108 14-Sep-98 14.00
S032 P105 14-Sep-98 16.00
S032 P110 15-Sep-08 18.00
Patient Relation Staff_Dentist Relation
4(a)
• Attribute is a named column of a relation. – It corresponds to a characteristic of an entity. – They are also called fields
• Tuple is a row of a relation. • Domain is the set of allowable values for one or more attributes. • Degree is the number of attributes in a relation. • Cardinality is the number of tuples in a relation.
(c) (i) From Room (hotelNo) From Booking (hotelNo, guestNo,roomNo) (ii) Entity Integrity
• In a base relation, no attribute of a primary key can be null. Ensures that all entities are unique.
StaffNo ADate SurgeonNo
S011 12-Sep-08 S15
S011 12-Sep-08 S15
S024 12-Sep-08 S10
S024 14-Sep-98 S10
S032 14-Sep-98 S15
S032 15-Sep-08 S13
PNo PName
P100 James White
P105 Jill Bell
P108 Tom Fred
P108 Tom Fred
P105 Jill Bell
P110 John Stone
StaffNo DentistName
S011 Tony Smith
S011 Tony Smith
S024 Hellen Chris
S024 Hellen Chris
S032 Rose Kelvin
S032 Rose Kelvin
27
Referential Integrity • If foreign key exists in a relation, either foreign key value must match a candidate key value of
some tuple in its home relation or foreign key value must be wholly null.Entity Integrity
(iii)
5.(a) (1) Selection (or Restriction)
predicate (R) • Selection operation : selects tuples that satisfy a given predicate.
(2) Projection Operation
col1, . . . , coln(R) • Projection operation copies its argument relation for the specified attributes only.
(3) Union
R S • Union of two relations R and S defines a relation that contains all the tuples of R, or S, or both R and S,
duplicate tuples being eliminated. • R and S must be union-compatible.
(4) Set Difference R – S
• Defines a relation consisting of the tuples that are in relation R, but not in S. R and S must be union-compatible.
(5) Cartesian product
• The Cartesian product of two relations is denoted by a cross (), written as
R1 R2
(b) (i) hotelNo, hotelName, City (Hotel)
(ii) hotelNo (type = ‘single’AND price > 2000 (Room))
(iii) guestName, Address (Guest) (c)
(i) Select count(*) AS Count From Hotel (ii) Select hotelNo, hotelName, City From Hotel Where city = ‘London’ (iv) Select count (Distinct HotelNo) AS Count From Room (v) Select guestName, Address From Guest Where Address LIKE ‘ %London%’ Oder By guestName
6(a) Data Mining, also popularly known as Knowledge Discovery in Databases (KDD), refers to the nontrivial extraction of implicit, previously unknown and potentially useful information from data in databases.
Hotel hotelNo hotelName city
Ho1 Gateway Sango
Ho2 Presidential Osogbo
Ho3 Eko Lagos
Ho4 Premier Lagos
Ho5 Mayor Ibadan
Ho6 Nicon Abuja
Room roomNo hotelNo type price
Roo5 Ho3 Single 1000
R006 Ho3 Double 2000
Roo5 Ho4 Single 1500
R007 Ho3 Exec. 2500
R005 Ho2 Double 2500
Guest
guestNo guestName guestAddress
G001 Fred Jan 22, Oshodi
G005 Ajayi Ila 30,Ikorodu
G006 Wisdom Ayo 14,brown Abuja
Booking hotelNo guestNo dateFrom dateTo roomNo
H03 G001 02-Apr-98 02-May-98 Roo5
H04 G005 01-Oct-02 05-Oct-02 R005
H03 G001 05-Jun-02 05-Jul-02 R007
H06 G006 04-Jul-04 04-Jul-04 R003
28
(c) This is the process of managing simultaneous operations on the database without having them interfere
with one another.
(d) The lost update problem
Successfully complete update operation overridden by another user.
Uncommitted dependency problem
When one transaction is allowed to see the intermediate results of another transaction before
committed
Inconsistent analysis problem
When a transaction reads several values from the database but a second transaction updates some
of them during the execution of the first.
(e) Deadlock: An impasse that may result when two (or more0 transactions are each waiting for locks to be
released that are held by the other.
(b)
29
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: CSC216
CREDIT UNIT: 2 COURSE TITLE: Foundations of Parallel and sequential Programming
INSTRUCTION: Attempt Question One and any Other Two Questions
TIME: 2 HOURS
Question One [Compulsory]
1. a) i. Write the pseudo code to implement an interactive program that prompts the user for his or
her year of birth, month of birth, the current year, and the current month and then computes and prints
the user’s age in years and in months. The month values are integers in the range 1 through 12.
5Marks
ii. Write a pseudo code that uses a while statement to compute the sum of all integers between first
and second, where first and second are integers and first<=second.
5Marks
b) Given the following instruction set for a simple machine; Write the following in machine
language, assembly language and c language (high level language).
Adds the contents of memory location 12, initialized to 350 and memory location 14, initialized to
96, and store the result in location 16 , initialized to 0.
Machine language
Assembly language
30
9 Marks c) Explain the following;
i. Machine language
ii. High level language 4 Marks
d) Define the following
i. Sequential programming
ii. Parallel programming
iii. Instruction set
iv. Assembly language
v. CISC
vi. RISC
vii. Task 7 Marks
Question Two
a) Explain the following terms as relates to parallel terminology
i. Pipelining
ii. Shared Memory
iii. Distributed Memory
iv. Communication
v. Synchronization 71/2Marks
b) With the aid of a well labeled diagram, explain the typical memory hierarchy of a computer system.
6Marks
c) Can the following problem be solved by parallel programming? Give reasons for your answer.
i. Calculate the potential energy for each of several thousand independent conformations of a molecule.
When done, find the minimum energy conformation.
ii. Calculation of the Fibonacci series (0,1,1,2,3,5,8,13,21,...) by use of the formula:
F(n) = F(n-1) + F(n-2) 2Marks
d) Explain 2 important steps to designing a parallel program. 2Marks
Question Three
a) Differentiate between Multiprogramming and Multiprocessing. 3 Marks
b) Explain Granularity in parallel computing. 4 Marks
c) With the aid of mathematical formulas define Speed-up S(n), Throughput U(n), and Efficiency
E(n). 6 Marks
d) Using the chart below, if I represents the instruction, calculate the Speed-up S(n), Throughput U(n),
and Efficiency E(n). of the pipelining process. 7Marks
31
Question four
a) Explain 2 characteristics of parallelism. 4 Marks
b) Draw a flow chat and write the pseudo code to determine how much a worker earns if the rate of
payment is as flows:
Normal rate (12hours & below) - N50 per hour
Overtime (Above 12hours) - N90 for every extra hour. 8Marks
c) Using a pseudo code, explain the how to parallelize the following sequential prefix sum algorithm.
8 Marks PREFIX_SUM(x,n)
1. y0=x0
2. for i=1 to n-1 do
3. yi=yi-1+xi
4. end for
5. return y
Question five
a) Explain four(4) reason for the use of parallel programming. 8 Marks
b) Explain how to parallelize the summation of a sequence of n data values:
x0, x1, x2, …, xn-1 6 Marks
c) With the aid of a well labelled diagram, explain the Von Neuman architecture.
6 Marks
MARKING SCHEME
1. a) i)
1. Begin
2. Prompt user to input year of birth, current year, month of birth and current month in digits (1-
12)
3. User's age in years= current-year-year of birth
4. User's age in month= (current month (in numbers)- month of birth) + (users age in year*12)
5.Print user's age in years & users age in months
6. End
ii)
1. Begin
2. Prompt user to input two numbers(first and second)
3. Read first number as num1, second number as num2
4. Initialize sum to zeero
5. Increment num1 by 1
32
6 while (num1< num2)
{
sum = sum = num1
print sum
Increment num 1 by 1
7 Print final sum
8 End
b)
Machine Language
Assembly Language
C Language
33
#include<stdio.h>
void main( )
{
int k=360;
int c=96;
int addition;
addition= c+k;
printf("%i",addition);
}
c)
A machine language program for a given architecture is a collection of machine instructions represented in
binary form. Programs written at any level higher than the machine language must be translated to the binary
representation before a computer can execute them.
High level languages
They are programming languages that enables a programmer to write programs that are more or less
independent of a particular type of computer. Such languages are considered high-level because they are closer
to human languages and further from machine languages. A high level language hides the micro abstractions
such as set of command required to be performed by the processors such as CPU.
d) i. Sequential programming is the programming paradigm such that the process is deterministic, only one
possible execution sequence and one possible final result (if any)
ii. Parallel programming is one consisting of two or more processes, threads of execution or control
happening at the same time.
iii. Instruction set Also called a command set, the basic set of commands, or instructions, that a microprocessor
understands. One of the principal characteristics that separates RISC from CISC microprocessors is the size of the
instruction set -- RISC microprocessors have relatively small instruction sets whereas CISC processors have relatively
large instruction sets
iv. Assembly language Assembly language is the symbolic form of machine language. Assembly programs
are written with short abbreviations called mnemonics. A mnemonic is an abbreviation that represents the
actual machine instruction.
v. CISC: that by doing more in a single instruction, one can use a smaller number of instructions to perform
the same job. Fewer memory read/write operations, Speedup of operations. Increasing the complexity of
instructions and the number of addressing modes
Advantage of reducing the “semantic gap” between the instructions in a high-level language and those in the
low-level (machine) language.
vi. RISC: promotes the optimization of architectures by speeding up those operations that are most
frequently used while reducing the instruction complexities and the number of addressing modes. Reduced
34
instructions set computers (RISCs). Examples Sun SPARCTM and MIPSTM machines. RISC architectures
are faster execution of programs.
The majority of contemporary microprocessor chips seems to follow the RISC paradigm.
vii. Task: A logically discrete section of computational work. A task is typically a program or program-like
set of instructions that is executed by a processor.
2a)
i. Pipelining: Breaking a task into steps performed by different processor units, with
inputs streaming through, much like an assembly line; a type of parallel computing. Task is divided into a number of subtasks
The subtasks are performed in sequence.
Each subtask is performed by a given functional unit.
The units are connected in a serial fashion and all of them operate simultaneously.
pipelining improves the performance
ii. Shared Memory: From a strictly hardware point of view, describes a computer
architecture where all processors have direct (usually bus based) access to common
physical memory. In a programming sense, it describes a model where parallel tasks all
have the same "picture" of memory and can directly address and access the same logical
memory locations regardless of where the physical memory actually exists.
iii. Distributed Memory: In hardware, refers to network based memory access for
physical memory that is not common
iv. Communication: Parallel tasks typically need to exchange data.
v. Synchronization: The coordination of parallel tasks in real time, very often associated
with communications.
b)
35
Without a memory no information can be stored or retrieved in a computer. A computer memory is organized
in a hierarchy. This arrangement is such that, larger and slower memories are used to supplement smaller and
faster ones. Hierarchy starts with a small, expensive, and relatively fast unit, called the cache.
The cache is followed in the hierarchy by a larger, less expensive, and relatively slow main memory unit.
Cache and main memory are built using solid-state semiconductor material. They are followed in the hierarchy
by far larger, less expensive, and much slower magnetic memories that consist typically of the (hard) disk and
the tape.
c)i. This problem is able to be solved in parallel. Each of the molecular conformations is independently
determinable. The calculation of the minimum energy conformation is also a parallelizable problem
ii. This is a non-parallelizable problem because the calculation of the Fibonacci sequence as shown would
entail dependent calculations rather than independent ones. The calculation of the F(n) value uses those of
both F(n-1) and F(n-2). These three terms cannot be calculated independently and therefore, not in parallel.
d)
Identify the program's hotspots:
◦ Know where most of the real work is being done. The majority of scientific and technical
programs usually accomplish most of their work in a few places.
◦ Focus on parallelizing the hotspots and ignore those sections of the program that account for
little CPU usage.
Identify bottlenecks in the program
◦ Are there areas that are disproportionately slow, or cause parallelizable work to halt or be
deferred? For example, I/O is usually something that slows a program down.
◦ May be possible to restructure the program or use a different algorithm to reduce or eliminate
unnecessary slow areas
Identify inhibitors to parallelism. One common class of inhibitor is data dependence, as
demonstrated by the Fibonacci sequence above.
Investigate other algorithms if possible. This may be the single most important consideration when
designing a parallel application.
3a)
– multiprogramming: the execution of concurrent processes by timesharing them on a single
processor (concurrency is simulated);
– multiprocessing: the execution of concurrent processes by running them on separate
processors which all access a shared memory (true parallelism as in distributed processing).
b) Granularity In parallel computing, granularity is a qualitative measure of the ratio of computation to
communication.
– Coarse: relatively large amounts of computational work are done between communication
events
36
– Fine: relatively small amounts of computational work are done between communication
events
This is one of the simplest and most widely used indicators for a parallel program's performance.
c)
d)
Speed-up =3.07
Throughput = 0.31
Efficiency = 0.31
4 a)
Explicitly parallel algorithms are fundamentally different from sequential algorithms, because they
embody multiple points of execution.
• Programs with concurrent interactions are harder to reason about and harder to debug.
• It’s harder to achieve good performance with a parallel program.
• Small inefficiencies can lead to large performance problems.
• It’s harder to ignore low-level details.
The performance model is different and more complex.
• Counting instructions is insufficient.
• Focusing on communication is insufficient.
• The performance problem is instead an inseparable problem with multiple dimensions.
• The joint goals of portability and performance are harder to achieve.
37
• Tools and languages are immature.
b)
START
Read HRS, RATEN, RATEO
If HRS < = 12 Then
PAY=HRS * RATEN
Else
PAY=((HRS-12)*RATEO))+(HRS * RATEN)
WRITE PAY
STOP
c)
A prefix sum can be calculated in parallel by the following steps
1. Compute the sums of consecutive pairs of items in which the first item of the pair has an even index:
z0 = x0 + x1, z1 = x2 + x3, etc.
2. Recursively compute the prefix sum w0, w1, w2, ... of the sequence z0, z1, z2, ...
3. Expand each term of the sequence w0, w1, w2, ... into two terms of the overall prefix sum: y0 = x0, y1
= w0, y2 = w0 + x2, y3 = w1, etc. After the first value, each successive number yi is either copied from
38
a position half as far through the w sequence, or is the previous value added to one value in the x
sequence
5a)
1. Save time and/or money: In theory, throwing more resources at a task will shorten its time to completion,
with potential cost savings. Parallel computers can be built from cheap, commodity components.
2. Solve larger problems: Many problems are so large and/or complex that it is impractical or impossible to
solve them on a single computer, especially given limited computer memory.
3. Provide concurrency: A single compute resource can only do one thing at a time. Multiple computing
resources can be doing many things simultaneously.
For example, the Access Grid (www.accessgrid.org) provides a global collaboration network where people
from around the world can meet and conduct work "virtually".
4. Use of non local resources: Using compute resources on a wide area network, or even the Internet when
local compute resources are scarce.
5. Limitts to serial computing: Both physical and practical reasons pose significant constraints to simply
building ever faster serial computers:
a)Transmission speeds - the speed of a serial computer is directly dependent upon how fast data can move
through hardware. Absolute limits are the speed of light (30 cm/nanosecond) and the transmission limit of
copper wire (9 cm/nanosecond). Increasing speeds necessitate increasing proximity of processing elements.
etc
b)
Another, more parallel, order of summation is to add even/odd pairs of data values yielding intermediate sums,
x0 + x1, x2 + x3, x4 + x5, x6 + x7, …
which are added in pairs,
(x0 + x1) + (x2 + x3), (x4 + x5) + (x6 + x7), …
yeilding more intermediate sums, etc. This solution can be visualized as inducing a tree on the computation,
where the original data values are leaves, the intermediate nodes are the sum of the leaves below them, and
the root is the overall sum;
Summing in pairs. The order of combining a sequence of numbers (6, 4, 16, 10, 12, 14, 2, 8) by (recursively) combining pairs of
values, then pairs of results, etc
39
The advantage of summing by pairs is that the approach uses separate and independent subcomputations,
which can be performed in parallel.
c)
von Neumann Architecture
◦ Named after the Hungarian mathematician John von Neumann who first authored the general
requirements for an electronic computer in his 1945 papers.
◦ Since then, virtually all computers have followed this basic design, differing from earlier
computers which were programmed through "hard wiring".
Comprised of four main components:
◦ Memory
◦ Control Unit
◦ Arithmetic Logic Unit
◦ Input/Output
Read/write, random access memory is used to store both program instructions and data
◦ Program instructions are coded data which tell the computer to do something
◦ Data is simply information to be used by the program
Control unit fetches instructions/data from memory, decodes the instructions and then sequentially
coordinates operations to accomplish the programmed task.
Aritmetic Unit performs basic arithmetic operations
Input/Output is the interface to the human operator