Ics104 Final v1 211

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

Information and Computer Science Department

ICS 104: Introduction to Programming in Python and C


Final Exam, Term 211
Code 001 Thursday, December 30, 2021 Code 001
Duration: 120 minutes

Name: ID:
Instructor and Section: Select one
Instructor Section
Mr. Mustafa AlTurki [ ] 01 (UT 9 – 9:50) [ ] 10 (UT 11 – 11:50)
Dr. Husni Al-Muhtaseb [ ] 02 (UT 10 – 10:50) [ ] 09 (UT 9 – 9:50)
Dr. Mohammed Amro [ ] 03 (MW 10 – 10:50) [ ] 04 (MW 11 – 11:50)
Dr. Samer Arafat [ ] 5 (UT 13 – 13:50) [ ] 6 (UT 14 – 14:50)
Dr. Mohamed Balah [ ] 7 (MW 8 – 8:50) [ ] 8 (MW 9 – 9:50)

Instructions:
1. Answer all questions. Make sure your answers are clear and readable.
2. The exam is closed book and closed notes. No calculators or any helping aides are allowed. Make
sure to turn off your mobile phone and keep it in your pocket.
3. If there is no space on the front of the page, use the back of the page. Indicate this clearly.

Question Maximum Points Earned Points Remarks


MCQ 60
Output 20
Program 20
Total 100
Page 2 of 20

Part 1 : MCQ questions [ 40 x 1.5 = 60 points ]: (Make sure to bubble the correct
answer in the green sheet)

1) Which one of the following code segments will result in an error?

a) a = [1,2,3]
a[1]=5
a = [1,2,3]
b)
print(a[0])
a = (1,2,3)
c)
a[1]=5
a = {"k1":3,"k2":4}
d)
a["k3"]=5
e) None of the above

For questions 2-3 consider the following class:


class Ticket:
def __init__(self, movie, seat, time):
self._movie = movie
self._seat = seat
self._time = time
def change_time(self, newTime):
self._time = newTime
def change_seat(self, newSeat):
self._seat = newSeat
def printTicket(self):
print(self._movie, self._seat, self._time)

2) What will be the output of the following code fragment?

ticket1 = Ticket("Apple Documentary", "2B", "5:00pm")


ticket2 = Ticket("Google Documentary", "4C", "5:00pm")
ticket1.change_time("7:30pm")
ticket2.change_seat("5A")
ticket1.printTicket()
ticket2.printTicket()

a) Apple Documentary 2B 7:30pm


Google Documentary 5A 5:00pm
Apple Documentary 2B 5:00pm
b) Google Documentary 4C 5:00pm
Apple Documentary 4C 7:30pm
c) Google Documentary 4C 7:30pm
Apple Documentary 2B 5:00pm
d) Google Documentary 2B 5:00pm
Apple Documentary 2B 5:00pm
e) Google Documentary 5A 5:00pm
Page 3 of 20

3) Which of the following methods is known as constructor?

a) change_time
b) change_seat
c) __init__
d) printTicket
e) None of the above

4) Which of the following code segments add a new key, value pair to a dictionary named d?
a) d{"c":7}
b) d.add("c", 7)
c) d.append("c", 7)
d) d{"c"}=7
e) d["c"]=7

5) What will be the output of the following code fragment?

def modify(myList):
for i in range(len(myList)):
myList[i] = myList[i] + 1
a = [1,2,3]
modify(a)
print(a)
a) [2, 3, 4]
b) [1, 2, 3]
c) [2, 4, 6]
d) [1, 1, 1]
e) [1, 2, 3, 1]

6) What will be the output of the following code fragment?

a = [1, 2, 3, 10, 5, 8, 9]
i = len(a)//2
while i >=0:
if a[i] % 2 == 1:
print(a[i], end=" ")
i = i - 1

a) 1 3 5 9
b) 9 5 3 1
c) 3 1
d) 1 3
e) 5 3 1
Page 4 of 20

7) Assume the variable names is a list of strings, which of the following is the correct way to
transform the strings in that list to upper case?

