0% found this document useful (0 votes)
20 views

C Model Questions

Uploaded by

lubangap
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

C Model Questions

Uploaded by

lubangap
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Question One

a) Define the following terms as used in Computer Programming


i) Programming Language (2 marks)
A Programming Language is a stylized communication technique intended to be used for controlling the behavior of a
machine (often a computer). Like human languages, programming languages have syntactic and semantic rules used to
define meaning. There are a number of Programming languages that have evolved since the 1960’s, some of these include
C, C++, Java, C#, Basic, etc.
ii) IDE (2 marks)
IDE is an acronym for Integrated Development Environment, also known as Integrated Design Environment and
Integrated Debugging Environment, which is a type of computer software that assists computer programmers to
develop software.

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.

d) What is a Software Bug in Computer Programming? Discuss the implications of a


Software Bugs? (4 marks)
A Software Bug is an error, flaw, mistake, failure, or fault in a computer program that prevents it from working as
intended, or produces an incorrect result. Bugs arise from mistakes and errors, made by people, in either a program's
source code or its design. A program that contains a large number of bugs, and/or bugs that seriously interfere with its
functionality, is said to be buggy. Reports about bugs in a program are referred to as bug reports, also called PRs
(problem reports), trouble reports, CRs (change requests), and so forth.

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

a) What is an object in C++? (2 marks)


In C++, an object is a region of storage with associated semantics. C++ provides objects (variables and constants) for
storing and manipulating data in a program. Memory is allocated to each object that is used in a program. Just as in
algebra, the values of an object may change in the program; such objects are referred to as variables while those objects
which cannot be modified in the program are known as constants. Each object used in a program must be declared, that is,
the program must contain a statement specifying precisely what kind of information (object/data type) the object will
contain and a unique name which the program will use to identify the object. The name given to an object is termed as its
identifier.
b) Give the rules and conventions that should be followed when defining object identifiers
in C++. (6 marks)
Object Naming Rules in C++
 A valid identifier is a sequence of one or more letters, digits or underscores (_). They should not include
embedded space or any symbols such as: ? !- + @ # % * ( ) [ ] { } . , ; : “ ‘ / < > ~ ` \.
 The length of an identifier is not limited, although for some compilers only the 32 first characters of an identifier
are significant (the rest are not considered).
 Object identifiers should always begin with a letter. They can also begin with an underscore character (_),
however identifiers starting with a double underscore (__) or beginning with an underscore and an uppercase
letter are reserved for use by C++ implementations and standard libraries so they should not be used. An object
identifier can never begin with a digit.
 The object identifier must be unique (C++ is case sensitive). The C++ language is "case sensitive", that means that
an identifier written in capital letters is not equivalent to another one with the same name but written in small
letters. Thus, for example the object customerName is not the same as the object customername or the variable
CustomerName.
 Another rule that must be considered when inventing identifiers is that they cannot match any key word of the
C++ language or the compiler's specific ones since they could be confused with these. A keyword is a word that
is reserved as part of the language having special meaning to the compiler.
 Additionally, alternative representations for some operators do not have to be used as identifiers since they are
reserved words under some circumstances: and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq
Object Naming Conventions in C++
 Object identifiers must be meaningful and short. The names must reflect the data that the object contains. For
example to store the age of an employee, the identifier can be employee_age.
 If the object identifier contains two or more words, join the words and begin each word with uppercase letter, or
separate each word with an underscore. E.g. EmployeeName or employee_name.
 Variable names are normally in lowercase letters.
c) How many Null bytes are at the end of the following string literal? (1 mark)
“What is going on here?\0”
There are Two(2) Null bytes, (Explaining why Earns a Bonus Mark)

© 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)

Control Passed to If Construct Control Passed to If-else Construct

Boolean_Condition False Boolean_Condition False


? ?

True True

Action Action 1 Action 2

Control Passed to the statements after If construct Control Passed to the statements after If-else
construct

b) A system of two (2) simultaneous equations can be generally represented as:

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]);

cout <<setprecision(3)<< “ X1 = “<<X[0]<<” and X2 = “<<X[1]<<endl;


}
else
cout << "\a\a\a System has no Unique Solution" << endl;
system(“PAUSE”);
return 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).

ii) Serial Files (1 mark)

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.

iii) Indexed Sequential Files (2 marks)

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.

iv) Random Access Files (2 marks)

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.

d) Consider the file Records.txt, containing the following Data:


Jonathon Smith 400.23
Peter Newton 340.19
Describe how the source code below accesses and displays the data. (7 marks)
#include <iostream>
#include <fstream>
using namespace std;
#define max 500
int main()
{
char record[max]={0};
ifstream fin("Records.txt", ios::in);
if (!fin)
{
cerr << "Unable to open the file Records.txt"<<endl;
return 1;
}
while (!fin.eof())
{
fin.getline(record, max);
cout << record << endl;
}
system(“PAUSE”);
return 0;
}
Question Five
a) How does passing parameters by value differ from by reference (2 marks)
Pass by Value: If parameters are passed by value, only a copy of the variable has been passed to the function. Any changes
to the value will not be reflected back to the calling function.

Pass by Reference: A function that uses call-by-reference arguments reflects any changes to the values of the arguments
to the calling function.

b) Give the Criteria for function recursion (2 marks)


When a function invokes itself, such an instantiation is termed as Recursion. Recursive functions or procedures should
satisfy the following criteria.

 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

in radians and return the associate cos x  


10
 1n x 2 n .
n  0 2 n !

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

g) Procedural programming is often a better choice than simple sequential or unstructured


programming in many situations which involve moderate complexity or which require
significant ease of maintainability. List three (3) possible benefits of Procedural
Programming. (3 marks)

 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").

 The ability to be strongly modular or structured.

~Good Luck~

© 2006

You might also like