Barik Question and Answer

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

STUDENT ID: FMS/0161/16

OPTION: BSc COMPUTER SCIENCE


C. K. TEDAM UNIVERSITY OF TECHNOLOGY AND APPLIED SCIENCES
FACULTY OF MATHEMATICAL SCIENCES
COMPUTER SCIENCE DEPARTMENT
SECOND SEMESTER’S EXAMINATION ANSWER ALL QUESTIONS CSC 418-
COMPARATIVE PROGRAMMING LANGUAGES TIME: HOURS
INSTRUCTIONS: Yours answers should be brief and precise. The duration of the paper is
three hours, the remaining thirty minutes is to be used for preparation, organization,
scanning and submission or uploading to my mail.
It should be submitted to [email protected] with the Subject as SUBMISSION in caps, a
hyphen and your student Identification number. Example: SUBMISSION-FMS/0027/02

SECTION A (20%)

STUDENT ID NUMBER :FMS/0161/16


QUESTION 1 (10 marks)

(a) James Gosling from Sun Microsystems and his team initiated the Java language project in

i …1991… whiles ii…Bjarne Stroustrup….developed C++ in iii…1979……

at……Bell Labs…. C++ is regarded as an intermediate-level language because it comprises

iv……high-level…….…and v…low level languages features. (3 marks)

(b) C++ introduces object-oriented programming (OOP) features to C. It offers classes, which

provide the four features commonly present in OOP (and some non-OOP) languages including:

(i) Abstraction, (ii) Encapsulation (iii) Inheritance and (iv) Polymorphism


(2 marks)

(c) The Java Programming Language was created with some ideals including; (5 marks)

(i) It should be simple, object-oriented and familiar

(ii) It should be robust and secure.

1
STUDENT ID: FMS/0161/16
OPTION: BSc COMPUTER SCIENCE
(iii) It should execute with high performance

(iv) It should be architecture-neutral and portable.

(v) It should be interpreted, threaded and dynamic.

QUESTION 2
Use the code below to answer questions (i) and (ii). (5 marks)

name.cpp
#include <stdio.h> #include
<stdlib.h> using namespace std;

int main (int argc, char *argv[]) { if (argc != 2) {


printf ("You forgot to type your name.\n"); exit(1);
} printf("Hello %s", argv[1]); return 0;
}

i. Write the output of the program if after compilation, the statement name Peter is entered to run
the program in command prompt. (2
marks)
Answer

The output for the above program would be “Hello Peter”.

ii. Clearly describe the argc and argv parameters in the main function of the C++ code (3 marks)

Answer
(a) The argc parameter holds the number of arguments on the command line and it is always an
integer. It is always at least 1, because the name of the program qualifies as the first parameter

(b) The argv parameter is a pointer to an array of character pointers. Each element in this array
points to a command line argument.

SECTION B (55%)

2
STUDENT ID: FMS/0161/16
OPTION: BSc COMPUTER SCIENCE

QUESTION 1

a. Write the C++ version of the Java code below separating the class declaration from the
implementation file. (4 marks) file
Person.java:
/* This class represents a Person */ public class Person
{ /* person constructor */ public Person(String name, int
age)
{ this.name = name; this.age =
age;
}
/* mutator for age */ public void
setAge(int age)
{ this.age = age;
}
/* accessor for name */ public String
getName()
{ return name;
}
/* accessor for age */ public int getAge()
{ return age;
}
/* print out full information */ public void print()
{
System.out.print("Name: " + name + " Age: " + age);
}
private String name; private int age;
}
b. Indicate three (3) differences between the two versions. (3 marks)

c. By creating Person objects, write C++ and Java programs that prints the name and age of
any person. (3 marks)

d. Java is referred to as WORA while C++ is referred to as WOCA. Briefly Explain.(3


marks)
e. What differences exist in how method parameters are passed in Java and C++? (3 marks)

f. Destructors in C++ announce the “death” of a class. What do destructors in Java do?
(3 marks)

3
STUDENT ID: FMS/0161/16
OPTION: BSc COMPUTER SCIENCE
Answer to Question 1

a) Class Declaration File

person.h
/* This class represents a Person */
#include <string>
Using std::string
class person
{
Public:
// Constructor
Person(string name, int age);

// Mutator
Void setAge(int age);

// Accessors

String getName() const;


Int getAge() const;

// Print out full information


Void print() const;

Private:
String _name;
Int_age;
};

Implementation for class person

#include “person.h”
#include “<iostream>

Using std::cout;

Person:: Person(string name, int age): _name(name), _age(age)