a) for n in names:
n = n.upper()
for n in names:
b) n.upper()
for i in range(len(names)):
c) i = i.upper()
for i in range(len(names)):
d) names[i].upper()
for i in range(len(names)):
e) names[i] = names[i].upper()

8) Which of the following is the correct way to handle the exception raised by opening a file for
reading that does not exist?

f = open("hello.txt", "r")
a) if f == IOError:
print("Error")
f = open("hello.txt", "r")
b) except IOError:
print("Error")
try:
f = open("hello.txt", "r")
c) except IOError:
print("Error")
try open("hello.txt", "r")
d) except IOError
except IOError:
print("Error")
e) try:
f = open("hello.txt", "r")

9) In Python, what will happen if you open a file for writing that does not exist?

a) The program will not be executed.


b) The file will be created when you run the code.
c) An exception will be raised.
d) The program will open the file for reading instead.
e) None of the above

10) Assume no exception is raised when you run the following Python code fragment, what is its
output?

try:
f = open("output.txt", "w")
except IOError:
print("Something went wrong")
finally:
Page 5 of 20

print("cleaning up")

a) Something went wrong


Cleaning up
b) cleaning up
c) Something went wrong
d) NO OUTPUT
e) None of the above

11) What will be the output of the following code fragment?

def fun(list1, list2):


list3 = []
for i in range(len(list1)):
list3.append(list1[i] + list2[i])
return list3
a = fun([1,2,3], [4,5,6])
print(a)
a) [1, 2, 3, 4, 5, 6]
b) 21
c) [1, 2, 3]
d) [5, 7, 9]
e) [4, 5, 6]

12) Which of the following statement is true in Python?

a) Multiple objects can be created from one class.


A dictionary can have two items with the same key but
b) different values.
c) Each function must have a return statement.
The code under “finally” clause will be executed only when
d) an exception is raised in the code of the try clause.

e) All the above are true statement.

13) What will be the output of the following code fragment?


d = {"ICS104": 3, "COE202":4, "ICS108": 3, "ICS202": 3}
for k in d:
if "ICS" in k:
d[k] = d[k] + 1
print(d)
a) {'ICS104': 4, 'COE202': 5, 'ICS108': 4, 'ICS202': 4}
b) {'ICS104': 4, 'COE202': 4, 'ICS108': 4, 'ICS202': 4}
c) {'ICS104': 3, 'COE202': 5, 'ICS108': 3, 'ICS202': 3}
d) {'ICS104': 1, 'COE202': 1, 'ICS108': 1, 'ICS202': 1}
Page 6 of 20

e) {'ICS104': 4, 'ICS108': 4, 'ICS202': 4}


14) What will be the output of the following code fragment?

myList = ['a', 'b', 'c', 'd']


myList.pop()
el = myList.pop(1)
myList.append(el)
print(myList)
a) ['a', 'b', 'c', 'd']
b) ['a', 'c', 'el']
c) ['b', 'c']
d) ['a', 'c', 'b']
e) This code will generate an error

15) What will be the output of the following code fragment?

def f1():
a = 5
def main():
a = 4
print(a, end=" ")
f1()
print(a)
main()

a) 4 5
b) 4 4
c) 5 5
d) 5 4
e) None of the answers is correct

16) What will be the output of the following code fragment?

d = {"A": 1, "B": 2}
d["C"] = d["C"] + 1
print(d)

a) {"A": 1, "B": 2}
b) {"A": 1, "B": 2, "C": 1}
c) {"C": 1}
d) {"A": 2, "B": 3, "C": 1}
e) This code will generate an error
Page 7 of 20

17) Consider the following code fragment:

x = [2, 3, 5, 7]
y = x
z = list(y)
Given the following statements:
1. x and y are references to the same list.
2. z and y are references to two independent lists.
3. z and x are references to two independent lists.
4. A total of two lists are created by the above program.
Choose the most suitable answer:
a) Only statement 1 is True.
b) Only statement 2 is True.
c) Only statement 3 is True.
d) Only statement 4 is True.
e) All four statements are true.

18) What will be the output of the following code fragment?

s = [1, 1, 1]
for i in range(3):
s[3] = s[i] * 2
print(s)

