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

STRUCTURED PROGRAMMING DICT MOD 1

TOPIC 1: INTRODUCTION TO STRUCTURED PROGRAMMING.


-Outline two advantages of Structured programming languages. (2 marks)
1. It is user friendly and easy to understand.
2. Similar to English vocabulary of words and symbols.
3. It is easier to learn.
4. They require less time to write.
5. They are easier to maintain.
6. These are mainly problem oriented rather than machine based.

-Outline two ways of checking the correctness of a program. (2 marks)

1. Prove that the correct output is produced if the program successfully completes.
2. Compiling and Executing.

-Distinguish between program and programming as used in software development. (2 marks)


A program (noun) is executable software that runs on a computer. It is similar to
a script, but is often much larger in size and does not require a scripting engine to run.
Instead, a program consists of compiled code that can run directly from the
computer's operating system.

Programming is the implementation of logic to facilitate specified computing operations


and functionality. It occurs in one or more languages, which differ by application,
domain and programming model.

-Differentiate between beta and alpha testing. (2 marks)

Alpha Testing Beta Testing

First phase of testing in Customer Validation Second phase of testing in Customer


Validation

Performed at developer's site - testing Performed in real environment, and hence


environment. Hence, the activities can be activities cannot be controlled
controlled

Only functionality, usability are tested. Functionality, Usability, Reliability, Security


Reliability and Security testing are not usually testing are all given equal importance to be
performed in-depth performed

White box and / or Black box testing Only Black box testing techniques are
techniques are involved involved

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 1 of 31


Alpha Testing Beta Testing

Build released for Alpha Testing is called Build released for Beta Testing is called
Alpha Release Beta Release

-Explain four types of program testing. (4 marks)


1) Alpha Testing
It is the most common type of testing used in the Software industry. The objective of this testing
is to identify all possible issues or defects before releasing it into the market or to the user. Alpha
testing is carried out at the end of the software development phase but before the Beta Testing.
Still, minor design changes may be made as a result of such testing. Alpha testing is conducted at
the developer’s site. In-house virtual user environment can be created for this type of testing.
2) Acceptance Testing
An acceptance test is performed by the client and verifies whether the end to end the flow of the
system is as per the business requirements or not and if it is as per the needs of the end user.
Client accepts the software only when all the features and functionalities work as expected. It is
the last phase of the testing, after which the software goes into production. This is also called as
User Acceptance Testing (UAT).
3) Ad-hoc Testing
The name itself suggests that this testing is performed on an ad-hoc basis i.e. with no reference to
test case and also without any plan or documentation in place for such type of testing. The
objective of this testing is to find the defects and break the application by executing any flow of
the application or any random functionality.
Ad-hoc testing is an informal way of finding defects and can be performed by anyone in the
project. It is difficult to identify defects without a test case but sometimes it is possible that
defects found during ad-hoc testing might not have been identified using existing test cases.

4) Beta Testing

Beta Testing is a formal type of software testing which is carried out by the customer. It is
performed in Real Environment before releasing the product to the market for the actual end
users. Beta testing is carried out to ensure that there are no major failures in the software or
product and it satisfies the business requirements from an end-user perspective. Beta testing is
successful when the customer accepts the software.

Differentiate between cohesion and coupling as used in programming. (2 marks)


Cohesion is the indication of the relationship within a module. Coupling is the indication of
the relationships between modules. Cohesion in software engineering is the degree to
which the elements of a certain module belong together. ...Coupling represents the degree
to which a single unit is independent from others.

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 2 of 31


-Differentiate between procedural and structured programming. (4 marks)
Procedural programming generally flows from one statement to the next, with
occasional jumps and loops handled with goto statements. As the amount of code and
complexity increases, the end result is code that is extremely difficult to read and
maintain, known as spaghetti code. Assembly language and the resultant machine code
are both examples of procedural languages.

Structured programming introduces looping structures (for, while, do..while) with


orderly breaks, and procedure calls which allow code to branch and return to the caller,
rather than simply jump to arbitrary code never to return. There is much less need for
goto statements which ultimately makes code that much easier to read and easier to
maintain.

-Explain three types of test data. (3 marks)


Normal Data Values
This is data that would normally be entered into the system.
The system should accept it, process it, and we can then check the results that are output to make
sure they are correct.
Extreme Data Values
Extreme values are still normal data. However, the values are chosen to be at the absolute limits
of the normal range. Extreme values are used in testing to make sure that all normal values will
be accepted and processed correctly.

Abnormal Data Values


