CSC 332 Past Questions and Marking Scheme
CSC 332 Past Questions and Marking Scheme
UNIVERSITY OF IBADAN
B.Sc. Degree Examinations (First Semester, 2015/2016)
(b) Using Python and C# / Java example code snippets, explain how
(i) Textual data can be converted to string arrays [1 mark each = 2]
(ii) Group of data can be read from a database into an array [1 mark each = 2]
Q2: (a) Using the concepts of Orthogonality and Portability, explain the programming-
friendliness of the following languages:
(i) Java
(ii) C#
(iii) Python
(iv) C
(v) Javascript [2 marks each = 10]
(b) Discuss the functional characteristics of all the stakeholders involved in programming
languages’ evolution. [3 marks]
(c) Keywords and reserved words have posed serious challenges to language designers
(i) Differentiate between keywords and reserved words [2 marks]
(ii) What are the challenges posed by these concepts. Discuss
how language designers overcame these problems [5 marks]
Q3. Consider the following code snippet in a programming language.
if (a > b)
if (a < c)
a++;
else
k = a – b + c;
(a) What is the syntactic ambiguity associated with the above code snippet? [3 marks]
(b) What happens on the values of k if the else part of the code is attached
to the innermost and the outermost if-statements? [5 marks]
(c) Illustrate your solutions with syntax trees. [6 marks]
(d) Explain how C, Java and FORTRAN solve this problem. [6 marks]
(b) Assuming you are interested in designing a programming language, identify all the
different lexical categories you will need in the design. [5 marks]
(c) Design a comprehensive BNF grammar for the lexical categories identified in (b)
above. [8 marks]
(d) State any two likely limitations of the BNF grammar designed in (c) above.
[4 marks]
CSC 332 2015/2016 MARKING SCHEME
Q1.
(a) One characteristic and one examples of
(i) Imperative Languages: Von Neuman compliance, command driven, data and program stored in memory,
“how to do it” principle, eg. C, Pascal, Java, FORTRAN
(ii) OOP Languages: OOP means Object Oriented Programming based on objects and classes, data
encapsulation, inheritance, etc e.g. Java, C#, C++, Python, PHP, etc
(iii) POP: POP means Procedure Oriented Programming based on procedures and functions, command
driven, etc, eg. FORTRAN, COBOL, PASCAL, etc
(iv) Scripting Languages such as Javascript, HTML, PHP, etc., are loosely typed, used for web programming,
usually embedded into HTML
(v) Typeless Languages such as Python, PHP, Javascript etc, are loosely typed, no need of explicitly
declaring or binding variables with specific data types. [1 mark each = 5]
(b) (i) Inheritance is a characteristic of OOP languages in which a class (sub or child class) acquires some or all
properties of another class [1 mark]
(ii) Single Inheritance – Java, Multiple inheritance – C++ or C# [2 marks]
(i) Rationale for using inheritance – Code reusability, efficient programs, etc [2 marks]
(c) (i) To convert textual data into string arrays, we use the split functions in both Java and Python
For example, stringArray [ ] = textData.split(“”); [2 marks]
(ii) To read group of data from database into arrays in Java and Python, we use the SQL SELECT statement
to read the data and then assign the data into an array (candidates to show codes) [2 marks]
(d) (i) Reasons for using functions – program modularity, code reusability, ease of debugging, etc [2 marks]
(ii) Python:
def average (x, y):
if x%2 != 0 || y%2 != 0 :
sum = x + y
mean = sum/2
print mean
else:
print(“numbers are not odd” [2 marks]
Java:
Static double mean(int x, int y) {
if ((x%2 != 0) || (y%2 != 0)){
int sum = x + y;
double mean = (double) sum/2;
System.out.print (“mean = “ + mean);
} else
System.out.print (“numbers are not odd”); [2 marks]
(iii) Returning functions would return a value to the calling program/function on completion, void functions
would not return any value while a recursive functions keeps on calling itself until a base case is reached
[3 marks]
(iv) Functions are nested when a function is being put (nested) inside another function. PASCAL, MODULA
are examples of languages that support nesting of functions [2 marks]
(v) PASCAL, MODULA, etc are examples of languages that support nesting of functions [1 mark]
(e) Data coercion is the conversion of data types from one type to the other. Implicit data coercion occurs when we
have mixture of variables of various types in an expression and all of them converted to a single type by the
language. For example in Java, if x, y and z are all int while k is double in the expression, x + y + z + k; then the
whole expression becomes double. Explicit data coercion occurs when programmers explicitly type cast an
expression into another type, for example, double double mean = (double) sum/2; [4 marks]
Q2 (a)
Orthogonality: The term specifies if a symbol or reserved word always carry the same meaning regardless of the context
in which it is used or if a language contain a small number of basic features that interact in a predictable fashion no matter
how they are combined in a program. It occurs when a name is bound to a type when the program is written and that
binding cannot change when running the program.
[1 mark for this explanation]
(i) Java supports method and operator overloading and so, its orthogonality is small.
(ii) C# supports operator overloading, so it has small orthogonality
(iii) Python is typeless or loosely typed, and so, it has no orthogonality
(iv) C is highly orthogonal since symbols or reserved words always remain the same
(v) Javascript is typeless or loosely typed, and so, it has no orthogonality
[1 mark each = 5]
Portability: A portable language is one which is implemented on a variety of computers. Its design is relatively machine
independent. Languages that are standardized by America National Institute (ANS) and well-defined tend to be more
portable than others. [1 mark for this explanation]
(b) Functional characteristics of all the stakeholders involved in programming languages’ evolution.
(i) A programmer could be a person using programming languages to develop applications or someone who writes
a compiler
(i) A language designer designs a language – its vocabulary and other pragmatics
(ii) A language implementer is a person or group which develops a compiler or interpreter for a language on a
particular machine
The different stakeholders must understand the needs and constraints that govern the other two activities. A good language
designer must must be a good programmer. In many cases, the designer of a language is also its primary implementer, who
must have unusual programming and software engineering skills.
[3 marks]
(c)
(i) Keywords are like reserved words but can still be used as users’ variables in a program; whereas, reserved words
are excluded by fiat from the class of identifiers that a program can define for its own use. All keywords are
reserved words but not all reserved words are keywords. [2 marks]
(ii) The challenges posed by keywords and reserved words is how language designers treat them as delimiters and
how to separate and define them. Also programmers too may want to use them as variables and this could create
a confusion for the compiler during compilation. [2 marks]
How language designers overcame these problems (a) prescribe in the language definition that all such tokens
are reserved words. This simplifies lexical analysis but a long reserved word list encumbers the programmer.
(b) Designate such tokens as keywords by requiring that they be explicitly flagged in the program text by
special delimiters or typing conventions. This approach frees some words like BEGIN, VAR, END as
programmer’s variable names and keeps the lexical analysis simple but makes program preparation more tedious
and difficult to a reader. (c) Allo these tokens to be used as identifiers in the program and place the burden of
distinguishing between the two uses of an identifier on the context in which it appears in the program.
Programmers using this method deserve whatever consequence they get, moreover, a significant burden is placed
on the compiler to support such “freedom of expression” [3 marks]
Q3. (a) The syntactic ambiguity associated with the code snippet is the dangling else problem. The else
part is dangling between the outer and inner if statements. [3 marks]
(b) If the parse attaches the else part to the outer if statement, then the expression k = a - b + c will
be evaluated when the condition (a > b) is not true. But if it is attached to the inner if, it will be
evaluated when the condition (a < c) is not true. [5 marks]
(c) Two different parse trees are drawn for the same block of statements. [3 marks per diagram = 6]
if stmt if stmt
(d) C attaches the else clause to the first (outer) if stmt, FORTRAN enforces END IF at the end of all IF statements
while Java solves the problem by enforcing that all IF statements must have an explicit else clause.
[2 each = 6 marks]
Q4. (a) BNF – Backus Naur Form is a metalanguage notation for defining the syntax or grammar of
programming languages. It has a start symbol S, production (re-writing) rules P, set of terminals T and
set of non-terminals N. BNF = (N, T, P, S). [3 marks]
Literals 🡪 digits
Digit 🡪 0 | 1 | …. | 9
Separators 🡪 ; | , | { | }
(d) BNF does not guarantee that a variable has been declared and initialized with a value [4 marks]
DEPARTMENT OF COMPUTER SCIENCE
UNIVERSITY OF IBADAN
B.Sc. Degree Examinations (First Semester, 2016/2017)
a) Identify errors, the type of errors, corrective action to be taken on the errors and the line
numbers where they occur in the snippet above, using the following table format [8
marks]
c) Write C / C++ codes that will achieve the goals of lines 11 and 15 in the code snippet [6
marks]
e) What effect would line 4 have on the outputs of the snippet? [3 marks]
f) Assume the first row of array A has the following data items: 2, 3, 4.3, and 7. An error tagged
“NumberFormatException” may occur in Java. What is the implication of this error and on
which line will it occur if the data items were inputted into the snippet? State the reason for
your answer. [3 marks]
g) When we attempt to print out the value of j at line 10, would there be any problem? If yes,
suggest what might lead to the problem. [3 marks]
h) ‘+=’ is used in lines 5 and 6 of the snippet above.
(i) What type of operator is +=? [1 mark]
(ii) Give any 4 programming languages that permit the use of the += in their
grammar. [2 marks]
(iii) What is the semantic constraint on the use of += in these languages? [2 marks]
Q2. (a) Some programming languages are platform independent while some are strongly typed.
Explain with examples, the emphasized terms [2 marks]
(b) Give two features which make a program structured. [2 marks]
(c) Explain with sample code snippets how data coercion occurs in Java [2 marks]
(d) Give two reasons why methods or functions are needed in programs [2
marks]
(e) The mean deviation (MD) of some numbers is given as
Σ(|x – mean|)
n
Write a C / C++ program involving methods/class to compute the MD,
where |x| is the magnitude of x. [7 marks]
Q3. Discuss the general features of the following programming language categories with examples:
a. Algorithmic Languages
b. Object-Oriented Languages
c. Declarative Languages
d. Scripting Languages
e. Document Formatting Languages [3 marks each = 15]
Q4. (a) The .NET Framework was designed to make life easier for programmers.
(i) To what extent is the above statement true? [2 marks]
(ii) Explain the common features that can be used by programmers
of all .NET languages. [6 marks]
(a) What are programming languages’ lexicons? List all the lexicons
with examples. [7 marks]
CSC 332 (2016/2017) Marking Scheme
Q1. Consider the following code snippet written to manipulate a two-dimensional n by m array A:
1. float Total = 0; int i = 0;
2. while ( i <= n) {
3. int sum = 0;
4. while ( j < m); {
5. sum += A[i][j];
6. Total += A[i][j];
7 j++;
8. } // next j
9. i++;
10. System.out.println(“The value of j = ” + j);
11. //Statements for computing and printing the mean of each row follows
12.
13. }//next i
14.
15. //Statements for computing and printing overall mean follows
(a) Identify errors, the type of errors, corrective action to be taken on the errors and the line numbers where they
occur in the snippet above, using the following table format [8 marks]
(b) “IndexOutOfBoundException” is usually reported by Java. Explain the meaning of this exception and which line
of the code snippet is the exception likely to occur? [3 marks]
(c) Write C / C++ codes that will achieve the goals of lines 11 and 15 in the code snippet [6 marks]
(e) What effect would line 4 have on the outputs of the snippet? [3 marks]
(f) Assume the first row of array A has the following data items: 2, 3, 4.3, and 7. An error tagged
“NumberFormatException” may occur in Java. What is the implication of this error and on which line will it
occur if the data items were inputted into the snippet? State the reason for your answer. [3
marks]
(g) When we attempt to print out the value of j at line 10, would there be any problem? If yes,
suggest what might lead to the problem. [3 marks]
(i) Re-write the corrected code snippet in Python programming Language. [7 marks]
Q1 Solution
(a) Errors in the program snippet
Line Number Errors committed Type of error Corrective action
of errors committed
Line 2 Index out of bound exception, the i <= n, Semantic error The i <= n in the for loop
in the for loop is going beyond the length should be written as i < n
of the array
Line 4 & others Variables i, j, m, n were not declared Semantic error Declare i, j, m, n appropriately
Line 4 Semi colon after the for-loop Logic error Remove the semicolon after the
for loop
Lines 5 and 6 Array A was not declared Semantic error Declare array A before the first
for-loop
[½ mark each for line number, errors committed, type of error and corrective action for each error = 8 marks]
(b) IndexOutOfBoundExcepption means an error committed when a program tries to access a data beyond the limit of an
array. Since java arrays are zero index based, the indexing of an array starts at zero and ends at n-1, where n = the length of
the array. The error would occur on line 2 [3 marks]
(d) Purpose of Line 1: To declare an accumulator for the overall total or summations of all the data in array A
Purpose of Line 3: To declare an accumulator for summing data per row of the array A. [1 mark each = 2]
(e) The effect of line 4: The while control will loop indefinitely if j is actually less than m [3 marks]
(f) NumberFormatException error is like Type mismatch error in some other languages. It is an error that results when the
data value read is not in the right type the variable is declared with. The error will be thrown on line 5. Sum is declared as
int in line 5, but on reading the 3rd data (4.3), which is float, an error will occur. [3 marks]
(g) Yes, there will be problem if we attempt to print j at line 10 provided it is declared inside the loop. This is because j is
declared inside a loop block and therefore, it has a local scope within the loop where it is declared. [3 marks]
Q2 Solution
(a) Platform independence means that codes from a programming language can be executed on different hardware
or operating system (OS) platforms. Example is Java [1 marks]
Strongly typed means that variables must be explicitly declared and associated with types in the languages. Usually
they are also case sensitive. E.g. Java, C++, C, etc. [1 marks]
(b) Major features of a structured program – Method/functions usage, appropriate and adequate comments and white
spaces to introduce different sections of the program, proper indentations within code blocks, etc
[2 marks]
(c) Data coercion is automatic conversion of data types from one form to another. In Java, automatic coercion occurs
when there is a mixture of data types in an expression. Example, when an arithmetic expression contains double,
float, int and long data type variables, all the variables are automatically converted to double. Forced or artificial
coercion can occur by type casting method. For example if an integer expression is to be converted to double, we
write
Double y = (double) integer expression; [2 marks]
(d) Reasons for methods/functions in programs – code reusability, ease of bugs’ isolation and debugging, ease of
program maintenance, etc (Explanations are needed) [2 marks for two
explained points]
return (sum/n);
}
int main( ) {
int n;
printf(“Enter the length of the array”);
scanf(“%d”, &n);
Q3. Discuss the general features of the following programming language categories with examples:
a. Algorithmic Languages
b. Object-Oriented Languages
c. Declarative Languages
d. Scripting Languages
e. Document Formatting Languages [3 marks each = 15]
Q3 solution
(a) Algorithmic Languages are designed to express mathematical or symbolic computations. They can express algebraic
operations in notation similar to mathematics and allow the use of subprograms that package commonly used
operations for reuse. They were the first high-level languages. Examples are FORTRAN, ALGOL, LISP and C.
(b) Object-oriented languages help to manage complexity in large programs. Objects package data and the operations on
them so that only the operations are publicly accessible and internal details of the data structures are hidden. This
information hiding made large-scale programming easier by allowing a programmer to think about each part of the
program in isolation. In addition, objects may be derived from more general ones, “inheriting” their capabilities.
Such an object hierarchy made it possible to define specialized objects without repeating all that is in the more
general ones.
Object-oriented programming began with the Simula language (1967), which added information hiding to ALGOL.
Another influential object-oriented language was Smalltalk (1980), in which a program was a set of objects that
interacted by sending messages to one another. Other examples are C++, ADA, JAVA and VISUAL BASIC
(d) Declarative Languages also called nonprocedural or very high level, are programming languages in which (ideally)
a program specifies what is to be done rather than how to do it. In such languages there is less difference between the
specification of a program and its implementation than in the procedural languages described so far. The two
common kinds of declarative languages are logic and functional languages.
(d) Scripting Languages are sometimes called little languages. They are intended to solve relatively small programming
problems that do not require the overhead of data declarations and other features needed to make large programs
manageable. Scripting languages are used for writing operating system utilities, for special-purpose file-manipulation
programs, and, because they are easy to learn, sometimes for considerably larger programs.PERL (Practical
Extraction and Report Language) was developed in the late 1980s, originally for use with the UNIX operating system
(e) Document Formatting Languages specify the organization of printed text and graphics. They fall into several
classes: text formatting notation that can serve the same functions as a word processing program, page description
languages that are interpreted by a printing device and, most generally, markup languages that describe the intended
function of portions of a document. Examples: TeX, POSTSCRIPT and SGML
[3 marks each = 15]
Q4. (a) The .NET Framework was designed to make life easier for programmers.
(i) To what extent is the above statement true? [2 marks]
(ii) Explain the common features that can be use by programmers
of all .NET languages. [6 marks]
(l) What are programming languages’ lexicons? List all the lexicons
with examples. [7 marks]
Q 4 Solution
(a) (i) The .NET framework was designed to make life simpler for programmers by providing a common platform that can
be used when writing programs in several different programming languages (C# and Visual Basic among others)
[2 marks]
(ii) The .NET platform provides common features that can be used by programmers of all .NET languages. These include
:-
a. a Common Language Runtime (CLR) engine that allows all .NET programs to run and use common features
based on a Common Language Specification (CLS). The CLR also shields the programmer from having to deal
with issues that are specific to individual operating systems.
b. a comprehensive class library providing a wealth of in built functionality (GUI, File I/I, Database, Threading,
Serialization, Security, Web applications, Networking etc)
c. a Common Intermediate Language (CIL). All .NET source code is compiled into a common intermediate
language this provides the ability to integrate code written in any .NET language making use of common
exception handling facilities. [2
marks each = 6]
Q4 (b) The lexicon of a programming language is the set of all grammatical categories that defines strings of nonblank
characters, called tokens, from which programs are written. The lexicons or tokens in a programming language are
🕚
CSC 332 (SURVEY OF PROGRAMMING LANGUAGES)
Q1. (a) Re-write the following Java Code in Python Programming Language:
float sum = 0;
for (int i = 1; i <= 5; i++) {
System.out.println(“Enter data “ + i);
float d = input.nextFloat( );
if (d%5 == 0)
break;
else
sum += d;
} // next i
System.out.println(“Total sum = “ + sum); [5 marks]
(b) Explain with example codes, the following types of for loops using any familiar language
(i) Up-counting for loop
(ii) Down-counting for loop
(iii) Nested for loop
(iv) Infinite for loop [2 marks each = 8]
(d) Write a Python code to compute the sum and mean of any two numbers [4 marks]
(e) Using C# or C++, write a program to compute the mean of elements inserted
into a linear array of size n. [5 marks]
Q2 Using suitable example programming languages, explain the following design qualities of
programming languages.
(a) Pedagogy
(b) Orthogonalilty
(c) Portability
(d) Expressivity
(e) Reliability [4 marks each = 20]
Pg. 1 of 2
Q3. Consider the following code snippet in a C-like language.
if (x > y)
if (x < z)
x++;
else
m = x + z – y;
(e) Identify the syntactic ambiguity associated with the above code snippet. [3 marks]
(f) Explain the effects of associating the else part of the code to the
innermost and the outermost if-statements on the values of m. [5 marks]
(g) Illustrate your solutions with syntax trees. [6 marks]
(h) Explain how C, ALGOL and FORTRAN solve this problem. [6 marks]
class test {
int a = 6;
float j;
public static void main (String[ ] args) {
a) Using the above program snippet, explain the concepts of local and
global variable scope. [4 marks]
b) Using the above program snippet, explain how parameters are passed by
values and / or references [4 marks]
c) How is ‘a’ passed into the method/function add? [2
mark]
d) How is ‘demo’ passed into the method/function add? [2
mark]
e) How can we pass an array by value into a method/function? [2
marks]
f) What happens to the values of the variables passed by value and
reference after the execution of the method/function? [3 marks]
g) Using the above program snippet, explain how local scope can mask
a global scope in a program. [3 marks]
Pg. 2 of 2
(e) Using C# or C++, write a program to compute the mean of elements inserted
into a linear array of size n. [5 marks]
Solution
(a) Re-writing the following Java Code in Python Language:
Java Code Python Code
float sum = 0; sum = 0
for (int i = 1; i <= 5; i++) { for i in range (1,6,1):
System.out.println(“Enter data “ + i); d = float(input(“Enter data “ i)
float d = input.nextFloat( );
if (d%5 == 0) if (d%5 == 0):
break; break
else else:
sum += d; sum += d
} // next I
System.out.println(“Total sum = “ + sum); print (“Total sum = “ sum) [5 marks]
(b) The code structure must contain the following for-loop syntax
(i) Up-counting for loop: for(int i = 1; i <= n; i++)
(ii) Down-counting for loop: for(int i = n; i >= 1; i--)
(iii) Nested for loop: for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
(iv) Infinite for loop: for( ; ; ) [2 marks each with explanations= 8]
● a Common Language Runtime (CLR) engine that allows all .NET programs to run and use common
features based on a Common Language Specification (CLS). The CLR also shields the programmer
from having to deal with issues that are specific to individual operating systems.
● a comprehensive class library providing a wealth of in built functionality (GUI, File I/I, Database,
Threading, Serialization, Security, Web applications, Networking etc)
● a Common Intermediate Language (CIL). All .NET source code is compiled into a common
intermediate language this provides the ability to integrate code written in any .NET language making
use of common exception handling facilities.
(ii) Logic programming: Logic programming languages, of which PROLOG (programming in logic) is
the best known, state a program as a set of logical relations (e.g., a grandparent is the parent of a parent
of someone). Such languages are similar to the SQL database language. A program is executed by an
“inference engine” that answers a query by searching these relations systematically to make inferences
that will answer a query.
(d) #Python code to compute sum and mean of any two numbers
# Data Input
num1 = float(input("Enter the first number "))
num2 = float(input("Enter the Second number "))
# Data Processing
sum = num1 + num2
mean = sum/2
#Printing results
print("Sum of the two numbers = " , sum)
print("Mean of the two numbers = %.3f" %mean) [5 marks]
Q2 Using suitable example programming languages, explain the following design qualities of
programming languages.
(a) Pedagogy
(b) Orthogonalilty
(c) Portability
(d) Expressivity
(e) Reliability [4 marks each = 20]
Solution
(a) By pedagogy, we mean easier to teach and to learn; they have better textbooks, they are implemented in
a better programming environment: widely known, and used by the best programmers in an application
area. BASIC and Pascal were designed especially as pedagogical tools.
(b) Orthogonality: The term specifies if a symbol or reserved word always carry the same meaning regardless of the
context in which it is used or if a language contain a small number of basic features that interact in a predictable
fashion no matter how they are combined in a program. It occurs when a name is bound to a type when the
program is written and that binding cannot change when running the program.
(vi) Java supports method and operator overloading and so, its orthogonality is small.
(vii) C# supports operator overloading, so it has small orthogonality
(viii) Python is typeless or loosely typed, and so, it has no orthogonality
(c) Portability: A portable language is one which is implemented on a variety of computers. Its design is
relatively machine independent. Languages that are standardized by America National Institute (ANS)
and well-defined tend to be more portable than others. For example FORTRAN> BASIC has different
dialects, which programmers must familiarize themselves with when programming in the language.
Java is portable and platform independent.
(d) Expressivity: ability of a language to clearly reflect the meaning intended by the algorithm designer
(the programmer). An expressive language permits an utterance to be compactly stated and encouraged
the value of statement forms associated with structured programming. Finally, an expressive language is
one whose symbols are uniformly used; the meaning of a symbol should not vary unreasonably from
one instance in a program to another.
(e) Reliability of Programs: Does programs behave the same way every time they are run with input data
or when they are run on different platforms. To achieve this in a language, it must be incorporated
appropriate exception handling mechanism into the language that resist aliasing and memory leaks,
support strong typing, have well-defined syntax and semantic and support programs verification and
validation have the reliability edge [4 marks each = 20]
if (x > y)
if (x < z)
x++;
else
m = x + z – y;
(i) Identify the syntactic ambiguity associated with the above code snippet. [3 marks]
(j) Explain the effects of associating the else part of the code to the
innermost and the outermost if-statements on the values of m. [5 marks]
(k) Illustrate your solutions with syntax trees. [6 marks]
(l) Explain how C, ALGOL and FORTRAN solve this problem. [6 marks]
Solution
(a) The syntactic ambiguity associated with the code snippet is the dangling else problem. The else
part is dangling between the outer and inner if statements. [3 marks]
(b) If the parse attaches the else part to the outer if statement, then the expression m = x + z - y will
be evaluated when the condition (x > y) is not true. But if it is attached to the inner if, it will be
evaluated when the condition (x < z) is not true. [5 marks]
(c) Two different parse trees are drawn for the same block of statements. [3 marks per diagram = 6]
if stmt if stmt
(d) C attaches the else clause to the first (outer) if stmt, FORTRAN enforces END IF at the end of all IF statements
while Java solves the problem by enforcing that all IF statements must have an explicit else clause. Algol
demands that no two if statements should follow each other. [2 each = 6
marks]
Q4. Consider the following program snippet:
class test {
int a = 6;
float j;
public static void main (String[ ] args) {
a) Using the above program snippet, explain the concepts of local and global variable
scope.
[4 marks]
b) Using the above program snippet, explain how parameters are passed by
values and / or references [4 marks]
c) How is ‘a’ passed into the method/function add? [2
mark]
d) How is ‘demo’ passed into the method/function add? [2
mark]
e) How can we pass an array by value into a method/function? [2
marks]
f) What happens to the values of the variables passed by value and
reference after the execution of the method/function? [3 marks]
g) Using the above program snippet, explain how local scope can mask
a global scope in a program. [3 marks]
Solution:
(a) Local variable scope means that the declared variable is only accessible within a function or
block of code. Variables j declared inside the function sum in the code given has a local scope.
Whereas a global variable is accessible any where in the program; including a function or
block. Variables a, array and j have global scope in the code given. [4 marks]
(b) A parameter is passed by value when the actual value of a variable is passed into a function as
parameter. a is passed by value into the function sum. A parameter is passed by reference when
the address of a variable is passed as parameter into a function. array is passed by reference
into the function sum in the code given. [4
marks]
(c) a is passed by value into the function sum. [2 marks]
(d) array is passed by reference into the function sum [2 marks]
(e) An array can be passed by value into a function if a particular location is passed, e.g. passing
array[5] into a function is by value. [2 marks]
(f) The original value of a variable passed by value remains unchanged while the one passed by
reference assumes the new value after the execution of the function. [3 marks]
(g) A local scope can mask a global scope when a global variable is re-declared in a function or
block. For instance, j declared in the function sum has masked the one declared up as global
variable in the code segment given. [3 marks]