a) [1, 1, 1]
b) [2, 2, 2]
c) [1, 2, 1]
d) [1, 1, 1, 1, 1, 1]
e) This code will generate an error

19) What will be the output of the following code fragment?

a = [2, 2, 2]
b = [1, 1, 1]
c = a+b
print(c)

a) This code will generate an error


b) [3, 3, 3]
c) [1, 1, 1, 2, 2, 2]
d) [3, 3, 3, 3, 3, 3]
e) [2, 2, 2, 1, 1, 1]
Page 8 of 20

20) What will be the output of the following code fragment?

grades = {"Ahmed": 3, "Ali": 6, "Khalid": 7, "Rami": 1}


for student in grades:
if grades[student] > 5:

print(student, end=" ")

a) Ali Khalid
b) Ahmed Ali Khalid Rami
c) {"Ali": 6, "Khalid": 7}
d) 6 7
e) {"Ahmed": 3, "Ali": 6, "Khalid": 7, "Rami": 1}

21) What will be the output of the following code fragment if the file f.txt does not exist?
try:
print("Start", end =" ")
f = open("f.txt", "r")
print("Opened", end =" ")
except IOError:
print("Error")
a) Opened Error
b) Start Opened Error
c) Error
d) Start
e) Start Error
22) What will be the output of the following code fragment?

class Member:
def __init__(self, name, points=0):
self._name = name
self._points = points

def addPoints(self, newPoints):


self._points = self._points + newPoints

def display(self):
print(self._name, self._points)
m1 = Member("Ali")
m2 = Member("Ahmed", 34)
m1.addPoints(4)
m2.addPoints(2)
m1.display()
m2.display()

a) Ali 4
Page 9 of 20

Ahmed 2
Ali 4
b) Ahmed 36
Ali 4
c) Ahmed 40
Ali 0
d) Ahmed 34
e) None of the other answers is correct.

23) The following Python code fragment is supposed to print out the string s in reverse order
'edcba'..

s = 'abcde'
t = ''
for ch in s:
t = XXX
print(t)
What goes in the place marked XXX?
a) s
b) t + ch
c) ch
d) ch + t
e) s + ch

24) Given the following function definition which returns two values

def func():
x = 1
y = 2
return (x, y)

which of the following code fragments calls the function and prints the second returned value?

a) print(y)
(x, y) = func()
y=func()
b)
print(y)
func(x,y)
c)
print(y)
(y,x) = func()
d)
print(x)
e) There is no correct answer.

25) Which of the following is the correct way of calling the constructor of the class Account to
create an object, assume the constructor takes no arguments?

a) obj = Account. constructor()


b) obj = Account. __init__()
Page 10 of 20

c) obj = Account()
d) obj = Account. __init__(self)
e) obj = Account(self)

26) What will be the content of the file output.txt after running this code?

content = ["Intro","to","programming"]
f = open('output.txt', 'w')
for w in content:
f.write(w)
f.close()
a) Introtoprogramming
b) Intro to programming
Intro
c) to
programming
d) www
e) None of the other answers is correct.

27) What will be the output of the following code fragment?

x = [1, 2, 3]
x = x * 2
evens = []
for i in x:
if i % 2 == 0:
evens.append(i)
print(evens)
a) 2
b) [2, 4, 6]
c) [2]
d) [2, 2]
e) This code will generate an error.

28) Which of the following prints the indexes of the negative numbers in the list x?
For example if x=[ -4, 12, 5, -2], the program will print 0 3

for i in range(x):
a) if i<0:
print(i, end=" ")
for i in range(len(x)):
b) if i<0:
print(i, end=" ")
for i in x:
c) if i < 0:
print(i, end=" ")
Page 11 of 20

for i in range(len(x)):
d) if x[i] < 0:
print(i, end=" ")
e) None of the above

29) Using the following variables


names = "Adam Ali Basel Badr"
scores = "12 3 12 4"
namesList = names.split( )
scoresList = scores.split( )

which of the following code segments will result in creating the following dictionary?

d = {'Adam': '12', 'Ali': '3', 'Basel': '12', 'Badr': '4'}