This is data that should not normally be accepted by the system - the values are invalid. The
system should reject any abnormal values. Abnormal values are used in testing to make sure that
invalid data does not break the system.
State three structured programming languages other than C and Pascal. (3 marks)
-Cobol
-Basic
-Lisp

-Explain computer generation programming languages. (4 marks)


1. First Generation Languages
1.1. Refered to as machine languages. Consists of a set of commands, which are represented as a
series of 1s and 0s corresponding to the instruction set that is hard wired into the security of a
microprocessor.
2. Second Generation Languages

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 3 of 31


2.1. Known as assembly languages, classified as a low level language because it is machine specific
and each assembly command corrasponds on a 1 to 1 basis to a machine language instruction.
3. Third Generation Languages
3.1. High level languages that came about in the 1950's. Mostly used for business and scientific
applications, and were considered major improvements from the first two generation languages.
4. Fourth Generation Languages
4.1. Fourth generation languages are used to help eliminate many of the strict puncuation and
grammar rules which can complicate the third generation languages. They are also high level
languages.
5. Fifth Generation Languages
5.1. Programming language based around solving problems using constraints given to the program,
rather than using an algorithm written by a programmer.

-Outline a function for each of the following software as used in programming. (2 marks)
a) Editor; ii. Compiler
A source code editor is a text editor program designed specifically for editing source code of
computer programs. It may be a standalone application or it may be built into an integrated
development environment (IDE) or web browser.

A compiler is a special program that processes statements written in a particular


programming language and turns them into machine language or "code" that a computer's
processor uses. Typically, a programmer writes language statements in a language such as
Pascal or C one line at a time using an editor.

-Explain the role of each of the following header files in a C program. (2 marks)
i. Stdio.h; ii Math.h.
Stdio.h is the header file for standard input and output. This is useful for getting the input from
the user (Keyboard) and output result text to the monitor (screen). Without this header file, one
cannot display the results to the users on the screen or cannot input the values through the
keyboard.

The math.h header defines various mathematical functions and one macro. All the functions
available in this library take double as an argument and return double as the result. Let us
discuss some important functions one by one.

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 4 of 31


-Explain the term stepwise refinement as used in programming. (2 marks)
Modularity and stepwise refinement - is the decomposition of a complicated task into a group
of small independent subtasks. The technique of stepwise refinement helps to gradually
develop an algorithm or a program, in a sequence of steps.

TOPIC 2 : PROGRAM DEVELOPMENT AND DESIGN.


-Outline four qualities of a good algorithm. (2 marks)
The characteristics of a good algorithm are:
• Precision – the steps are precisely stated(defined).
• Uniqueness – results of each step are uniquely definedand only depend on the input
and the result of the precedingsteps.
• Finiteness – the algorithm stops after a finite number ofinstructions are executed.
• Input – the algorithm receives input.
• Output – the algorithm produces output.
• Generality – the algorithm applies to a set ofinputs.

-State two disadvantages of monolithic programming. (2 marks)


• Difficult to check errors on large programs.
• Code can be specific to a particular problem i.e. it cannot be re-used.

-Differentiate between flowchart and pseudo code as used in programming. (2 marks)


Pseudocode is so easy to convey your programming ideas without getting involved in
sticky syntax. You just simply write down your concept in plain speech and leave
someone else to implement it with a programming skill.

A flowchart can be incredibly difficult to interpret and only captures the direction of
your code, not the more difficult thought process.

-Describe two tools that could be used in program design. (2 marks)


Flowcharts are written with program flow from the top of a page to the bottom. Each
command is placed in a box of the appropriate shape, and arrows are used to direct
program flow.

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 5 of 31


Pseudocode is a method of describing computer algorithms using a combination of natural
language and programming language. It is essentially an intermittent step towards the
development of the actual code.

-Draw a flow chart for a C program that will print Odd numbers from 2 to 6. (4 marks)

-Define the term variable scope and explain the two types of variable scope. (4 Marks)
Scope refers to the visibility of variables. In other words, which parts of your
program can see or use it. Normally, every variable has a global scope. Once
defined, every part of your program can access a variable.
The scope of the local variable- the function where that var was defined. Any
code inside that function can access (read and change) this variable. Any
code outside it cannot. It's local, so it's invisible from outside. A variable is said to
have global scope if they can be used anywhere but within the same class in which
it is declared. An instance variables are the variables that have global scope.

-Explain two approaches to programming that are used to implement stepwise refinement.

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 6 of 31


