Final Exam 2004 - Solutions

1. Mark all correct statements Recall not only theory, but also your experience.

A. An operating system
[T]   is a program that controls execution of other programs
[F]   is one of the most important hardware components in a computer
[T]   allocates physical resources (CPU time, memory, communication ports, etc.) to running programs
[T, usually]   doesn't communicate with users directly
[F]   ... and therefore doesn't need to be foolproof (i.e. protected from wrong or malicious user's action)   {OS must be foolproof to the fullest, not only against a user's improper keybord input, but also against hardware failures, competing and conflicting resource requests, malicious programs (viruses), network attacks, etc.}

B. Which statements comparing C and C++ are correct:
[F]   A C program must be contained in one file, while a C++ program may extend to several files.
[T]   A C++ compiler will compile every compilable C program.
[F]   In C++, it is not possible to use the stdio.h library. A programmer must use the input/output library iostream.h instead.
[T]   There is no keyword class in C.
[F]   C++ doesn't use pointers
[F]   Programming in C++ is more difficult because a programmer must use classes. {Using classes is not mandatory in C++. Also, after some practice, using classes makes programming easier.}

C. ASCII code is
[T]   a specific byte value assigned to each character
[F]   a specific number of bits assigned to each character
[F]   a table of escape sequences
[F]   a special character such as endline (\n), NULL (\0), and some others.

D. Suppose the variable x  is double  and the variable i  is  int.
[F]   Both assignments  i=x;  and   x=i;  are valid and don't cause any problems.
[F]   At least one of them is a syntax error.
[F]   The assignment  i=x;  doesn't cause a problem, while   x=i;  may lead to a loss of precision due to round-off.
[T]   The assignment   x=i;  doesn't cause a problem, while  i=x;  may lead to a loss of precision due to round-off.
[F]   Using explicit casts:   x=(double)i;  and   i=(int)x; , a programmer avoids potential round-off problems.

E. How many constructors and destructors can a class have?
[F]   Any number of constructors and any number of destructors.
[F]   Same (any) number of constructors and destructors.
[T]   Any number of constructors but at most one destructor.
[F]   At least one constructor and exactly one destructor.

F. The following lines in a C++ program
      ofstream ofile;
      ofile.open(argv[0]);
[F]   make possible input from a file specified in the command line
[F]   make possible output to a file specified in the command line   {would be True for argv[i] with i>0.}
[T]   is an attempt to erase the running program's file    {whose name is argv[0]}
[F (with reservations)]   make possible for the program to alter its own executable code "on the fly"   {Depends on the operating system. A good OS fails the  open  operation and enforces the value TRUE of  ofile.fail()  after it.

G. What of the following will likely cause "Memory Fault" error?
[F]   A variable declared but never used    { => compiler's warning}
[F]   Reference to a variable that wasn't declared    { => syntax error}
[T]   Reference to an array element with negative index
[T]   Improperly defined size of array
[F]   Attempt to divide by zero    { => Overflow error}
[F]   Passing a negative value to function sqrt    { => NAN (not a number) error}

2. Evaluate (the answer must be a number):

a)   4|2    Ans: 6   {100 | 010 = 110}
b)   5&3   Ans: 1   {101 & 011 = 001}
c)   7%1   Ans: 0
d)   11%4   Ans: 3
e)   (x*x==-1)   Ans: 0  {false}
f)   !(x&&0)   Ans: 1  {since for any x, x&&0=0}
g)   11/4.0   Ans: 2.75
h)   11/4   Ans: 2     (in theory. In practice, the test program revealed a strange effect, which I can't explain but suspect it is a deviation from language standards in implementation of printf.).

3. Each of the following lines of code contains some uncommon (suspicious) feature that may have been overlooked by a programmer. Identify such a feature. Match the codes with descriptions of effect. Assume i is of type int.

A    for (i=0; i!=5; ); {i++;}        /* semicolon before '{': empty loop. The value of i isn't changing, because {i++;} is not a part of the loop. */
B    for (i=i; i!=5; i++) { }        /* initialization i=i has no effect. Value of i remains uninitialized. */
C    for (i=0; i!=5) {i++;}        /* missing "update" part of for-loop */
D    for (i=0; i!=5; i++) {i++; } /* i incremented in two places in the loop. It never equals 5 exactly. */       

Descriptions / answers:
[B] Unpredictable number of iterations
[A, D]   Infinite loop
[none]   Loop exits in less than 5 iterations
[C]   Syntax error

4. Trace execution and determine the output of the following C code.
12     int p,q,a,b,i,j;
13     char* hint="i eat shy";  /* note: spaces are characters too */
14     p=737;
15     q=236;
16     for(i=0; i<4; i++)
17     {
18        a=p/q;
19        b=q;
20        q=p%q;
21        p=b;
22        j=i+(i!=2);
23        printf("%c%c", hint[a-j], hint[a]);
24     }
25     printf("!\n");

Output:    easy hit!      Test program

 line |  p  |  q  |  a  |  b  |  i  |  j  | output | comment
------------------------------------------------------------
 13i  hint=[i eat shy\0]    hint[0]=i, hint[1]=<space> etc.
            012345678 9
14,15 | 737 | 236 |  ?     ?     ?     ?
 16a  |     |     |              0                  enter loop  
 16b  |     |     |                                 (0<4) True
18,19 | 737 | 236 | 3    236
 20   |     | 29  |                                 737=236*3+29
 21   | 236 |     |
 22a  |     |     |                                 (i!=2) True=1
 22b  | 236 | 29  | 3    236     0     1             j=0+1=1
 23   |    (a-j=2, a=3)                       ea                                                      
---------------------------------------------------------------
 16a  |     |     |              1                  i=0+1  
 16b  |     |     |                                 (1<4) True
18,19 | 236 | 29  | 8    29
 20   |     |  4  |                                 236=29*8+4
 21   |  29 |     |
 22   |  29 |  4  | 8    29      1     2            j=1+(T)=2
 23   |    (a-j=6, a=8)                       sy                                                      
---------------------------------------------------------------
 16   |     |     |              2                  i=1+1, (2<4) T  
18,19 |  29 |  4  | 7     4
 20   |     |  1  |                                 29=7*4+1  
 21   |   4 |     |
 22   |   4 |  1  | 7     4      2     2            j=2+(F)=2
 23   |    (a-j=5, a=7)                       _h                                                      
---------------------------------------------------------------
 16   |     |     |              3                  i=2+1, (3<4) T  
18,19 |   4 |  1  | 4     1
 20   |     |  0  |                                 4=4*1+0   
 21   |   1 |     |
 22   |   1 |  0  | 4     1      3     4            j=3+(T)=4
 23   |    (a-j=0, a=4)                       it                                                      
---------------------------------------------------------------
 16   |     |     |              4                  i=2+1, (4<4) F 
---------------------------------------------------------------
 25   |  1  |  0  |  4    1      4     4      !<\n>   loop exited

5. Determine the output of the following C++ program. (Full trace is not required.)
1     #include <stdio.h>
2     class MyClass	
3     {
4       private:
5         int y,m,d;
6
7       public:
8         MyClass(int a, int b, int c);
9         ~MyClass();
10        int count();
11    };
12
13    int main()
14    {
15       MyClass x(2004,12,11);
16       while (x.count()){}
17       return(0);
18    }
19
20    MyClass::MyClass(int a, int b, int c)
21    {
22       y=a;
23       m=b;
24       printf("Start: %d/%d/%d!\n",y,m,d);
25       d=c;
26    }
27
28     MyClass::~MyClass()
29     {
30       y++;
31       m = m%12+1;
32       d=1;
33       printf("End: %d/%d/%d!\n",y,m,d);
34     }
35
36     int MyClass::count()
37     {
38       printf("%d,",++d); 
39       return(31-d);
40     }

Output:    Start: 2004/12/???! 12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,End: 2005/1/1!
(here ??? is a "random" (unitialized) value.)    Test program

Argument (instead of full trace).
Execution begins in line 15, where the constructor with arguments is invoked. We jump to line 20, where the values a,b,c become 2004,12,11 respectively. These values are then assigned to class member variables in lines 22,23,25. The output in line 24 refers to already known values of y, m and to a not yet initialized value of d. Thus we obtain "Start: 2004/12/???!"

Upon returning from constructor to main(), we proceed to line 16, which is a loop. Every time the member function count() is invoked and the loop continues while the value received from count() is nonzero. Analyse the code of count() in lines 38-39. The returned value is zero when d=31. How does d change? It gets incremented in line 38 by 1 each time. The prefix form i++ of the increment operator is used, therefore the value of i is first incremented, then printed (followed by comma). The initial value (from line 25) was d=11, therefore the first printed value will be 12. The last printed value will be 31.

After the loop in line 16terminates, the program must exit, but the destructor is automatically invoked in line 17. We proceed to lines 28-34, where the values become y=2004+1=2005, m=12%12+1=1, d=1. These are printed. Destructor returns to main() and the program ends.

6. Programming project: electrostatic potential of a system of point charges.
[The word electrostatic was misspelled in exam sheets.]
N electric charges of given magnitudes Q1,..., QN are located at points P1,...,PN in space. Each point is characterized by three given coordinates (xj, yj, zj),   j=1,...,N. Write a program to find the electrostatic potential phi(S) at the observation point S with given coordinates (X,Y,Z).

Mathematical definition.
phi(S)=A (Q1 / R1+... +QN / R N),
where:
A is a physical constant,
Qj is the magnitude of the j-th charge,
Rj=|Pj S|= Sqrt [ (xj-X)2+ (yj-Y)2+ (zj-Z)2 ]
is the distance from the observation point to the j-th charge.
The potential is undefined  (is infinite) when the observation point coincides with one of the charges.

Physical units.
If the unit of length is meter, the unit of charge is Coulomb, and the unit of electric potential is Volt, then the numeric value of the constant A in vacuum is
A=1/(4*Pi*epsilon0)=8.988 x 109    (Volt m)/Coulomb.
You may (if you wish) assume for simplicity that the units are such that A=1.

Programming notes.


Solution:    A program  and a sample input file  kindy provided by Shannon Sullivan
(BTW, it is an example of a C++ program without classes -- cf. last item in Q. 1B.)

Here is a "minimal" passing-guaranteed program