d = {}
for i in namesList:
a)
d[namesList[i]] = scoresList[i]
d = {}
b) for i in range(namesList):
d[namesList[i]] = scoresList[i]
c) d = dict(names, scores)
d = {}
d) for i in range(len(namesList)):
d[namesList[i]] = scoresList[i]
for i in range(len(namesList)):
e) d = {}
d[namesList[i]] = scoresList[i]

30) What will be the output of the following code fragment?

def changeit ( mylist ):


mylist = [1, 2, 3, 4]
x=[4, 5, 6]
changeit(x)
print(x)

a) [4, 5, 6]
b) [1, 2, 3, 4]
c) Error: the 2 lists must have same size
d) [4, 5, 6, 1, 2, 3, 4]
e) None of the other answers is correct.
Page 12 of 20

31) Given a list x defined as :


x = [3, 6, 2, 1, 4, 8, 3]
Which of the following code fragments will print the following output?
8426
i = len(x)
while i >= 0:
a) if i % 2 == 0:
print(i, end="")
i = i - 1
i = len(x) - 1
while i >= 0:
b) if x[i] % 2 == 1:
print(x[i], end="")
i = i - 1
i = len(x) - 1
while i >= 0:
c) if i % 2 == 0:
print(x[i], end="")
i = i - 1
i = len(x) - 1
while i >= 0:
d) if x[i] % 2 == 0:
print(x[i], end="")
i = i - 1
i = len(x) - 1
while i >= 0:
e) if x[i] % 2 == 0:
print(x[i], end="")
i = i - 1

32) Which of the following statements is correct in Python?

a) The user of a class needs only to know the public interface.


b) To call a method of an object, we must write self as the first
argument.
c) lists and strings are object of the same class.
d) Multiple objects created from the same class always have the same
values for all instance variables.
e) Instance variables cannot be changed after the object is created.
Page 13 of 20

33) What will be the output of the following code fragment?

list1 = [3, 5]
list2 = [4, 6]
list3 = []
for i in list1:
list3.append(i)
for j in list2:
list3.append(j)
print(list3)

a) [3, 4, 6, 5, 4, 6]
b) [3, 5, 4, 6]
c) [3, 3, 3, 5, 5, 5]
d) [3, 4, 4, 5, 4, 4]
e) [3, 5, 4, 6, 3, 5, 4, 6]

34) What will be printed after executing the following C code fragment:

int i;
for(i = 0; i<3 ;i++)
i++ ;
printf("%d", i);

A. 3
B. 4
C. 5
D. 2
E. 6

35) What will be printed after executing the following C code fragment:

int i=5 ;
i++ ;
printf("%d", i++);

A. 4
B. 5
C. 6
D. 7
E. 8
Page 14 of 20

36) What will be printed after executing the following C code fragment:

int *i, *j, n = 3, m = -2;


i = & n ;
j = & m ;
*i = 4 ;
*j = -1 ;
printf("%d %d", m , n) ;
A. 4 -1
B. -1 4
C. 4 4
D. -1 -1
E. 3 -2
37) What will be printed after executing the following C code fragment:
int k = 9 ;
if(k > 10 || k <= 99)
printf("%d",(k - 5));
else
printf("OUT OF RANGE");

A. OUT OF RANGE
B. 9
C. 4
D. 0
E. -5

38) What will be printed after executing the following C code fragment:

int i, j, m = 0;
for(i = 0; i<3 ;i++)
for(j = 0; j<3 ;j++)
m=m+1;
printf("%d", m);
A. 4
B. 6
C. 16
D. 9
E. 12
Page 15 of 20

39) Consider the following C code


#include <stdio.h>
void f1(int a) { a = 5 ; }
void f2(int *b) { *b = 10 ; }
int main() {
int i = 9 ;
f1(i) ;
f2(&i) ;
printf("%d", i) ;
return 0;}
Which of the following is the correct output after executing the above code?
A. 9
B. 5
C. 10
D. 0
E. 15

40) What will be printed after executing the following C code fragment:

