CIT 834 Past Questions and Answers by Henry Finebone
CIT 834 Past Questions and Answers by Henry Finebone
Answers
Codes in answers
(ii) Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of another class.
For example, the bird ‘robin’ is a part of the class “flying bird’ which is again a part of the class ‘bird’. The
principle behind this sort of division is that each derived class shares common characteristics with the
class from which it is derived. The concept of inheritance provides the idea of reusability. This means that
we can add additional features to an existing class without modifying it. This is possible by deriving a new
class from the existing one. The new class will have the combined features of both the classes.
(iii) Data abstraction and encapsulation
Data abstraction refers to the act of representing essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes
such as size, weight and cost, and functions to operate on these attributes. They encapsulate all the
essential properties of the objects that are to be created.
Encapsulation, also known as data hiding, is an important object-oriented programming concept. It is the
act of concealing the functionality of a class so that the internal operations are hidden from the
programmer. With correct encapsulation, the developer does not need to understand how the class
actually operates in order to communicate with it via its publicly available methods and properties; known
as its public interface.
3. In order to assess your expertise in Object-Oriented Programming using C# Programming, you are required
to write a standard C# program to carry out two mass calculations and provide the output of the call count
property, where the Density is given as 40; Volume1 = 120; Volume2 = 140.
{
int density = 40; int
volume = 120; int
volume2 = 140;
int mass1 = MassCalculator.CalculateMass(density, volume);
int mass2 = MassCalculator.CalculateMass(density, volume2);
int calls = MassCalculator.CallCount;
Console.WriteLine("Mass1: {0}", mass1); // Outputs "Mass1: 5000"
Console.WriteLine("Mass2: {0}", mass2); // Outputs "Mass2: 9000"
Console.WriteLine("Calls: {0}", calls); // Outputs "Calls: 2"
}
4. Outline the procedure involved in constructing a simple Two-Dimensional Vector Class having K and L as
its properties.
private int _k, _l;
public Vector(int k, int l) { _k = k; _l = l; }
public int K
{
get { return _k; }
set { _k = value; }
}
public int L
{
get { return _l; }
set { _l = value; }
}
5. If a specific integer is given as 8, write down a simple C# Program to compute and output the square of this
integer.
static void Main(string[] args)
{
int squareMe = 8;
Console.WriteLine(Calculate.Square(squareMe));
}
/* OUTPUT
Integer Square calculated
64
*/
9. What steps would you adopt in creating a new project named ‘Practise.cs’?
1. Select File -> New project
2. From the project dialog, select the Console application
3. This is the most basic application type on a Windows system
4. Click Ok
5. Visual C# Express creates a new project for you, including a file called Program.cs.
12. In simple terms, describe how static methods are called in C#.
A static method is declared using a similar syntax to a class method. The 'static' keyword is used in the
declaration to indicate the modified behaviour. To add the mass calculation method to the new class,
insert the following code:
13. State the code for accomplishing the following in C#:
(i) Adding a mass calculation method to the new class
public static int CalculateMass(int density, int volume)
{
return density * volume;
}
14. Go through the source code carefully and answer the questions that follow:
(iii) State the main role of the keyword you have specified.
This keyword “using” imports a namespace.
15. Outline the steps required to build a new project named ‘Abuja’ and setup a form using the Windows
Application template.
First, we create a new Console Application project
Steps:
1. Open visual studio --> under file menu select the option new -->select project
2. On the left side, select Templates --> select Visual C# and select the Console Application. Name the
application ‘Abuja’.
3. After creating an application, by default, it will create a Program.cs file.
4. In C# programming the main method is where Program start execution it is the main entry point of the
program that executes all the objects and invokes methods to execute.
5. Click on F5 and execute the project, and follow the console window.
Then we create the form using the Windows Application template.
Steps:
1. Click the File menu again.
2. This time, select New Project from the menu. When you do, you'll see the New Project dialogue box
again.
3. Select Windows Application from the available templates. Keep the Name as ‘Abuja’ and then click OK.
When you click OK, a new Windows Application project will be created for you.
16. Based on the premise that you have successfully completed the course in Object-Oriented Programming
using C#, a newly registered learner has just approached you for guidance on how to build a C# sample
in a Microsoft.NET 2.0 SDK Framework. Outline the procedure you would adopt in order to accomplish
this requisite assignment.
1. Open the Microsoft .NET Framework 2.0 SDK command prompt (from the Windows Start menu, select
Programs > Microsoft .NET Framework SDK v2.0 > SDK Command Prompt. The command prompt
launches.
2. Navigate to the sub-directory containing the Build2005.cmd and other files: cd
%SDKHOME%\samples\DotNet
3. Run the Build2005.cmd to generate new stubs and compile into an assembly. Simply enter the name of
the script at the command prompt: build2005
4. Test your development workstation.
17. Give a short description of the following features in a common FCL library:
(i) Interop
This provides backward-compatibility with COM and Win32 code.
int s = 0, c = 0;
s, c = fun(a);
Console.WriteLine(s +" " + c) ;
}
static int fun(int x)
{
int ss, cc;
ss = x * x; cc = x * x * x;
return ss, cc;
}
}
}
Select, at most, two (2) correct statements among the following:
(i) An error will be reported in the statement s, c = fun(a); since multiple values returned from a function
cannot be collected in this manner.
(ii) It will output 25 125.
(iii) It will output 25 0.
(iv) It will output 0 125.
(v) An error will be reported in the statement return ss, cc; since a function cannot return multiple values.
(i) An error will be reported in the statement s, c = fun(a); since multiple values returned from a function
cannot be collected in this manner.
(v) An error will be reported in the statement return ss, cc; since a function cannot return multiple values.
23. Select a combination of correct statements about subroutines usage in C#.NET? (Choose only from the
options (A, B, C, D) provided.
(i) If we do not return a value from a subroutine then a value -1 gets returned.
(ii) Subroutine definitions cannot be nested.
(iii) Subroutine can be called recursively.
(iv) To return the control from middle of a subroutine exit subroutine should be used.
(v) Subroutine calls can be nested.
A. [(i), (ii), (iii)] B. [(ii), (iii), (v)] C. [(iii), (v)] D. [(iii), (iv)]
B. [(ii), (iii), (v)]
24. Define what constructors are and their role in C# programming.
A constructor is a special class member that is executed when a new object is created. The constructor's
job is to initialise all of the public and private state of the new object and to perform any other tasks that
the programmer requires before the object is used.
25. Write the correct syntax for adding two (2) integer variables to a Parallelogram class.
class Parallelogram
{
private int _base;
private int _height;
}
26. Study the figure below carefully and answer the questions that follow:
(i) Give any 2 reasons why this application is considered suitable for learning Object-Oriented
Programming using the C# and utility programs?
1. This application is ideal for learning C# development because the user interface is so simple.
2. Console application is very useful for utility programs that require little or no user interaction.
(ii) State the procedure involved in creating a new Console Application project.
A Console Application is an application that takes input and displays output at the console. This console
looks like a DOS window.
Creating a new Console Application project:
1. Open visual studio --> under file menu select the option new -->select project
2. On the left side, select Templates --> select Visual C# and select the Console Application. Give some name
for the application,
3. After creating an application, by default, it will create a Program.cs file.
4. In C# programming the main method is where Program start execution it is the main entry point of the
program that executes all the objects and invokes methods to execute.
5. Click on F5 and execute the project, and follow the console window.
27. Enumerate the steps required to build a novel class to represent a triangle. The class should be created in
such a way that it will define the triangle's height, base-length and area.
public class Triangle
{
private int _height;
private int _baseLength;
public int Height
{
get
{
return _height;
}
set
{
if (value < 1 || value > 100)
{
throw new OverflowException();
}
_height = value;
}
}
public int BaseLength
{
get
{
return _baseLength;
}
set
{
if (value < 1 || value > 100)
{
throw new OverflowException();
}
_baseLength = value;
}
}
public double Area
{
get
{
return _height * _baseLength * 0.5;
}
}
}
28. Within the context of programming using C#, what solution would you proffer, in the event that a web
service from Microsoft .NET client sample does not connect through a proxy server?
Try a different server on the same subnet as the client.
29. What determines the type of setup instruction used for C# Development?
Whether your development workstation already meets some or all of the requirements, and whether you
plan to use the provided samples.
30. Explain the concept of ‘private method’ within the context of Object-Oriented Programming using C#.
To provide for encapsulation, where the internal functionality of the class is hidden, some methods will
be defined as Private. Methods with a private protection level are completely invisible to external classes.
This makes it safe for the code to be modified to change functionality, improve performance, etc. without
the need to update classes that use the public interface. To define a method as private, the private
keyword can be used as a prefix to the method. Alternatively, using no prefix at all implies that the method
is private by default.
31. Demonstrate with example how parameters are being passed and received by a method.
The parameters a method receives are also provided in a set of parentheses, but the type and a name for
each parameter must be specified. The name does not have to be the same as the argument. For example:
public static void PassesInteger()
{
int fortyFour = 44;
TakesInteger(fortyFour);
}
static void TakesInteger(int i)
{
i = 33;
}
Here a method called PassesInteger passes an argument to a method called TakesInteger. Within
PassesInteger, the argument is named fortyFour, but in TakeInteger, this is a parameter named i. This
parameter exists only within the TakesInteger method.
32. Declare three (3) methods named; RegisterCourse, TakeExam, and GetResults with no parameters and
return no value under a class named student.
class Student
{
public void RegisterCourse(int numberofcourses) { }
public void TakeExam() { }
public int GetResults(int scores) { return 0; }
}
33. Refer to question 32 above, call the method with the student named “Peter” with the following arguments;
assuming he registered 2 courses, took exams on those two courses and had 60 and 57 respectively as
result.
Student Peter = new Student();
Peter.RegisterCourse(2);
Peter.TakeExam();
Peter.GetResults(60, 57);
34. Write a C# program to display the text “NOUN is a citadel of learning” using the WriteLine method.
using System ;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("NOUN is a citadel of learning");
Console.ReadLine();
}
}
}
37. Outline the steps taken to add a C# class using solution explorer.
1. In Solution Explorer, right-click the project name and click Add, and then click Add Class.
The Add New Item dialog box appears with the C# Class icon already selected.
2. In the dialog box, enter a class name in the Name field and click Open.
The new class is added to your project.
40. Identify a general form of a class definition for a class named “payment” and declare 4 instance variables
named; basicpay, houseallowance, transallowance and tax.
class payment {
// declare instance variables
access type basicpay;
access type houseallowance;
access type transallowance;
access type tax;
// ...
access type varN;
// declare methods
access ret-type method1(parameters) {
// body of method
}
access ret-type method2(parameters) {
// body of method
}
access ret-type method3(parameters) {
// body of method
}
access ret-type method4(parameters) {
// body of method
}
// ...
access ret-type methodN(parameters) {
// body of method
}
}
41. Show how a static method is declared with a formula to calculate the area of a rectangle, use values of
your choice to call the method.
Declaring the static method:
public static int CalculateArea(int length, int breadth)
{
return length* breadth;
}
Calling the static method:
static void Main(string[] args)
{
int length = 15;
int breadth = 10;
int area = AreaCalculator.CalculateArea(length, breadth);
Console.WriteLine("Area: {0}", area); // Outputs "Area: 150"
}
45. Demonstrate with examples the relationship between a class and an object.
The class is the abstract concept for an object that is created at design-time by the programmer. While
objects based upon the class are the concrete instances of the class that occur at run-time. For example,
the Car class will define that all cars have a make, model and colour. Only at run-time will an object be
instantiated as a Red.
46. Demonstrate how .net framework manages memory through garbage collection.
When objects are created they occupy some memory. As memory is a limited resource, it is important
that once the objects are no longer required, they are cleaned up and their memory is reclaimed. The
.NET framework uses a system of garbage collection to perform this activity automatically so that the
developer does not need to control this directly.
51. Write a C# program to add increment operator and test the program with (10,15) and display the results
on console.
public static Vector operator ++(Vector v)
{
v.X++;
v.Y++;
return v;
}
To test these operators, update and execute the Main method:
static void Main(string[] args)
{
Vector v1 = new Vector(10, 15);
v1++;
Console.WriteLine("({0},{1})", v1.X, v1.Y); // Outputs "(11,16)"
}
52. Illustrate syntactically, the declaration of a binary operator and explain each line of the illustration.
public static result-type operator binary-operator (
op-type operand,
op-type2 operand2
)
This initially appears to be a rather complex declaration but in fact is quite simple. The declaration starts
with public static as all operators must be declared as such. Other scopes are not permitted and neither
are non-static operators.
The result-type defines the data type or class that is returned as the result of using the operator. Usually
this will be the same type as the class that it is being defined within. However, that need not be the case
and it is perfectly valid to return data of a different type.
The operator keyword is added to tell the compiler that the following binary-operator symbol is an
operator rather than a normal method. This operator will then process the two operand parameters, each
prefixed with its data type (op-type and op-type2). As least one of these operands must be the same type
as the containing class.
53. Describe with an example how a reference type is created with the class keyword.
public class SampleRefType
{
public int value;
}
54. Declare a static method with a formula to calculate the area of a parallelogram. Use values of your choice
to call the method.
Declaring the static method:
public static int CalculateArea(int base, int height)
{
return base * height;
}
Calling the static method:
static void Main(string[] args)
{
int base = 8;
int height = 12;
int area = AreaCalculator.CalculateArea(base, height);
Console.WriteLine("Area: {0}", area); // Outputs "Area: 96"
}
56. Write a C# program to display the text “Nigeria is a great country” using the WriteLine method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Nigeria is a great country ");
Console.ReadLine();
}
}
}
62. Justify the importance of garbage collection in the process of object creation.
When objects are created they occupy some memory. As memory is a limited resource, it is important
that once the objects are no longer required, they are cleaned up and their memory is reclaimed. The
.NET framework uses a system of garbage collection to perform this activity automatically so that the
developer does not need to control this directly.
64. Create syntactically a new addition operator for the Vector class and instantiate two vector objects v1 and
v2 with values of (10,16) and (4,18) respectively, add them together and give the result.
public static Vector operator +(Vector v1, Vector v2)
{
return new Vector(v1.X + v2.X, v1.Y + v2.Y);
}
We can now test the Vector's new operator by modifying the program's main method. The following
program instantiates two Vector objects, adds them together and outputs the values of the resultant
Vector's X and Y properties.
static void Main(string[] args)
{
Vector v1 = new Vector(10, 16);
Vector v2 = new Vector(4, 18);
Vector v3 = v1 + v2;
Console.WriteLine("({0},{1})", v3.X, v3.Y); // Outputs "(14,34)"
}
66. What are the requirements for Web services client application?
1. Development environment for C#, such as Microsoft Visual C#, Microsoft Visual Studio 2003, or
Microsoft Visual Studio 2005.
2. Microsoft .NET Framework, specifically Microsoft .NET Framework 2.0 (which is included with
Microsoft Visual Studio 2005).
3. Microsoft .NET Framework 2.0 Software Development Kit. Depending on the specific version of the
Microsoft Visual Studio and Microsoft .NET Framework that you use, you may need to also specifically
install the Microsoft .NET Framework 2.0 software development kit, which includes the command-line
C# compiler (csc.exe).
69. Create a class that represents a triangle with the definition of its properties: height, base-length and area.
static void Main(string[] args)
{
Triangle triangle = new Triangle();
Console.WriteLine("Height:\t{0}", triangle.Height);
Console.WriteLine("Base:\t{0}", triangle.BaseLength);
Console.WriteLine("Area:\t{0}", triangle.Area);
}
/* OUTPUT
Triangle constructor executed
Height: 1
Base: 1
Area: 0.5
*/
70. Using an example, state the code for the execution of a constructor.
The newly added constructor replaces the default constructor and is executed automatically when a new
Triangle is instantiated. This can be tested by adding some code to the console application's Main method.
Add the following code and execute the program to test the results and to see that the height and base-
length are set correctly.
static void Main(string[] args)
{
Triangle triangle = new Triangle();
Console.WriteLine("Height:\t{0}", triangle.Height);
Console.WriteLine("Base:\t{0}", triangle.BaseLength);
Console.WriteLine("Area:\t{0}", triangle.Area);
}
/* OUTPUT
Triangle constructor executed
Height: 1
Base: 1
Area: 0.5
*/
71. Give a concise explanation of the concept of Polymorphism as it relates to inheritance and upcasting.
When using inheritance, polymorphism is achieved when an object of a derived class is substituted where
an instance of its parent class is expected. This uses a process known as upcasting. With upcasting, the
object of the more specialised class is implicitly cast to the base class type required.
72. State the advantages and five (5) areas of application of object-oriented programming.
Advantages:
1. We can eliminate redundant code and extend the use of existing classes through inheritance.
2. We can build programs from the standard working modules that communicate with one another, rather
than having to start writing the code from scratch. This leads to saving of development time and higher
productivity.
3. The principle of data hiding helps the programmer to build secure programs that cannot be invaded by
code in other parts of the program.
4. It is possible to have multiple instances of an object to coexist without any interference.
5. It is possible to map objects in the problem domain to those in the program.
6. It is easy to partition the work in a, project based on objects.
7. The data-centered design approach enables us to capture more details of a model in implementable
form.
8 Object-oriented systems can be easily upgraded from small to large systems.
9. Message passing techniques for communication between objects makes the interface descriptions with
external systems much simpler.
10. Software complexity can be easily managed.
Application areas:
1. Real-time systems
2. Simulation and modeling
3. Object-oriented databases
4. Hypertext, hypermedia and expert text
5. AI and expert systems
6. Neural networks and Parallel programming Decision support and office automation systems
7. CIM/CAM/CAD systems
75. Enumerate two (2) conditions on which the specific setup instructions used for C# development variation
will depend on.
1. Whether your development workstation already meets some or all of the requirements.
2. Whether you plan to use the provided samples.
string Secondsemester;
Secondsemester = Textbox.Text;
84. Explain what each line of the corrected code you got in question 83 above does.
The first line sets up the variable, and tells C# to set aside some memory that will hold a string of text.
The name of this storage area will be Secondsemester.
The second line is the one that actually stores something in the variable - the Text from a text box called
TextBox.
85. In the code you got in question 83 above, add a line of code that will display the output in a message box.
MessageBox.Show(Secondsemester);
87. Briefly state the two (2) methods of adding classes in C# and their procedures.
Adding a C# Class Using Solution Explorer:
1. In Solution Explorer, right-click the project name and click Add, and then click Add Class.
The Add New Item dialog box appears with the C# Class icon already selected.
2. In the dialog box, enter a class name in the Name field and click Open. The new class is added to your
project.
Adding a C# Class Using Class View:
1. In Class View, right-click the project name and click Add
2. Then click Add Class
3. The C# Class Wizard appears
88. List at least five (5) folders that are created when one saves a work in C#.
1. Visual Studio 2005
2. Projects
3. ConsoleApplication1
4. bin
5. obj
89. What is the function of the double quotes and the semicolons in C#?
1. Double quotes: These tell C# that you want text.
2. Semicolons: All complete lines of code in C# must end with a semicolon. Miss one out and you'll get
error messages. Type the semicolon at the end and the red wiggly line will go away.
90. Cleary explain the term method in C# and write the syntax for creating one.
A method is a code block containing a series of statements. In C#, every executed instruction is done in
the context of a method.
Syntax:
attributes modifiers return-type method-name(parameters )
{
statements
}
92. Explain the term method overloading and state its advantages.
Method overloading is a technique which allows the programmer to define many methods with the same
name but with a different set of parameters.
Advantages:
1. It provides improvement to code readability and maintainability.
2. It allows you to always call Math.Truncate.
93. Briefly explain any four (4) common variables in C#; stating their syntax.
String: String variables are always text. Click inside the two curly brackets of the button code, and add
the following:
string firstName;
Integer Variables: As well as storing text in memory you can, of course, store numbers. There are a
number of ways to store numbers, and the ones you'll learn about now are called Integer, Double and
Float. First up, though, are Integer variables. For example:
int myInteger;
Double and Float Variables: Integers, as was mentioned, are whole numbers. They can't store the point
something, like .7, .42, and .007. If you need to store numbers that are not whole numbers, you need a
different type of variable. You can use the double type, or the float type. You set these types of variables
up in exactly the same way: instead of using the word int, you type double, or float. Like this:
float myFloat;
double myDouble;
(Float is short for "floating point", and just means a number with a point something on the end.) The
difference between the two is in the size of the numbers that they can hold. For float, you can have up to
7 digits in your number. For doubles, you can have up to 16 digits. Float is a 32-bit number and double is
a 64-bit number.
95. With the aid of a well-labelled diagram, describe the Common Language Runtime (CLR) execution process.
Beyond just executing code, parts of the execution process directly affect your application design and
how a program behaves at runtime. Many of these subjects are handled throughout this book, but this
section highlights specific additional items you should know about. From the time you or another process
selects a .NET application for execution, the CLR executes a special process to run your application, shown
in the figure below:
96. Explain the term C# indexer and write the syntax for declaring a two-dimensional/multidimensional
indexer.
A C# indexer is a member that enables an object to be indexed in the same way as an array, a one-
dimensional indexer accepts a single value between the square brackets.
{
get {}
set {}
}
98. Write a code that calls the finalizer of a base class object.
protected override void Finalize()
{
try
{
// Destructor code
}
finally
{
base.Finalize();
}
}
99. Explain the concept garbage collection, and state the key roles of garbage collector.
When objects are created they occupy some memory. As memory is a limited resource, it is important
that once the objects are no longer required, they are cleaned up and their memory is reclaimed. The
.NET framework uses a system of garbage collection to perform this activity automatically so that the
developer does not need to control this directly.
Role of the Garbage Collector:
1. The garbage collector periodically checks for objects in memory that are no longer in use and that are
referenced by no other objects.
2. It also detects groups of objects that reference each other but as a group have no other remaining
references. When detected, the objects' destructors are executed and the memory utilised is returned to
the pool of available memory.
106. With the aid of a simple code, explain the process of method calling.
Calling a method on an object is similar to accessing a field. After the object name; add a period, the
name of the method, and parentheses. Arguments are listed within the parentheses, and separated by
commas. The methods of the Motorcycle class can therefore be called like this:
Motorcycle moto = new Motorcycle();
moto.StartEngine();
moto.AddGas(15);
moto.Drive(5, 20);
107. With the aid of a diagram, discuss the concept of inheritance as related to the OOP.
Inheritance is a powerful object-oriented concept that permits the creation of hierarchical groups of
classes that share common functionality. Using inheritance, one class can be derived from another. The
derived class, also known as the child class or subclass, inherits functionality from the base class, also
known as the parent class or superclass. The subclass can add methods and properties or modify the
functionality that it has inherited to provide a more specialised version of the base class. Using
inheritance, classes become grouped together in a hierarchical tree structure. The more generalised
classes appear at the root of the hierarchy with the more specific classes appearing on the tree's
branches. This categorisation of classes into related types is why inheritance is sometimes referred to
as generalisation (or generalization). When using inheritance, all of the base class' methods, properties,
events, indexers, operators and some internal variables are all automatically provided to every subclass.
As this functionality is automatically available in the child class, there is no need to duplicate code. This
reduces maintenance problems, as changes need only to be made in one class, rather than throughout a
series of related classes.