(4 marks)
Top-down programming tends to generate modules that are based on functionality, usually in
the form of functions or procedures. Typically, the high-level specification of the system states
functionality. This high-level description is then refined to be a sequence or a loop of simpler
functions or procedures, that are then themselves refined.

In this style of programming, there is a great risk that implementation details of many data
structures have to be shared between modules, and thus globally exposed. This in turn makes it
tempting for other modules to use these implementation details, thereby creating unwanted
dependencies between different parts of the application.

Modular programming is the process of subdividing a computer program into separate sub-
programs.
A module is a separate software component. It can often be used in a variety of applications and
functions with other components of the system. Similar functions are grouped in the same unit
of programming code and separate functions are developed as separate units of code so that the
code can be reused by other applications.

-Outline three circumstances that would make a programmer to use a compiler during program
writing. (3 marks)

Compiling

Compiling is the process of transforming a high level language into a low level
language. A high level language is closer to English. A low level language is
closer to what the computer understands.

Compiling a C Program

1. Compiling is the transformation from Source Code (human readable) into


machine code (computer executable). A compiler is a program.
2. The compiler also ensures that your program is TYPE correct. For example,
you are not allowed to assign a string to an integer variable!
3. The compiler also ensures that your program is syntactically correct. For
example, "x * y" is valid, but "x @ y" is not.

-A program is required to prompt a user to enter two non-zero integers. The program then checks
and outputs the larger integer.
Write a pseudo code and draw the flowchart to represent the logic. (4 marks)
Start

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 7 of 31


input_one = input(“Number one: “)

input_two = input(“Number two: “)

if input_two >= input_one:


print(input_two + “ is the largest number”)

else:
print(input_one + “ is the largest number”)

Stop

Using a diagram, explain the two types of connectors as used in flow charts (2 marks)

On-page Pairs of labeled connectors replace long or confusing lines on a flowchart


Connector page. Represented by a small circle with a letter inside.

Off-page A labeled connector for use when the target is on another page.
Connector Represented as a home plate-shaped pentagon.

TOPIC 3 : PROGRAM STRUCTURE.


-Explain the use of each of the following Keywords in Pascal programs. (2 marks)
(i) Type – Used to define a record.
(ii) ( Input, Output) – Used to define the program header..

-Write operator order of precedence for evaluating mathematical expressions as used in Pascal
programming. (3 marks)

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 8 of 31


Operator Precedence

~, not, Highest

*, /, div, mod, and, &

|, !, +, -, or,

=, <>, <, <=, >, >=, in

or else, and then Lowest

-Assuming a C program language, evaluate the expression;

Z=a+b % c * (d^2)
Given that a=10, b=23, c =7 and d=5. (4 marks)
=10+23%7*(5*5)
=10+2*(25)
=10+50
=60

-Given that x is a variable in C program that stores a numeric value, distinguish between x++ and
++x as used in the program operations. (4 marks)
++x i.e. pre-increment operator uses the principle ‘change-then-use’ while, x++ i.e.
post-increment operator uses the principle ‘use-then-change’.

for example, the following code;


1. int a=10,b=15;
2. int product = a * b++;
3. printf(“%d”,product);
This will produce an output 150. Obviously, b is first used then changed.
1. int a=10,b=15;
2. int product = a * ++b;
3. printf(“%d”,product);

-Outline three reasons for declaring variables in a program. (3 marks)


1. To avoid getting unexpected results
2. Your code will run much faster and use less memory

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 9 of 31


3. It makes debugging far easier, because the Editor will then be able to “spot”errors it would
otherwise miss.

4 It makes debugging far easier in another way, because if you accidentally misspell a variable
. name somewhere, this will be picked up as an undeclared variable if you compile your project
(Debug menu).

-Outline three reasons for using comments in a program. (3 marks)


Commenting involves placing Human Readable Descriptions inside of computer
programs detailing what the Code is doing.
i. Proper use of commenting can make code maintenance much easier.
ii. Helping make finding bugs faster.
iii. Commenting is very important when writing functions that other people will use.

-Using the syntax, differentiate between float and int data types with examples in C. (4 marks)

Integers and floats are two different kinds of numerical data. An integer (more commonly
called an int) is a number without a decimal point. A float is a floating-point number, which
means it is a number that has a decimal place. Floats are used when more precision is needed.
int a = 0; // Create a variable "a" of the datatype "int"
float b = 0.0; // Create a variable "b" of the datatype "float "

-Describe five types of operators used in C programming language. (5 marks)

C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction and multiplication on numerical values (constants and variables).

Increment and decrement operators