{}
Void Person:setAge(int age)
{
_age = age;
}

4
STUDENT ID: FMS/0161/16
OPTION: BSc COMPUTER SCIENCE
String Person::getName() const
{
return _name
}

Int person::getAge() const


{
Return _age;
}

void Person::print() const


{
Cout<<”Name ”<< _name << “Age: “<< _age;
}

b) Differences between C++ and Java Versions of the Code Above


1. In the C++ version above, the implementation of the code is separated from class
declaration whiles in java both declaration and implementation are all included in
a single file.
2. In the C++ version, the program includes <iostream> and specifies that is is using
namespace std whiles, the Java program imports java.io.* in order to be able to
output results to the screen
3. In the C++ version, the keyword #include is used to add libraries and external
resources whiles in Java the key word import is used to add libraries and external
resources to the program.

c) C++ and Java Objects


In C++ writing a Person object would be
// Object declaration
Person object1(“victor”, 20);

//Getting name and age


object1.getName();
object1.getAge();

5
STUDENT ID: FMS/0161/16
OPTION: BSc COMPUTER SCIENCE
In Java writing a Person object would be
// Object declaration

Person javaObject = new Person(“victor”, age);

//Getting name and age


javaObject.getName();
JavaObject.getAge();

d) WORA AND WOCA

i) Java is referred to as WORA which stands for Write Once Run Anywhere.
This acrimony illustrates the cross-platform benefit of java that enables java
program written and compiled on any device to be able to run on any device
anywhere. This is possible because of the Java Virtual Machine.

ii) C++ is referred to as WOCA which stands for Write Once Compile
Anywhere. This illustrates C++ ability that of writing computer programs that
can be compiled on all platforms without the need to modify its source code.

e) Destructor in Java
Destructors in java are used to free up memory allocated during the initialization and
declaration of variables. Java has a feature called automatic garbage collector and this
does the work of a destructor in C++. The method finalize is used to free memory from
previous initializations.

QUESTION 2

a.i. Give two(2) forms of the #include directive in C++ and briefly state their meanings. (2 marks)

Answer
a) The first form is #include <filename>: This is used for standard library headers. Examples
are; #include <iostream>
b) The second form is #include “filename”: This form is used to include header files written
by programmers. Example; #include “convert.h”. this form normally includes the .h suffix.
6
STUDENT ID: FMS/0161/16
OPTION: BSc COMPUTER SCIENCE

ii. Importing a class does not automatically import classes it imports; each class must explicitly
import the classes it needs. Briefly explain. (2 marks)
Answer
This simply means, a class that is imported in another class does automatically import the
classes that it contains. For instance, a class called Person, containing other imported
classes such as strings, when imported into another class say, School, the string class
contained in Persons does not get imported into the School class. If string class is need, it
must be imported itself in the School class.

iii. Compare the import directive in Java with the #include and using directives in C++. (2 marks)
Answer
The java import directive in used to include other classes in a program. Its syntax is”java.”
or “javax.” It is possible to include all classes in a given package using the wildcard “.*”
The #include refers to textual inclusion in C++. When used, in a program, the text of the
header file is copied at that point.

b. Briefly outline the difference(s) between C++ and Java string type(s). (2 marks)
Answer
a) C++ strings are treated as an array of characters where java strings are treated as
a reference type.
b) String in C++ are terminated as a null character ‘\0’ while java strings are not
since they are not treated as an array of characters.

c. Use the code below to answer (i) and (ii)


i. What is the output of the following code?
(1 mark)
Answer
The output would be “Hello World”

ii. Write a C++ code that will produce similar output as the Java code shown below:

void foo(StringBuffer x)
{
x.append(“ world!”);
}

StringBuffer s = new StringBuffer(“Hello”); foo(s);
System.out.println(s);
(3 marks)

7
STUDENT ID: FMS/0161/16
OPTION: BSc COMPUTER SCIENCE
Answer

void foo(string & x)


{
x += " world!";
}
...
string s = "Hello";
foo(s);
cout << s << endl;

QUESTION 3

a. Write the Java version of the C++ code below and indicate two (2) differences between both
versions. (8 marks)

#include <iostream> using


namespace std;

int fibCallsCounter;

/* Calculate the nth fibonacci


* number. Increment fibCallsCounter
* every time it is called.
*/

int fib(int n)
{ fibCallsCounter ++; if (n <= 2)
return 1; else
return fib(n-1) + fib(n-2);
}

int main(int argc, char * argv[])