int x=7;
if(x >= 5 )
if(x > 10)
if(x <15)
printf("AA");
else
printf("CC");
else if ( x >= 0)
printf("DD");
else
printf("BB");
else
printf("E");
A. AA
B. BB
C. CC
D. DD
E. E
Page 16 of 20

Part 2: 20 points
What is the output generated by the following C or Python code fragments? Write only what
appears on the screen in the output box shown on the right side.

// 2 pts
int val, sum, x;
val = 1;
do {
sum = 0;
for (x = 0; x < val; x++) {
sum = sum + x;
}
val = val + 1;
printf("%d ", sum);
} while (val < 3);

// 2 pts
char c1 = 'z';
char c2 = 'a';
char *c3;
c3 = &c2;
printf("%c\n", *c3);
c3 = &c1;
printf("%c\n", *c3);

// 2 pts
#include <stdio.h>
void test2(int *a, int b);
int main(void) {
int a = 5, b = 10;
test2(&b, a);
printf("%d %d\n", a, b);
return 0;
}
void test2(int *a, int b) {
*a = 7;
b = 8;
}

// 2 pts
int acc = 0, counter = 1;
while (counter <= 3) {
acc = acc + counter;
counter = counter + 1;
}
printf("%d %d\n", acc,counter);

# 1.5 pts
Page 17 of 20

depts = ["ICS", "COE", "ISE", "CHEM", "PE"]


depts.pop(0)
depts.pop(1)
print(depts)

# 1.5 pts
words = {2: "halo", 3: "hom", 1: "chico"}
for key in sorted(words) :
print("%s " % (words[key]))

# 2 pts
for cnt1 in range(2) :
for cnt2 in range(1, 3) :
print(cnt1 + cnt2, end=" ")
print()

# 1 pt
for indx in range(50, 70, 10) :
print(indx)

# 2 pts
str1 = "Jeddah, Riyad, and Dhahran"
print("ah" in str1)
print(str1.count("ah"))

# 2 pts
a=0
b=3
while a != 5 and b != 5:
a = b
b = b + 1
print(" a = " , a, " b = " , b)

# 2 pts
def f(i, j=2):
return i+j
print (f(f(4,3),4))
print(f(5))
Page 18 of 20

Part 3: Programming Question [20 points]


In mathematics, the dot product is the sum of the products of the corresponding entries of the two
equal-length sequences of numbers. The formula to calculate dot product of two sequences of
numbers a =[a0, a1, a2, …, an-1] and b =[b0, b1, b2, …, bn-1] is defined as:
n −1
˙
product= ∑ ai × bi
i=0

For example if a = [3.4 ,-5.2 , 6] and b = [2.5, 1.6, -2.9]


Dot product = 3.4 x 2.5 + (-5.2) x 1.6 + 6 x (-2.9) = -17.22

Write a python program that calculates the dot product. The program should have the following user-
defined functions.

main(): function asks the user for file names that contain the two sequences of real values. The
function calls readInput and dotProduct to read data from files and calculates the dot product
respectively.
readInput(filename): This function receives filename and reads the sequences of real values
from the file, stores them in a list. Then, the function returns the list. You need to call it for each
filename.
dotProduct(list1, list2): This function receives two lists of real values with same length.
It computes and returns their dot product. You are not allowed to print the dot product from this
function.
Note:

 Make sure that your indentation is clear, otherwise you may lose points.
 Your functions must be general and not specific to the given
example. Sample content of the input
 It is not allowed to use global variables and any external files:
library to calculate the dot product.
 Handle all exceptions when dealing with files. input1.txt
3.4
The following are sample runs of the program: -5.2
6
Sample run#1
Enter first file name : input1.txt input2.txt
Enter second file name: input3.txt 2.5
The two sequences numbers are not equal in length. 1.6
-2.9
Sample run#2
Enter first file name : input4.txt input3.txt
Error: the input file: input4.txt is not found -1.5
1.8
Sample run#3
Enter first file name : input1.txt input4.txt file does not exist
Enter second file name: input2.txt
Dot product = -17.22

Sample run#4
Enter first file name : input1.txt
Enter second file name: input4.txt
Page 19 of 20

Error: the input file: input4.txt is not found


Page 20 of 20

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

You might also like