C Model Questions
C Model Questions
IDEs normally consist of a source code editor, a compiler and/or interpreter, build-automation tools, and (usually) a
debugger. Sometimes a version control system and various tools to simplify the construction of a GUI are integrated as
well. Many modern IDEs also integrate a class browser, an object inspector, and a class hierarchy diagram, for use with
object oriented software development. Although some multiple-language IDEs are in use, such as the Eclipse IDE, NetBeans
or Microsoft Visual Studio, typically an IDE is devoted to a specific programming language, as in the Visual C++ IDE.
b) Distinguish between a Compiler, a Decompiler, and a Source to Source Translator.
(3 marks)
A Compiler is a computer program (or set of programs) that translates text written in a computer language (the source
language) into another computer language (the target language). The original sequence is usually called the source code
and the output called object code. Commonly the output has a form suitable for processing by other programs (e.g., a
linker), but it may be a human readable text file.
The most common reason for wanting to translate source code is to create an executable program. The name "compiler" is
primarily used for programs that translate source code from a high level language to a lower level language (e.g., assembly
language or machine language). A program that translates from a low level language to a higher level one is a decompiler. A
program that translates between high-level languages is usually called a language translator, source to source translator,
or language converter.
A compiler is likely to perform many or all of the following operations: lexing, preprocessing, parsing, semantic analysis,
code optimizations, and code generation.
c) Using appropriate illustrations distinguish between Procedural and Object Oriented
Programming. (6 marks)
Procedural Programming is sometimes used as a synonym for imperative programming, but can also refer to a
programming paradigm based upon the concept of the procedure call. Procedures, also known as routines, subroutines,
methods, or functions (not to be confused with mathematical functions, but similar to those used in functional
programming) simply contain a series of computational steps to be carried out. Any given procedure might be called at any
point during a program's execution, including by other procedures or itself.
Procedural programming. The main
program coordinates calls to procedures
and hands over appropriate data as
parameters.
© 2006
Object-Oriented Programming, OOP for short, is a computer programming paradigm. The idea behind object-oriented
programming is that a computer program may be seen as comprising a collection of individual units, or objects, that act on
each other, as opposed to a traditional view in which a program may be seen as a collection of functions, or simply as a list
of instructions to the computer. Each object is capable of receiving messages, processing data, and sending messages to
other objects. Each object can be viewed as an independent little machine or actor with a distinct role or responsibility.
Object-oriented programming. Objects of the program interact by
sending messages to each other.
Bugs can have a wide variety of effects, with varying levels of inconvenience to the user of the program. Some bugs have
only a subtle effect on the program's functionality, and may thus lie undetected for a long time. More serious bugs may
cause the program to crash or freeze. Other bugs lead to security problems; for example, a common type of bug which
allows a buffer overflow may allow a malicious user to execute other programs that are normally not allowed to run.
The results of bugs may be extremely serious. A bug in the code controlling the Therac-25 radiation therapy machine was
directly responsible for patient deaths and in 1996, the European Space Agency's US$1 billion prototype Ariane 5 rocket was
destroyed less than a minute after launch, due to a bug in the on-board guidance computer program. Also, in June 1994 a
Royal Air Force Chinook crashed into the Mull of Kintyre, killing 29. This was initially dismissed as pilot error, but an
investigation by Computer Weekly uncovered evidence sufficient to convince a House of Lords enquiry that it may have been
caused by a Software Bug in the aircraft's FADEC.
e) What are the uses of Source Code in a programming Project? (3 marks)
Source code is either used to produce object code, or to be run by an interpreter. Modifications are not carried out on
object code, but on source code, and then converted again.
Source code has a number of other uses. It can be used for the description of software. It can also be used as a tool of
learning; beginning programmers often find it helpful to review existing source code to learn about programming
techniques and methodology. It is used as a communication tool between experienced programmers, due to its (ideally)
concise and unambiguous nature. The sharing of source code between developers is frequently cited as a contributing
factor to the maturation of their programming skills.
© 2006
Source code is a vital component in the activity of porting software to alternative computer platforms. Without the source
code for a particular piece of software, portability is generally so difficult as to be impractical and even impossible. Binary
translation can be used to run a program without source code, but not to maintain it. Decompilation can be used to
generate source code where none exists, and with some manual effort, maintainable source code can be produced.
Programmers frequently borrow source code from one piece of software to use in other projects, a concept which is
known as Software Reusability.
Question Two
© 2006
d) Explain why the following code snippet is illegal in C++. (2 marks)
int x = 5;
int y;
int z;
(z = y) = x;
Line 1 is legal and conventional, Line 2 and 3 are legal but Unconventional; the objects have not been initialized at definition.
Line 4 is Illegal because the left operand of the assignment operator cannot be an expression; this will result into a
compiler error.
e) For the following expressions give the final values of objects a and b. The objects of
interest are:
int a (5);
int b (10);
i) a = b++ + ++b; (2 marks)
b = b + 1; // b = 11
a = b + b; // a = 22
b = b + 1; // b = 12
Therefore, a = 22, and b = 12
ii) ++a++; (2 marks)
This statement is illegal; it results into a compiler error. The unary operators cannot be used as pre and post
unary modifiers on the same operand.
iii) a = 2 + (b += a)++; (2 marks)
b = b + a; // b = 15
a = 2 + b; //a = 17
b = b + 1; //b = 16
Therefore, a = 17, and b = 16
f) Give a single statement that is equivalent to:
i) a = b; (1 mark)
b = b + 1;
Solution: a = b++;
ii) a = a - 2; (2 mark)
a = a + 1;
b = a;
Solution: b = ++ (a -= 2);
Question Three
© 2006
a) Using flow charts, illustrate the difference between the basic if and the extended if-else
selective execution constructs. (4 marks)
True True
Control Passed to the statements after If construct Control Passed to the statements after If-else
construct
a11 x1 a12 x 2 b1
a21 x1 a22 x2 b2
If the parameter aij and bi are provided, we can solve for x 1 b1 a 22 b 2 a 12 and
a 11 a 22 a 12 a 21
b 2 a11 b1 a 21
x2 provided a11 a22 a12 a 21 0 .
a 11 a 22 a 12 a 21
Using arrays and control constructs design an algorithm that extracts the coefficient
a a12 b
matrix A 11 and vector B 1 from the default input console, computes and
a 21 a 22 b2
x
displays the vector X 1 provided a11 a22 a12 a 21 0 and error message otherwise.
x2
© 2006
i) Draw the flow chart (6 marks)
Start
Start
Extract
Extract Matrix
Matrix AA
Is
Is False
aa11aa22 aa12 aa21 00
11 22 12 21
??
Yes
bb11 aa 22 b a 12
22 b 22 a12
xx1 Print Error Message
1 a a a aa 21
a11
11 a 2222 a1212 21
bb11aa 21
bb2 aa22 21
xx 22
2 11
aa11 a 22
11 a 22 aa12 a 21
12 a 21
Print x1 and x 2
Stop
© 2006
ii) Write the program source code following all the ISO/ANSI C++ Standards
and conventions. (10 marks)
/*Program Extract constant parameters in 2 simultaneous equations,
computes and diplays values of the variables if a unique solution
exists*/
//Author: Paul Isaac Musasizi
//Date: Tuesday, October 28, 2008
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double A[2][2] = {0}; // Coefficient Matrix
double B[2] = {0}; // requirements Matrix
double X[2] = {0}; // Matrix of unknowns
for (int i=0; i<2; i++)
for (int j =0; j<2; j++)
{
cout <<” Enter A[“<<i<<”][“<<j<<”] :”;
cin >> A[i][j];
}
if (A[0][0]*A[1][1]-A[0][1]*A[1][0]!=0)
{
for (int i=0; i<2;i++)
{
cout <<”Enter B[“<<i<<”] :”;
cin >> B[i];
}
X[0]= (B[0]*A[1][1]-B[1]*A[0][1])/ (A[0][0]*A[1][1]-A[0][1]*A[1][0]);
X[1]= (B[1]*A[0][0]-B[0]*A[1][0])/ (A[0][0]*A[1][1]-A[0][1]*A[1][0]);
Question Four
a) Distinguish between an array and a structure (2 marks)
An array has the limitation that it can store data of only one object type. A structure object is a collection of variables of
similar or dissimilar types. A structure is a user defined object type while an Array could of a fundamental of User defined
type.
b) Discuss the two-step process for the creation of a Structure (4 marks)
1. Create a structure prototype (model). This informs the compiler about the different types of data that can be
stored in the structure objects. No memory is allocated at this point, since objects have not yet been created. The
syntax for a structure prototype has the following general form:
struct Prototype_Name
{
type1 Identifeir1;
type2 Identifier2;
type3 Identifier3;
.
};
© 2006
2. Definition of structure object(s). Memory is allocated after an object has been defined. The structure object can
be defined and initialized at the time of creating the structure prototype or later The syntax for instantiating a
structure object is of the form: Prototype_Name Object_Identifier;
c) Write short notes about:
i) Sequential Files (2 marks)
This is the most primitive type of file commonly used in a data processing environment. We may think of the items
stored on this type of file as being listed in a suitable order for example alphabetical order of name or numerical
order of reference number). The data within this type of file may be retrieved by reading the items in the order in
which they are stored. So to retrieve the one thousandth entry in the file will involve reading through nine
hundred and ninety nine which are not required. This makes sequential files unsuited to the storage of data items
which are likely to be required singly on demand. However, sequential files are well suited to applications which
involve the processing of each entry in the file (each record) in turn (such as a payroll programs).
Sometimes, data items are stored one after another in unsorted order. This type of file is described as a Serial
File. Data which is collected and stored gradually through the day (for example a list of library book taken out)
would typically be collected and stored serially (since we obviously can not insist that borrowers take books in
any particular order). Unsorted serial files are then sorted into ordered sequential files for their main
processing.
Indexed Sequential files are stored rather like sequential files, in the same sense that data items are stored in a
particular order. The principal difference is that some record is kept of whereabouts certain data items are in the
file, and it is possible ton start searching from any of the records in the index. The larger the index, the smaller
the number of records which will need to be searched before finding the one desired.
Within an indexed sequential file system there is a trade-off between a system which uses a very large index and
therefore needs a lot of memory, but allows almost direct access to many elements in the file, as against a
smaller index which means that more records will be accessed on average before the one required is located, and
therefore access is slower.
The theory behind the random or direct access file is that any record within the file may be accessed directly,
without accessing any other record first, and the time taken to locate each record will be the same. Random
access is quite complicate and more expensive to implement than either of the previous file access methods, but
it can be justified in situations where very quick access is required to single data items within the file. Interactive
© 2006
programs are the sort which typically require random access files; mail order companies make heavy use of this
type of program at their tele-sales desk.
Pass by Reference: A function that uses call-by-reference arguments reflects any changes to the values of the arguments
to the calling function.
There must be a base value (base criteria) for which the function recursion will be terminated.
Every instance of recursion must modify the arguments passed to the function effectively to reach the base
criterion
n
c) 0
Write a program that extracts 0 x 360 computes and 0
displays cos x
1 2 n
10
x
n 0 2 n !
© 2006
rounded off to 3 significant figures. The program should include implementation of the
following Programmer Defined Functions:
factorial: this function should be of return type long. It should accept an
unsigned short integer and return its factorial.
radians: this functions should be of return type double. It should accept an angle
in degrees, and return its equivalent in radians. The function should be executed
inline.
cosine: this function should be of return type double. It should accept an angle x
All functions should be defined as Local functions and default values assigned to their
arguments. (16 marks)
//Program computes the cosine of an angle between 0 and 360
//Author: Paul Isaac Musasizi
//Date: 12- May -2006
#include "iostream"
#include "iomanip"
#include "cmath"
using namespace std;
inline double Radians(double &A) { return ((A/180)*acos(-1.0));}
int main()
{
double cosine (double Rad = 0.0);
double Angle=0; //Angle btn 0 and 180in degrees
cout<<"Enter the angle whose cosine you want to find : ";
cin >> Angle;
if(Angle>=0 && Angle <=360)
{
if(Angle>180)
Angle-=360;
cout << "cos" <<Angle<<'='<<setiosflags(ios::showpoint)<<setprecision(3)
<<cosine(Radians(Angle))<< endl;
}
else
cerr<<"\a\aAngle entered is not valid"<<endl;
system("PAUSE");
return 0;
}
double cosine (double Rad)
{
long factorial (unsigned short n = 0 );
double cosine=0;
if (fabs(Rad) != acos(-1.0)/2)
for(int m=0; m<=10 ; m+=2)
cosine+=(pow((-1.0),(m/2))*pow(Rad, m))/factorial(m);
return cosine;
}
long factorial (unsigned short n )
{
if (n == 0)
return 1;
else
return (n*factorial (n-1));
}
© 2006
Question Six
a) What are the contents of a Library Header File? (3 marks)
A Library Header File normally contains a related collection of function and operator prototypes, global constants and
variable object definitions, and class descriptions. The collection is essentially an interface descrip tion for using the
associated software library.
b) Distinguish between a Standard Library and a Personal Library. (2 marks)
If a Library is a standard one, then linking is automatically done by the compiler. If a library is a personal one, then
compiling commands are given to specify where definitions can be found. The linking of personal files can be automated
through use of make or project tools associated with the compiler.
c) Explain what happens at a function call (2 marks)
When a function is invoked, flow of control is transferred from the invoking function to the invoked function. When the
invoked function completes executing successfully, control is transferred back to the invoking function. If the invoked
function returns a value, then that value is essentially substituted for the invocation.
d) Discuss the terms below as applied to C++ Programming:
i) Function Prototype (2 marks)
A Function Prototype in C++ is a declaration of a function that omits the function body but does specify the
function's name, argument types and return type. While a function definition specifies what a function does, a
function prototype can be thought of as specifying its interface i.e. the return type, function name and form of the
parameter list.
ii) Function Overloading (2 marks)
Overloading allows multiple functions taking different types to be defined with the same name; the compiler or
interpreter automatically calls the right one. This way, functions appending lists of integers, lists of strings, lists
of real numbers, and so on could be written, and all be called append—and the right append function would be
called based on the type of lists being appended.
e) The C++ I/O libraries provide an interface between the program and the hardware
devices that make up the computer system. There are two major libraries for I/O
operations; iostream and cstdio libraries. Discuss the distinguishing characteristics of
the iostream library from the cstdio library. (3 marks)
An important characteristic of the iostream library is its extensibility. This characteristic is not true of the other major
alternative library, the cstdio library. The stdio library is the library C programmers use to do I/O. While there are
functions to input and output the standard types and strings, there are no methods for extending or redefining these
functions to operate on programmer-defined data types. For this reason, it is recommended that the iostream library be
used for handling all input and output in C++.
f) The preprocessor is responsible for processing three kinds of commands in a program
file. List them. (3 marks)
File Inclusion Directives specifying the files that are to be part of the translation unit that is to be compiled
Macro Definitions and Invocations, which enable parameterized textual substitution
© 2006
Conditional Compilation Directives which allow a programmer to restrict which lines of code are compiled
The ability to re-use the same code at different places in the program without copying it.
An easier way to keep track of program flow than a collection of "GOTO" statements (which can turn a large,
complicated program into so-called "spaghetti code").
~Good Luck~
© 2006