C programming has two operators increment ++ and decrement -- to change the
value of an operand (constant or variable) by 1.

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 10 of 31


Increment ++ increases the value by 1 whereas decrement -- decreases the value
by 1. These two operators are unary operators, meaning they only operate on a
single operand.

C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =

C Relational Operators

A relational operator checks the relationship between two operands. If the


relation is true, it returns 1; if the relation is false, it returns value 0.

C Logical Operators

An expression containing logical operator returns either 0 or 1 depending upon


whether expression results true or false. Logical operators are commonly used
in decision making in C programming.

-List and explain 3 types of language translators. (3 marks)

Compiler Interpreter Assembler

Translates high-level
Temporarily executes high-level Translates low-level assembly
languages into machine
languages, one statement at a time code into machine code
code

An executable file of
No executable file of machine code is An executable file of machine
machine code is
produced (no object code) code is produced (object code)
produced (object code)

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 11 of 31


Compiled programs no
Interpreted programs cannot be used Assembled programs no longer
longer need the
without the interpreter need the assembler
compiler

Outline three uses of comments in a program. (3 marks)

Planning and reviewing


Comments can be used as a form of pseudocode to outline intention prior to writing the actual
code. In this case it should explain the logic behind the code rather than the code itself.

Code description
Comments can be used to summarize code or to explain the programmer's intent.
Algorithmic description
Sometimes source code contains a novel or noteworthy solution to a specific problem. In such
cases, comments may contain an explanation of the methodology. Such explanations may
include diagrams and formal mathematical proofs.

-Write operator order of precedence for evaluating mathematical expressions as used in C


programming. (3 marks)
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right

TOPIC 4 : PROGRAM WRITING.


-Write a program in Pascal programming language that computes the sum of even numbers
between 44 and 100 and output the results. Use for loop. (4 marks)
Program Rewards (I, O);{IF…THEN DEMO}

var i,sum: Integer;

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 12 of 31


Begin
sum := 0;
for i := 44 to 100 do
if (i mod 2 = 0 )then
begin
Writeln(i);
sum := sum + i;
end;
Writeln( 'The sum of even numbers between 40 -100 is ', sum);
writeln();
readln();
End.

-Write a Pascal program that would accept a positive integer. The program should then
determine the square and cube of the value and output the results. (6 marks)
Program PRODNUM;
Var
Num1, square, Prod : Integer;
Begin {no semicolon}
Writeln('Input number 1:');
Readln(Num1);
square := Num1 * Num1;
cube := Num1 * Num1 * Num1;
Writeln('The square of', Num1’, square);
Writeln('The square of', Num1’, cube);
Readln;
End.

-Write a C program that accepts the base and height of a right angled triangle and also computes
and outputs the area of the triangle. (5 marks)
1. /*
2. * C Program to Find Area of a Right Angled Triangle
3. */
4. #include <stdio.h>
5. int main()
6. {

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 13 of 31


7. float height, width;
8. float area;
9. printf("Enter height and width of the given triangle:\n ");
10. scanf("%f%f", &height, &width);
11. area = 0.5 * height * width;
12. printf("Area of right angled triangle is: %.3f\n", area);
13. return 0;
14. }

-Write a C program that prompt a user to enter three integers and displays the largest of them.
Make use of ternary operator. (5 marks)
#include <stdio.h>
main()
{
int a, b, c, big ;
printf("Enter three numbers :\n") ;
scanf("%d %d %d", &a, &b, &c) ;
big = (a < b) ? (a < c ? a : c) : (b < c ? b : c) ;
printf("\nThe smallest number is : %d\n", big) ;
system ("Pause");
return 0;
}

-Write a C code that determine and display the area the area of the trapezium.
Hint: Area of Trapezium = ½ (a+b)h (6 marks)
1. /*
2. * C Program to Find Area of Trapezium
3. */
4. #include <stdio.h>
5. int main()
6. {
7. float a, b, h;
8. float area;
9. printf("Enter the value for two bases & height of the trapezium: \n");
10. scanf("%f%f%f", &a, &b, &h);
11. area = 0.5 * (a + b) * h ;

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 14 of 31


12. printf("Area of the trapezium is: %.3f", area);
13. return 0;
14. }

- Write a C program to output the pattern below. (5 marks)


2
2 4
2 4 6
#include <stdio.h>
int main()
{
int i,j;
for(i=1;i<=3;++i)
{
for(j=1;j<=i;++j)
{
printf("%d ",j*2);
}
printf("\n");
}
system("pause");
return 0;
}