{ while (true)
{ int N;
fibCallsCounter = 0;
cout << "Desired value of N - "
<< "0 to quit: "; cin >>
N; if (N == 0) break; cout <<
"The " << N
<< "th fibonacci number is "
<< fib(N) << endl;

8
STUDENT ID: FMS/0161/16
OPTION: BSc COMPUTER SCIENCE
cout << "Function was called "
<< fibCallsCounter
<< " times" << endl;
}
}

Answer

/*
Java Equivalent of the above program
*/
import java.io.*;
public class Demo1
{
private static int fibCallsCounter;
/* Calculate the nth fibonacci
* number. Increment fibCallsCounter
* every time it is called.
*
* @param n desired fibonacci number
* @return the fibonacci number
*/
private static int fib(int n)
{
fibCallsCounter ++;
if (n <= 2)
return 1;
else
return fib(n-1) + fib(n-2);
}
public static void main(String[]args)
throws IOException
{
while (true)
{
int N;
fibCallsCounter = 0;
System.out.print(
"Desired value of N - " +
"0 to quit: ");
String input =
(new BufferedReader(

9
STUDENT ID: FMS/0161/16
OPTION: BSc COMPUTER SCIENCE
new InputStreamReader(
System.in))).readLine();
N = Integer.parseInt(input);
if (N == 0)
break;
System.out.println("The "+ N +
"th fibonacci number is " +
fib(N));
System.out.println(
"Function was called " +
fibCallsCounter + " times");
}
System.exit(0);
}
}

Difference between both Versions

a) Java uses the import statement to add external library files to


the program whiles C++ uses #include to add external files to
the program
b) Java makes use of the System.exit(0) to return the status of the
program termination whiles C++ does not make use of such
statement in this program.

b. Briefly compare C++ pointers and Java references. Indicate any similarities and
differences between them. (4 marks)
Answer

c) The real difference is, in C++ the term "pointer" strictly means
an integer that happens to be the memory address of some data.
Whereas in Java the term "reference" more closely matches the
C++ "reference" concept. You can't work with the memory
address directly even if you want to, but you use it the same
way.

QUESTION 4

10
STUDENT ID: FMS/0161/16
OPTION: BSc COMPUTER SCIENCE
a. What is meant by binding a storage allocation to a variable? (2 marks)

Answer
It refers to the establishment of a connection between a variable and the memory location it refers
to.

b. Both Java and C++ accomplish this binding in one of three ways. Enumerate these approaches
and clearly identify differences in both languages if they exist. (6 marks)
Answer
1. Static or Permanent allocation: This binding between a variable and a particular
location or memory lasts during the entire time the program is running. C++ uses this
for all top-level variables (declared outside any class or function), and also for variables
explicitly declared static either inside a class or in a function. Java uses static allocation
only for variables that are explicitly declared static in a class; it does not have top-level
variables and does not allow local variables of a function to be declared static.

2. Automatic or stack allocation: The binding between a local variable in a


function/method and a particular location in memory is established when the
declaration for the variable is reached during the execution of the function. It remains
in effect until the block in which the variable is declared exits.

3. Dynamic (heap) allocation: The binding of storage for an entity is accomplished by an


explicit use of the new operator, which always returns a pointer to the newly allocated
storage. Both Java and C++ use new in similar ways. However, they handle freeing up
unneeded storage differently. In Java, the storage remains allocated until there are no
more references to the entity, in which case the storage is reclaimed by garbage
collection. In C++, the programmer is responsible for explicitly freeing storage
allocated using new by using the corresponding operator delete. This approach is more
time efficient, since garbage collection is time consuming; however, it is also a source
of programming errors when a programmer either forgets to free up storage when it is
no longer needed (resulting in storage leaks) or frees up storage prematurely (resulting
in dangling references) or multiple times (usually resulting in serious corruption of the
storage management subsystem.) The following illustrates the difference between C++
and Java as regards the explicit deallocation of dynamic storage

c. Java does not really support the kind of separation of interface and implementation that C++
supports. Give two (2) points to support this statement. (2 marks)
Answer

11
STUDENT ID: FMS/0161/16
OPTION: BSc COMPUTER SCIENCE
1. Because each publicly accessible Java class must be placed in its own source (.java)
file.
2. Because when a java source file is compiled the resulting .class file contains both
the method of declarations and their implementations.

d. Rounding and precision of floating-point values and operations in C++ and Java is different. In
two sentences, agree or disagree with the statement giving examples where necessary. (2 marks)
Answer

I agree. Because the algorithm doing the compile computations of floating points numbers in both
java and C++ are different, hence different results are produced in the cases of high precision.

12

You might also like