-Write a C program that would accept a positive integer. The program should then determine the
square of the number and display the number and its square. (5 marks)
/* C Program to Calculate Square of a Number */

#include<stdio.h>

int main()
{
int number, Square;

printf(" \n Please Enter any integer Value : ");


scanf("%d", &number);

Square = number * number;

printf("\n Square of a given number %d is = %d", number, Square);

return 0;

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 15 of 31


-Explain two techniques that may be used to prevent a program from unexpected termination and
outline two circumstances that may cause a runtime error in a program. (4 marks)
Abnormal Program Termination
Abnormal program termination refers to a runtime error where an unexpected or unusual fault
occurs and Windows must close the program. In most cases, a specific set of circumstances is the
cause of an abnormal termination. Analyzing what was happening at the time of the error is key
to diagnosing the root of the problem.

Solutions
Solutions to abnormal program terminations vary based on the source of the error. If a software
conflict is at fault, identifying the two pieces of software and avoiding running them
simultaneously is the best course of action. A good way to identify if a software or driver conflict
is at fault is to perform a clean boot, which will start your computer with minimal drivers and
auto-launching applications. Instructions for performing a clean boot are included in the
Resources section. If other resource errors are at fault, you may need to consult your company's
IT professional for a case-specific plan. If you suspect a software glitch, consider uninstalling the
software and performing a clean re-install. This may remedy issues with corrupted files and other
faults that have occurred over time. Software that is inherently defective will likely need to be
replaced with a comparable program.
Causes of run time error.

• division by zero
• performing an operation on incompatible types
• using an identifier which has not been defined
• accessing a list element, dictionary value or object attribute which doesn’t exist
• trying to access a file which doesn’t exist

-A newly constructed computer lab is 15metres long and 10 meters wide. The lab is to be fitted
with floor tiles. Write a program in C language that prompts a user to enter the length and width
of the lab. The program then computes the number of the tiles required. One tile has an Ares of
0.36M2. (6 marks)

#include<stdio.h>
#include<conio.h>

int main() {
int length, breadth, area,tiles;

printf("\nEnter the Length of Rectangle : ");


scanf("%d", &length);

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 16 of 31


printf("\nEnter the Breadth of Rectangle : ");
scanf("%d", &breadth);
area = length * breadth;
tiles=area/0.36;
printf("\nArea of Rectangle : %d", area);
printf("\n Tiles: %d", tiles);
return (0);
}

-Write a C program that prompt a user to enter three integers and displays the largest of them.
Make use of ternary operator. (5 marks)
# include <stdio.h>

void main()
{
int a, b, c, big ;
printf("Enter three numbers : ") ;
scanf("%d %d %d", &a, &b, &c) ;
big = a > b ? (a > c ? a : c) : (b > c ? b : c) ;
printf("\nThe biggest number is : %d", big) ;
}

-A newly established bank converts Kenya shillings to US dollar at the rate of 1US dollar=102
Kenya shillings. Write a program in C programming language that prompts a user to enter the
currency either Ksh or USD. The program then outputs the equivalent amount. Use functions.
(6 marks)
/*Program to demonstrate the working of user defined function*/
#include <stdio.h>
float CON1(int amount); //function prototype(declaration)
float CON2(int amount); //function prototype(declaration)
int main()
{
float pesa,answer;
char opt;
printf("Enters Character D or K\n");
scanf("%c",&opt);
if (opt == 'D')
{
printf("Enters Dollar to convert to Ksh=\n");
scanf("%f",&pesa);
answer=CON1(pesa);
printf("Answer After Convertion %.2f\n",answer);
}
else
{
printf("Enters Ksh to convert to Dollar=\n");
scanf("%f",&pesa);
answer=CON1(pesa);

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 17 of 31


printf("Answer After Convertion %.2f\n",answer);
}
system("pause");
return 0;
}
float CON1(int amount) //function declarator
{
/* Start of function definition. */
float ans;
ans=amount * 102;
return ans; //return statement of function
/* End of function definition. */
}
float CON2(int amount) //function declarator
{
/* Start of function definition. */
float ans;
ans=amount / 102;
return ans; //return statement of function
/* End of function definition. */
}
-The area A of a triangle is obtained using the formula A = √𝑆(𝑆 − 𝑎)(𝑆 − 𝑏)(𝑆 − 𝑐) where a, b
𝑎+𝑏+𝑐
and c are the dimensions of a triangle and S = . Write a Pascal program that would prompt
2

for the three dimensions of a triangle, computes the area and displays the results to the nearest 3
decimal places. (8 marks)
Program geo;
Var
a,b,c: Integer;
var s, ans:real;

Begin {no semicolon}


Writeln('Input number 1:');
Readln(a);
Writeln('Input number 2:');
Readln(b);
Writeln('Input number 2:');
Readln(c);
s := (a+b+c)/2;
answer:=sqrt(s*(s-a)*(s-b)*(s-c))
Writeln('Answer=’, answer);
Readln; End.

TOPIC 5 : CONTROL STRUCTURES


-Using syntax and flowchart explain Nested if statement in C programming. (4 marks)
A nested if is an if statement that is the target of another if statement. Nested if

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 18 of 31


statements means an if statement inside another if statement

Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

(a) In an athletics competition, athletes were awarded money based on the ranking as shown
below.
Rank Amount Allocated

1 1000000

2 500000

3 250000

Any Other 0
Write a C program that would accept the rank. The program should then determine the award
through the use of if statement
(6 marks)
#include <stdio.h>
int main()
{
int rank;
printf("Enter score\n:");
scanf("%d",&score);
if (score==1)
{
printf("Amount allocated is 1000000\n");
}
else if (score ==2)

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 19 of 31


{
printf("Amount allocated is 500000\n");
}
else if (score ==3)
{
printf("Amount allocated is 250000\n");
}

else
{
printf("Amount allocated is 0\n");
}
system("pause");
return 0;
}

-Using flow charts, explain the difference between repeat until and while-do loop structures.
(4 marks)
Difference between WHILE …DO & REPEAT…….UNTIL Loop Structure

WHILE …DO

1. The condition is tested before the body is executed.


2. It is possible that the body may never be executed.(this occurs if the condition is
true on the first test)
3. The loop is exited when the condition is false.

REPEAT…….UNTIL
1. The condition is tested after the body is executed.
2. The body is always executed at least once.
3. The loop is exited when the condition is true.

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 20 of 31


-The table below shows details of athletes rating based on nationality. Write a Pascal program
that would prompt a user to enter the country code. The program then outputs the corresponding
rating. Use if else if Statement.
(6 marks)
Country Code Rating

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 21 of 31


Kenya K or k Highly talented sportsmen

India I or i Sporting affected by their culture

United States U or u Good in short races

Nigeria N or n Give a good attempt in short races

All other Countries Any other General performance is low


/* Demonstrates the use of if statements */
#include <stdio.h>
main()
{
Char cou;
printf("\n Input character=");
scanf("%c", &cou);

if((cou == ‘K’)|| (cou == ‘K’))


printf("Highly talented sportsmen \n");

else if ((cou == ‘I’) || (cou == ‘i’))


printf("Sporting affected by their culture \n");
else if ((cou == ‘U’) || (cou == ‘u’))

printf("Good in short races \n");

else if ((cou == ‘N’) || (cou == ‘n’))


printf("Give a good attempt in short races\n");
else
printf("General performance is low \n");
system("pause");
return 0;
}

-Write a C program that will allow the user to specify the number of elements to enter in an array
then the program sorts the entered values in ascending order using a bubble sort algorithm.
(7 marks)

1. #include <stdio.h>
2. void main()
3. {
4. int i, j, a, n, number[30];
5. printf("Enter the value of N \n");
6. scanf("%d", &n);
7. printf("Enter the numbers \n");
8. for (i = 0; i < n; ++i)
9. scanf("%d", &number[i]);

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 22 of 31


10. for (i = 0; i < n; ++i)
11. {
12. for (j = i + 1; j < n; ++j)
13. {
14. if (number[i] > number[j])
15. {
16. a = number[i];
17. number[i] = number[j];
18. number[j] = a;
19. }
20. }
21. }printf("The numbers arranged in ascending order are given below
\n");
22. for (i = 0; i < n; ++i)
23. printf("%d\n", number[i]);
24. }

TOPIC 6: DATA STRUCTURES


-Write an algorithm that could be used to remove an element from a stack. (3 marks)
PROCEDURE DELETE(ITEM, STACK, TOP)
[Deletes ‘item’ from the ‘stack’, top is the number of elements currently in ‘stack’.]

1. [Underflow ?]
if (TOP <= 0)
write Stack is empty.
return.
2. [Deleting Element]
item <-- stack[top]
3. [Decrementing top]
top <-- top - 1
4. [FINISH]
return (top).

-Describe each of the following data structures as used in programming. (4 marks)


(i) Linked List (ii) Array
Linked lists are a way to store data with structures so that the programmer can automatically
create a new place to store data whenever necessary. Specifically, the programmer writes a
struct or class definition that contains variables holding information about something, and
then has a pointer to a struct of its type. Each of these individual struct or classes in the list is
commonly known as a node.

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of
the same type. An array is used to store a collection of data, but it is often more useful to

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 23 of 31


think of an array as a collection of variables of the same type.

-Outline three tree data structures traversals as used in programming. (3 marks)

Depth First Traversals:

(a) Inorder (Left, Root, Right) : 4 2 5 1 3


(b) Preorder (Root, Left, Right) : 1 2 4 5 3
(c) Postorder (Left, Right, Root) : 4 5 2 3 1
Breadth First or Level Order Traversal : 1 2 3 4 5

-Define quick sort as used in programming. (2 marks)


It picks an element as pivot and partitions the given array around the picked pivot. There are
many different versions of quickSort that pick pivot in different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.

-Using a trace table implement the logic below. (6 marks)


number = 3
PRINT number
FOR ( i=1;i<=3;i++):
{number = number + 5
PRINT number}
PRINT "?"

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 24 of 31


-Define the term efficiency as used in data structures. (2 marks)

Measuring Efficiency: The most obvious way to determine the efficiency of an algorithm, data
structure, or application is to write the necessary code and measure the running time and space
requirements.

-Write an algorithm using structured English that could be used to implement linear search in
Structured Programming. (3 marks)

• Step 1: Read the search element from the user


• Step 2: Compare, the search element with the first element in the list.
• Step 3: If both are matching, then display "Given element found!!!" and terminate the
function
• Step 4: If both are not matching, then compare search element with the next element in
the list.
• Step 5: Repeat steps 3 and 4 until the search element is compared with the last element in
the list.
• Step 6: If the last element in the list is also doesn't match, then display "Element not
found!!!" and terminate the function.

-Differentiate between level and degree as used in binary trees. (2 marks)

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 25 of 31


The degree of a node is the number of children it has. So every node of a B-tree has a degree
greater than or equal to zero and less than or equal to the order of the B-tree.
Height (of a tree): The length of the path from the root to the deepest node in the tree.

Level (of a node): The number of parent nodes corresponding to a given a node of the tree. For
example, the root, having no parent, is at level 0.

TOPIC 7: SUBPROGRAMS
-Explain two ways through which parameters can be passed to a function. (4 marks)

Parameter Passing

There are different ways in which parameter data can be passed into and out of methods and
functions. It is beyond the scope of these notes to describe all such schemes, so we will consider
only the two most common methods used in C++ and Java: "pass by value" and "pass by
reference".
First some important terminology:
Definition: Formal Parameter
A variable and its type as they appear in the prototype of the function or method.
Definition: Actual Parameter
The variable or expression corresponding to a formal parameter that appears in the function or
method call in the calling environment.

Pass by Value
Using "pass by value", the data associated with the actual parameter is copied into a separate
storage location assigned to the formal parameter. Any modifications to the formal parameter
variable inside the called function or method affect only this separate storage location and will
therefore not be reflected in the actual parameter in the calling environment. For example (this
could be either C++ or Java):
void cribellum(int x) // Formal parameter is "x" and is passed by value.
{
x = 27;
}
void someCaller()
{
int y = 33;
cribellum(y); // Actual parameter is "y"
// Actual parameter "y" still has 33 at this point.
...
}
Pass by Reference
Using "pass by reference", the formal parameter receives a reference (or pointer) to the actual
data in the calling environment, hence any changes to the formal parameter are reflected in the
actual parameter in the calling environment. Here is a modified version of this example (now
strictly a C++ example since Java does not allow primitive types to be passed by reference):
void cribellum(int& x) // Formal parameter "x" is now passed by reference.
{

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 26 of 31


x = 27;
}

void someCaller()
{
int y = 33;
cribellum(y);
// Actual parameter "y" now has 27 at this point.
...
}

-Outline three advantages of using functions in a program. (3 marks)

• Avoid repetition of codes.


• Increases program readability.
• Divide a complex problem into simpler ones.
• Reduces chances of error.
• Modifying a program becomes easier by using function.

Differentiate between iteration and recursion as used in programming. (4 marks)

Recursion and iteration both repeatedly executes the set of instructions. Recursion is when a

statement in a function calls itself repeatedly. The iteration is when a loop repeatedly executes

until the controlling condition becomes false. The primary difference between recursion and

iteration is that is a recursion is a process, always applied to a function. The iteration is applied
to the set of instructions which we want to get repeatedly executed.

-Explain two advantages of linked list data structure. (4 marks)

A linked list is a dynamic data structure and therefore the size of the linked list can grow or
shrink in size during execution of the program. A linked list does not require any extra space
therefore it does not waste extra memory. It provides flexibility in rearranging the items
efficiently.

The limitation of linked list is that it consumes extra space when compared to a array since each
node must also contain the address of the next item in the list to search for a single item in

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 27 of 31


-Write a C program that prompts you to specify the number of integers to enter in an Array. The
program then calculates the average of the entered integers and displays the results together with
all entered elements in reverse. (6 marks)
#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;

/* Array- declaration – length 4*/


int num[4];

/* We are using a for loop to traverse through the array


* while storing the entered values in the array
*/
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}

avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}

TOPIC 8 : FILE HANDLING.


-Explain ways in which records can be organized in a computer file. (3 marks)

1. Sequential file organization

• Records are stored and accessed in a particular order sorted using a key
field.
• Retrieval requires searching sequentially through the entire file record by
record to the end.
• Because the record in a file are sorted in a particular order, better file
searching methods like the binary search technique can be used to reduce
the time used for searching a file .

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 28 of 31


2. Random or direct file organization

• Records are stored randomly but accessed directly.


• To access a file stored randomly, a record key is used to determine where a
record is stored on the storage media.
• Magnetic and optical disks allow data to be stored and accessed randomly.

3. Serial file organization

• Records in a file are stored and accessed one after another.


• The records are not stored in any way on the storage medium this type of
organization is mainly used on magnetic tapes.

4. Indexed-sequential file organization method

Almost similar to sequential method only that, an index is used to enable the
computer to locate individual records on the storage media. For example, on
a magnetic drum, records are stored sequential on the tracks. However, each
record is assigned an index that can be used to access it directly.

-Differentiate between a, w and r as used in C programming. (3 marks)

Open for append. i.e, Data is


a If the file does not exists, it will be created.
added to end of file.

If the file exists, its contents are overwritten. If the file


w Open for writing.
does not exist, it will be created.

r Open for reading. If the file does not exist, fopen() returns NULL.

TOPIC 9 : PROGRAM DOCUMENTATION


-Describe two items that could be added to a user manual in order to assist in the access of
details and information. (4 marks)
A table of contents, usually headed simply Contents and abbreviated informally as TOC,
is a list, usually found on a page before the start of a written work, of its chapter or section

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 29 of 31


titles or brief descriptions with their commencing page numbers.
A glossary, also known as a vocabulary or clavis, is an alphabetical list of terms in a
particular domain of knowledge with the definitions for those terms. Traditionally,
aglossary appears at the end of a book and includes terms within that book that are either
newly introduced, uncommon, or specialized.

-Distinguish between technical and user documentation of a program. (2 marks)


Technical documents are usually written in more technical terms, can assume a higher
level of technical knowledge, and are more concerned with how things work behind the
scenes.

User documents should assume no technical or terminology knowledge (with some


exceptions) and are written to describe how you use things to achieve an end result.

-Describe two documents which could be created during program development. (2 marks)

Internal documentation is the one that talks in detail about how the code does whatever it
function is. It describes the data structures, algorithms, and control flow in the programs.

Internal documentation is usually formed by:

1. Name, type, and purpose of each variable and data structure used in the code
2. Brief description of algorithms, logic, and error-handling techniques
3. Information about the required input and expected output of the program
4. Assistance on how to test the software
5. Information on the upgrades and enhancements in the program.
External documentation, on the other hand, focuses on what the problem to be solved is, and
which approach is used in solving it. This can be a graph detailing the execution, a list of
algorithms, dependencies, as well as meta-data such as the author, the date,

TOPIC TEN (10) EMERGING TRENDS IN PROGRAMMING.


-Explain three ways of coping with new programming languages. (3 marks)

Harnessing Emergence and Embracing Nondeterminism

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 30 of 31


A programing model for multi-core systems that embraces nondeterminism and supports
emergence.

Consistency and Logical Monotonicity

The group of Hellerstein addresses the challenge of consistency and parallelism in distributed
systems by applying declarative/logic programming and monotonicity analyses.

Distributed Dataflow Programming

Declarative dataflow programming provides a concurrency model with inherent coordination,


entirely hidden from the developer. Massively parallel data-centric computing frameworks such
as MapReduce have shown the strong points of dataflow programming.

DICT MOD 1 STRUCTURED PROGRAMMING REVISION KIT Page 31 of 31

You might also like