BIT1102 Introduction to Programming and Algorithms
BIT1102 Introduction to Programming and Algorithms
1
BIT1102 : INTRODUCTION TO PROGRAMMING AND ALGORITHMS
Pre-requieste:
concepts
Course Content;
of programming languages.
linear search, bubble sort Problem solving strategies; top down, bottom up
programming constructs
2
TABLE OF CONTENTS Page
Introduction ................................................................................................................................ 6
1.1 Program............................................................................................................................ 7
1.6.1Keywords.......................................................................................................................13
3
2.4 Constants ............................................................................................................................45
4.6 Flowchart.......................................................................................................................78
4
6.1 Introduction .................................................................................................................108
5
Introduction
The basic aim of this module is to teach programming and algorithm using C language
in a simpler way. As I write this module I have put in consideration the beginners and
This module do not need prior knowledge in programming though basic computer skills
You will explore the world of C from the basic concepts to other facets of the language.
Explanations, examples, exercises and tip notes are used. The guide uses an easy – to
learn approach. You will find the guide comprehensive, concise and practical – oriented.
To help grasp the concepts of the language, a number of real - life situation examples
You will find revision questions at the end of every chapter so that you can test your
Finally, the model examination papers at the end of the guide shall test your
I wish you all the best and I hope you will enjoy it!
6
CHAPTER ONE: PROGRAMMING BASIC IN C LANGUAGE.
Chapter Objectives
1.1 Program
task. These instructions are like commands and they are written by a computer
1.2 Programmer
This is a qualified personnel or a specialist who writes computer programs, and mostly
7
These programs are then translated into machine code (in binary) by a compiler.
Generally, the program is a simple text file (written using a word processor or a text
The source file contains lines of program called source code. Once the source file has
The compiler transforms the source code into object code, and saves it in an
object file, i.e. it translates the source file into machine code (some compilers
The compiler then makes a call to a link editor (or linker or binder) which enables
the program into the final file but which are not stored in the source file.
Then an executable file is created which contains all items required for the
program to run on its own (in Microsoft Windows or MS-DOS this file will have
8
1.4 Steps in Program Development
In this level the all the ideas are formulated and the expected output drafted. At this
stage, the programmer should think in general terms, not in terms of some specific
computer language.
Design program
The programmer decides how the program will go about its implementation, what
should the user interface be like, how should the program be organized, how to
represent the data and what methods to use during processing. It may be possible to
It is the design Implementation by writing the (C) code i.e. translating your program
design into C language instructions. In this stage the programmer uses C’s text editor or
any other editor such as notepad to write the source code and the source file should
have .c extension.
A compiler converts the source code into object code. Object code is instructions in
incorporate code for C libraries into the final program that is an executable file that the
9
The compiler also checks errors in your program and reports the error to you for
correction. The object code can never be produced if the source code contains syntax
errors.
This is the actual execution of the final code, usually preceded by linking. Once the
This involves checking whether the system does what it was intended to do. Programs
may have bugs (errors). Debugging involves the finding and fixing of program mistakes.
Occasionally, changes become necessary to make to a given program. You may think
of a better way to do something in a program, a clever feature or you may want to adapt
the program to run in a different machine. These tasks are simplified greatly if you
document the program clearly and follow good program design practices.
PASCAL and FORTRAN developed for some specific uses. C is designed to work with
both software and hardware. C has in fact been used to develop a variety of software
such as:
10
Application packages: WordPerfect and Dbase.
When you write a program in C language, your instructions form the source code (or
simply source file). C filenames have an extension .c. The part of the name before the
period is called the base name and the part after the period is called the extension.
The linker combines the intermediate code library routines and other code
You can compile individual modules, and then combine the compiled modules later.
Therefore, if you need to alter one module, you don’t have to recompile the others.
Linking is the process where the object code, the start up code, and the code for library
routines used in the program (all in machine language) are combined into a single file -
11
It allows programmers to break down their programs into functions. Further it supports
Efficiency
C is a concise language that allows you to say what you mean in a few words.
Portability
C programs written for one system can be run with little or no modification on other
systems.
It has (and still is) been used to solve problems in areas such as physics
and engineering.
Programmer orientation
memory.
It also has a rich selection of operators that allow you to expand programming
capability.
12
1.6 C Programs’ Components
1.6.1Keywords
These are reserved words that have special meaning in a language. The compiler
recognizes a keyword as part of the language’s built – in syntax and therefore it cannot
be used for any other purpose such as a variable or a function name. C keywords must
Examples of keywords
Preprocessor directives
Functions
13
Declaration statements
Comments
Expressions
#include<stdio.h>
main()
return 0;
Every C program contains a function called main. This is the start point of the program.
#include<stdio.h> allows the program to interact with the screen, keyboard and file
system of your computer. It is always found at the beginning of almost every C program.
main() declares the start of the function, while the two curly brackets show the start and
finish of the function mostly the body of the function.. Curly brackets in C are used to
14
printf("C program is a simple language \n"); prints the words on the screen. The text to
be printed is enclosed in double quotes. The \n at the end of the text tells the program to
Most C programs are in lower case letters. C is case sensitive, that is, it recognizes a
lower case letter and it's upper case equivalent as being different.
#include<stdio.h>
main()
return 0;
15
All C statements must end with a semicolon. C does not recognize the end of a line as a
terminator. This means that there are no constraints on the position of statements within
a line.
All C programs consist of one or more functions, each of which contains one or more
Although a C program may contain several functions, the only function that it must have
is main().
The main() function is the point at which execution of your program begins. That is,
when your program begins running, it starts executing the statements inside the main( )
function, beginning with the first statement after the opening curly brace. Execution of
which your program may use. This collection of functions is called the C standard
library. The standard library contains functions to perform disk I/O (input / output), string
manipulations, mathematics, and much more. When the program is compiled, the code
16
One of the most common library functions is called printf() which is found in the “stdio.h”
header file in the c library. This is C’s general purpose output function. Its simplest form
is
printf(“string – to – output”);
The printf() prints out any character that are contained between the beginning and
The double quotes are not displayed on the screen. In C, one or more characters
enclosed between double quotes is called a string. The quoted string between printf( )’s
To call a function, you specify its name followed by a parenthesized list of arguments
that you will be passing to it. If the function does not require any arguments, no
arguments will be specified, and the parenthesized list will be empty. If there is more
Then, the use of return (0); all the that have a return type must have a return statement,
Note:
17
(i) Since the main function does not return any value, line 3 can alternatively be
written as: void main () – void means valueless. In this case, the statement
(ii) While omitting the keyword int to imply the return type of the main() function
does not disqualify the fact that an integer is returned (since int is default),
actually compiled. Preprocessor directives are not actually part of the C language, but
file and include it within your program. This is generally used to read in header files for
library functions.
Header files contain details of functions and types used within the library. They must be
included before the program can make use of the library functions.
Library header file names are enclosed in angle brackets,<>. These tell the
preprocessor to look for the header file in the standard location for library definitions.
Comments
18
Comments are non – executable program statements meant to enhance program
readability and allow easier program maintenance, i.e. they document the
programThere two types of comments i.e. single-line and multiple line comments.
Single –line: are basically for one line and we use // followed by the comment.
While multiple or block comments uses /*comments*/ and everything between the
Declaration statements
In C, all variables must be declared before they are used. Variable declarations ensure
that appropriate memory space is reserved for the variables, depending on the data
An assignment statement uses the assignment operator “=” to give a variable on the
operator’s left side the value to the operator’s right or the result of the expression on the
Escape sequences are character combinations that begin with a backslash symbol (\)
One of the most important escape sequences is \n, which is often referred to as the new
line character. When the C compiler encounters \n, it translates it into a carriage return.
19
For example, this program:
#include<stdio.h>
main()
return 0;
#include<stdio.h>
main()
printf(“\a”);
return 0;
20
Remember that the escape sequences are character constants. Therefore to assign
one to a character variable, you must enclose the escape sequence within single
char ch;
\a alert/bell
\b backspace
\n new line
\v vertical tab
\t horizontal tab
\\ back slash
\0 null
21
1.6.6 Errors in Programming
There are three types of errors: Syntax, Semantic and Logic errors.
Syntax errors
They result from the incorrect use of the rules of programming. The compiler detects
such errors as soon as you start compiling. A program that has syntax errors can
produce no results.
Illegal declaration.
Logic Errors
These occur from the incorrect use of control structures, incorrect calculation, or
Semantic errors
They are caused by illegal expressions that the computer cannot make meaning of.
Usually no results will come out of them and the programmer will find it difficult to debug
22
such errors. Examples include a data overflow caused by an attempt to assign a value
to a field or memory space smaller than the value requires, division by zero, etc.
Languages that computers use to communicate with each other, have nothing to do with
processor action.
The language used by the processor is called machine code. The code that reaches the
Machine code is therefore difficult for humans to understand, that’s why intermediary
languages, which can be understood by humans, have been developed. The code
23
written in this type of language is transformed into machine code so that the processor
The assembler was the first programming language ever used. This is very similar to
so similar to machine code that it strictly depends on the type of processor used (each
processor type may have its own machine code). Thus a program developed for one
A programming language is a code that can make programs which is use to make
software. Programming languages have some built in function which is based on the
protocols.
a) Low Level
b) High Level
The languages which use only primitive operations of the computer are known as low
language. In these languages, programs are written by means of the memory and
registers available on the computer. As to note, the architecture of computer differs from
24
one machine to another, so far each type of computer there is a separate low level
programming language.
Programs written in one low level language of one, architectural can’t be ported on any
other machine dependent languages. Examples are Machine Language and Assembly
Language.
Machine Language
In machine language program, the computation is based on binary numbers. All the
instructions including operations, registers, data and memory locations are given in
The machine directly understands this language by virtue of its circuitry design so these
programs are directly executable on the computer without any translations. This makes
the program execution very fast. Machine languages are also known as first generation
languages.
25
Specifies location of the data on which operation is to be performed.
Advantages
a) Efficient use of computer system resources like storage, registers, etc. the
need of translators.
b) Can be used to manipulate the individual bits in a computer system with high
Drawbacks
a) Machine languages are machine dependent and, therefore, programs are not
productivity.
Arithmetic Logic Unit and computer storage locations must be addressed directly,
not symbolically.
costs.
e) Programs written in machine language are more error prone and difficult to
26
f) Program size is comparatively very big due to non-use of reusable codes and
Assembly Language
Assembly language are also known as second generation languages. These languages
substitutes alphabetic or numeric symbols for the binary codes of machine language.
There is the use of mnemonics for all opcodes, registers and for the memory locations
which provide us with a facility to write reusable code in the form of macros.
These language require a translator known as “Assembler” for translating the program
Advantages
a) Provide optimal use of computer resources like registers and memory because of
need to remember or calculate the binary equivalents for opcode and registers.
27
Drawbacks
a) Assembly language programs are not directly executable due to the need of
translation.
b) Languages are machine dependent and, therefore, not portable from one
machine to another.
All high level language are procedure-oriented language and are intended to be
That is, the high level languages use natural language like structures.
The early high level language come in third generation of languages, COBOL, BASIC,
APL, etc.
These languages enable the programmer to write instruction using English words and
familiar mathematical symbols which makes it easier than technical details of the
28
Procedures are the reusable code which can be called at any point of the program.
task. The procedure can be called by its name with the list of required parameters which
c) Execution time is very high as the HLL programs are not directly executable.
it allows greater portability, i.e. can be easily adapted to run on different types of
computers.
29
Imperative and functional programming languages
Programming languages are generally divided into two major groups according to how
imperative languages;
Functional languages.
An imperative language programs uses a series of commands, grouped into blocks and
commands if the condition is met. These were the first programming languages in use,
Structured imperative languages suffer, however, from lack of flexibility due to the
sequentiality of instructions.
which creates programs using functions, returning to a new output state and receiving
an input result of other functions. When a function invokes or call itself, it is referred
recursion.
30
Interpretation and compilation
interpreted languages
compiled languages
Interpreted language
be translated so that the processor can understand the code. A program written in an
interpreted language requires an extra program (the interpreter) which translates the
Compiled language
a compiler which in turn creates a new stand-alone file which does not require any other
additional program to run it once it has been compiled. Furthermore, as the translation
31
modification of the source file (the file understandable by humans: the file to be
compiled) means that the program must be recompiled for the changes to take effect.
On the other hand, a compiled program has the advantage of guaranteeing the security
of the source code. In effect, interpreted language, being a directly legible language,
means that anyone can find out the secrets of a program and thus copy or even
Intermediary languages
Some languages belong to both categories (LISP, Java, Python...) as the program
phase, into a file written in a language different to the source file and non-executable
(requiring an interpreter). Java applets, small programs, often loaded in web pages, are
compiled files, which can only be executed from within a web browser (these are files
32
b) Generality: Most high-level languages allow the writing of a wide variety of
programs, thus relieving the programmer of the need to become expert in many
diverse languages.
2. From the following program, suggest the syntax and logical errors that may have
been made.
The program is supposed to find the square and cube of 5, then output 5, its square
and cube.
#include<stdio.h>
main()
33
{
n = 5;
n2 = n *n
n3 = n2 * n2;
return 0;
(ii) Keyword
(iv) Comment
(v) Linking
practice. Why?
34
9. Name and explain four characteristics of a programming language.
Chapter Objectives
2.1 Variables
A variable is a memory location whose value can change during program execution. In
C, a variable must be declared before it can be used. Variables can be declared at the
A declaration begins with the type, followed by the name of one or more variables. For
example,
Declarations can be spread out, allowing space for an explanatory comment. Variables
can also be initialised when they are declared. This is done by adding an equals sign
35
Variable Names
Every variable has a name and a value. The name identifies the variable and the value
stores data. There are rules or conventions that needs to followed when writing a
varaible.
These include:
Every variable name in C must start with a letter; the rest of the name can consist
C language is case sensitive hence lower and upper case letters are treated
differently i.e int sum ,int Sum ,int SUM are all different to the compiler,
You cannot use any of C's keywords like main, while, switch etc as variable
names.
White spaces should not exist or be contained in the words or names that
makeup the variable. Instead you should use underscore to join the words of just
The variable name should not contain special characters like %,$,&,* ete, except
the underscore(_)
t ,num3 ,tyyah1,sum,name,solution,match_score
36
2.2 Basic Data Types
C supports five basic data types.Don’t be confused by void. This is a special purpose
point numbers
int
It is a type specifier used to declare integer variables. For example, to declare num as
int num;
char
A variable of type char is 1 byte long and is mostly used to hold a single character. For
37
char name;
flloat
It is a type specifier used to declare floating-point variables. These are numbers that
have a whole number part and a fractional or decimal part for example 1632.90. To
float mynum;
double
It is a type specifier used to declare double-precision floating point variables. These are
variables that store float point numbers with a precision twice the size of a normal float
double s;
Use printf ( ) to display values of characters, integers and floating - point values. For
example:
displays The number is 234 on the screen.,This call to the printf( ) function contains two
arguments. The first one is the quoted string and the other is the constant 234. Note
38
In general, when there is more than one argument to a function, the arguments are
A format specifier, on the other hand informs printf( ) that a different type item is being
displayed. In this case, the %d, means that an integer, is to be output in decimal format,
The value to be displayed is to be found in the second argument. This value is then
output at the position at which the format specifier is found on the string.
Code Format
%c Character
%s String of characters
39
%X Unsigned hexadecimal (Uppercase letters)
Examples
This program shown below explain more about the concept. First, it declares a variable
called num. Second, it assigns this variable the value 56. Finally, it uses printf( ) to
#include<stdio.h>
main()
int num;
num = 56;
return 0;
2. This program creates variables of types char, float, and double assigns each a value
#include<stdio.h>
main()
char name;
float gyt;
40
double und;
name = ‘student’;
gyt= 89.63;
d = 567.123;
return 0;
Revision questions
1. Enter, compile, and run the two programs above.
2. Write a program that declares one integer variable called num. Give this variable the
908 and then, using one printf ( ) statement, display the value on the screen like this:
There are several ways to input values through the keyboard. One of the easiest is to
To use scanf( ) to read an integer value from the keyboard, call it using the general
form:
41
scanf(“%d”, &int-var-name);
Where int-var-name is the name of the integer variable you wish to receive the value.
The first argument to scanf( ) is a string that determines how the second argument will
be treated. In this case the %d specifies that the second argument will be receiving an
int num;
scanf(“%d”, &num);
The & preceding the variable name means ‘address of’. The values you enter are put
into variables using the variables’ location in memory. It allows the function to place a
When you enter a number at the keyboard, you are simply typing a string of digits.
The table below shows format specifiers or codes used in the scanf() function and their
meaning.
Code Meaning
42
%e Read a floating point number
%s Read a string
Examples
#include<stdio.h>
main()
int num;
return 0;
2. This program computes the area of a rectangle, given its dimensions. It first prompts
the user for the length and width of the rectangle and then displays the area.
#include<stdio.h>
main()
43
{
scanf( “ %d “, &width);
return 0;
Exercises
2. Write a program that inputs two floating-point numbers (use type float) and then
3. Write a program that computes the volume of a cube. Have the program prompt the
functions.
Variables declared outside all functions are called global variables and they may be
accessed by any function in your program. Global variables exist the entire time your
program is executing.
44
Variables declared inside a function are called local variables. A local variable is known
to and may be accessed by only the function in which it is declared. You need to be
(i) The local variables in one function have no relationship to the local variables in
another function. That is, if a variable called count is declared in one function,
another variable called count may also be declared in a second function – the two
(ii) Local variables are created when a function is called, and they are destroyed when
the function is exited. Therefore local variables do not maintain their values between
function calls.
2.4 Constants
A constant is a value that does not change during program execution. In other words,
constants are fixed values that may not be altered by the program.
Floating - point constants require the use of the decimal point followed by the number’s
fractional component. For example the body temperature can be set to be 37.1 and also
45
The number is optional. Although the general form is shown with spaces between the
component parts for clarity, there may be no spaces between parts in an actual number
. For example, the following defines the value 672.89 using scientific notation.
672.89E1
Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'.
letter= ‘u’;
Note:
There is nothing in C that prevents you from assigning a character variable a value
using a numeric constant. For example the ASCII Code for ‘A ‘ is 65. Therefore, these
char ch;
ch = “A’;
ch = 65;
Directly
Here the constant value is inserted in the expression, as it should typically be.
For example:
46
The value 3.14 is used directly to represent the value of PI which never requires
preprocessor before the program is compiled. For example, all occurrences of the
symbolic constant Temp are replaced with the replacement text 37.1.
Example:Area of a circle
#include<stdio.h>
#define PI 3.14
main()
scanf(“%f”, &radius);
return 0;
47
}
Note:
At the time of the substitution, the text such as 3.14 is simply a string of characters
composed of 3, ., 1 and 4.
left, the type of the right side is converted into that of the left. When the type of the left
side is larger than the right side, this process causes no problems. However, when the
type of the left side is smaller than the type of the right, data loss may occur.
When converting from a long double to a double or from a double to float, precision is
lost. When converting from floating point value to an integer value, the fractional part is
lost, and if the number is too large to fit in the target type, a garbage value will result.
As stated when converting from a floating-point value to an integer value, the fractional
#include<stdio.h>
main()
int num;
float decnum;
48
decnum= 1234.0098;
num = decnum;
return 0;
Revision Exercises
1. Discuss four fundamental data types supported by C, stating how each type is stored
in memory.
3. Suggest, with examples two ways in which constant values can be used in C
expression statements.
49
The mass of a single molecule of water is about 3.0 x 10 -23 grams. A quart of
water is about 950 grams. Write a program that requests an amount of water in
Chapter Objectives
Types of operators.
An operand is a data item that is acted upon by an operator. Some operators act upon
two operands (binary operators) while others act upon only one operand (unary
operators).
50
Examples
a) Arithmetic Operators
Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
Note:
51
(ii) The operands acted upon by arithmetic operators must represent numeric
Thus;
5 % 3 the answer is 2.
int x = 8;
(v) Dividing a floating point number with another floating point number, or a
Examples
a*b letter
52
a/b letterone + lettertwo +5
Note:
If one or both operands represent negative values, then the addition, subtraction,
multiplication, and division operators will result in values whose signs are determined by
r1 + r2 = 3.84
r1 - r2 = -5.16
r1 * r2 = -2.97
r1 / r2 = -0.1466667
Note:
(i) If both operands are floating point types whose precision differ (e.g. a float and a
double) the lower precision operand will be converted to the precision of the other
53
operand, and the result will be expressed in this higher precision. (Thus if an
expression has a float and a double operand, the result will be a double).
(ii) If one operand is a floating-point type (e.g. float, double or long double) and the
integer will be converted to the floating point type and the result will be expressed as
such.
(iii) If neither operand is a floating-point type but one is long integer, the other will be
converted to long integer and the result is expressed as such. (Thus between an int
(iv) If neither operand is a floating type or long int, then both operands will be converted
to int (if necessary) and the result will be int (compare short int and long int)
(i) i+f
(ii) i+c
(iii) i + c-‘w’
(iv) ( i + c) - ( 2 * f / 5)
Note: Whichever type of result an expression evaluates to, a programmer can convert
the result to a different data type if desired. The general syntax of doing this is:
54
(data type) expression.
The data type must be enclosed in parenthesis (). For example the expression (i + f)
(int) (i + f).
The order of executing the various operations makes a significant difference in the
(i) Multiplication and division have a higher precedence than addition and subtraction,
(ii) If operators of equal precedence; (*, /), (+, -) share an operand, they are executed in
the order in which they occur in the statement. For most operators, the order
(associativity) is from left to right with the exception of the assignment ( = ) operator.
(Since * and / are first before + but * and / share the operand n with * first)
55
Second: 360.0 / SCALE = 180
(Division follows)
include<stdio.h >
main()
56
int score,max;
score = 90;
return 0;
Try changing the order of evaluation by shifting the parenthesis and note the change in
Exercise
Write a program that calculates the two roots x1 x2 with double precision, and displays
#include<stdio.h >
#define Sec_in_min 60
57
main()
return 0;
sizeof returns the size in bytes, of its operand. The operand can be a data type e.g.
If it is a name type such as int, float etc. The operand should be enclosed in
parenthesis.
#include <stdio.h>
main()
58
int n;
sizeof n, sizeof(int)) ;
return 0;
The Assignment operator ( = ) is a value assigning operator. There are several other
Assignment expressions that make use of the assignment operator (=) take the form;
identifier = expression;
Examples of assignment;
a=3;
x=y;
pi = 3.14;
sum = a + b ;
59
Note
(iii) Multiple assignments are possible e.g. a =b = 5 ; assigns the integer value 5
to both a and b.
Conditional tests can be carried out with the conditional operator (?). A conditional
expression3.
Assuming i is an integer, the expression (i < 0) is evaluated and if it is true, then the
result of the entire conditional expression is zero (0), otherwise, the result will be 100.
60
Unary Operators
These are operators that act on a singe operand to produce a value. The operators may
Examples
Relational Operators
== Equal to
!= Not equal to
61
A logical expression represents conditions that are either true (represented by integer 1)
Example
Consider a, b, c to be integers with values 1, 2,3 respectively. Note their results with
Expression Result
a<b 1 (true)
c:=3 0 (false)
b==2 1 (true)
Logical operators
|| Logical OR
! NOT
The two operators act upon operands that are themselves logical expressions to
62
Example
Suppose i is an integer whose value is 7, f is a floating point variable whose value is 5.5
Revision Exercises
3. Suppose a, b, c are integer variables that have been assigned the values a =8, b = 3
and c = - 5, x, y, z are floating point variables with values x =8.8, y = 3.5, z = -5.2.
Further suppose that c1, c2, c3 are character-type variables assigned the values E, 5
and ? respectively.
(i) a/b
(ii) 2 * b + 3 * (a – c)
(iii) (a * c) % b
63
(iv) (x / y) + z
(v) x%y
(vi) 2 * x / (3 * y)
(vii) c1 / c3
64
65
Chapter Four: Introduction To Algorithmic Problem solving
Chapter Objectives
This means you must be conscious of the strategies you use to solve problems in order
Note:
66
Problem Solving Process
Step 3 - Maintenance
• Thoroughly understand the problem and problem requirements ,one would ask
67
of algorithms.
desired value(s).
line of work, and they call it different names. A cook, for instance, follows
ingredients (input) into some culinary dish (output), after a certain number
of steps.
An algorithm is a form that embeds the complete logic of the solution. Its
that solves the problem, and conversion of the algorithm into code. The
68
latter, usually known as coding, is comparatively easier; since the logic is
• Is specified by
Before a computer can perform a task, it must have an algorithm that tells it what to do.
Informally: “An algorithm is a set of steps that define how a task is performed.”
An example of an algorithm
69
The modern Euclidean algorithm to compute gcd (greatest common
not stop when executed, we will not be able to get any result from it.
Again, this goes without saying. An algorithm must provide the correct
This means that it must solve every instance of the problem. For
70
example, a program that computes the area of a rectangle should work on
Representation of Algorithms
Formulas: F = (9/5)C + 32
Flow Charts.
Pseudo-code.
In each case, the algorithm stays the same; the implementation differs.
program
• Problem solving techniques are not unique to Computer Science. The Computer
Science field has joined with other fields to try to solve problems better.
• Working backwards
71
Reverse-engineer.
Sort a particular list such as: David, Alice, Carol and Bob to find a general
sorting algorithm
• Stepwise Refinement
the specific.
detailing any first-level subsystems. Each subsystem is then refined in yet greater detail,
sometimes in many additional subsystem levels, until the entire specification is reduced
to base elements. A top-down model is often specified with the assistance of "black
72
Top-down programming involves writing code that calls functions you haven't defined
and working through the general algorithm before writing the functions that do the
processing.
Advantage of Top-down
Top-down programming is, to a good degree, a very abstract way of writing code
because it starts out by using functions you haven't designed, and that you perhaps do
existing primitives of the programming language, and constructing gradually more and
more complicated features, until the all of the application has been written.
The programmer writes the basic functions he/she realizes will be necessary at some
point in the programming and then work up to the more complex parts of the program.
b) Pieces of programs written bottom-up tend to be more general, and thus more
73
4.5 Pseudocode
Pseudocode is like a programming language but its rules are less stringent. It can also
Based on selection (if, switch) and iteration (while, repeat) constructs in high-level
programming languages.
Design using these high level primitives and it is Independent of actual programming
language.
Solution
74
count = how many numbers are
entered? }
eventually }
increment count
ave ß sum/count
Example 2.
This pseudo code is suppose to help capture the marks for the student and print
relevant messages on the screen that’s if the grade is equal to 60 or more then it should
Print "passed"
else
75
Print "failed"
Example 3.This is an example that helps to capture grade of ten student and then get
76
add this grade into the running total
else
77
add one to passes
else
4.6 Flowchart
Algorithms may also be represented by diagrams. One popular diagrammatic
method is the flowchart, which consists of terminator boxes, process boxes, and
The flowchart below depicts the same logic as the algorithms above in example 1.
Process box
Decision box
78
sum ß count ß 0
min ß ?
max ß ?
Yes
end of
input?
No
Yes
min num
ave sum/count
increment count
Yes max num
num<min?
No
num>max?
79
No
Whether you use the pseudo-code or the flowchart to represent your algorithm,
remember to walk through it with some sets of data to check that the algorithm
works.
Pseudocode Advantages
Pseudocode Disadvantages
Flowchart Advantages
i) Standardized: all pretty much agree on the symbols and their meaning
Flowchart Disadvantages
80
i) Hard to modify
More recent extensions to the methodology is the Jackson System Development (JSD)
JSD focuses on the identification of information entities and the actions that applied to
Produce data structure diagrams for input and output data streams.
Device independent and model as tree diagram using sequence, selection and iteration.
81
A A A
B C D B B C D
Iteration Selection
Sequence
Characteristics of JSP
b) It is rational, i.e. the design procedure is based on reasoned principles, and each
c) It is teachable. People can be taught to practice the method and two or more
programmers using the method to solve the same problem will arrive at substantially
82
d) It is practical. The method itself is simple and easy to understand, and the
environment.
Advantages of JSP
b) Provide a method that is "workable" within the intellectual limitations of the average
programmer.
Steps in JSP
i. Draw structure diagrams for each set of data such that the structure reflects the way
iii. Produce a program structure diagram using the same notation as that used in data
structures, and based on the data structures, combine them at the points of
correspondence.
83
iv. For each iteration and selection appearing in the program structure diagram,
v. Examine the specification and the conditions and from these draw up a list of basic
vi. Allocate the conditions and operations to the appropriate components of the
program structure.
vii. Produce schematic logic, also known as pseudo code from the program structure.
Example 1
Consider certain amount and then award interest rate based on the whether the amount
is less or more than 1,000.if the amount is less than 1000 award 6% otherwise award
Flowchart solution.
84
The pseudocode for this would be:
ELSE
ENDIF
Revision questions
85
b) Study the following flowchart and then provide the pseudocode equivalent
do
86
read a number
increment count by 1
display average
87
CHAPTER FIVE: CONTROL STRUCTURES
Chapter objective.
5.1 Introduction
Control structures these are programming constructs or elements that are used to alter
Sequence
Basically, program statements are executed in the sequence in which they appear in the
program.
printf(“Pass”);
else
88
printf(“Fail”);
until some condition is satisfied. This is known as looping. For example, the following
The if statement
The if statement provides a junction at which the program has to select which path to
if(expression)
statement;
If expression is true (i.e. non zero) , the statement is executed, otherwise it is skipped.
Normally the expression is a relational expression that compares the magnitude of two
Examples
89
(i) if (x<y)
(ii) if (age>18)
statement).
if(expression)
block of statements;
Example
if(age>18)
if - else statement
90
The if else statement lets the programmer choose between two statements as opposed
to the simple if statement which gives you the choice of executing a statement (possibly
if (expression)
statement;1
else
statement2;
compound.
Example:
if(x >=0)
91
{
x++;
else
if (expression)
statement;
else if (expression)
statement;
else if (expression)
statement;
else
statement;
92
(Braces still apply for block statements)
Example
if(sale_amount>=10000)
else
Example
#include<stdio.h >
#include<string.h >
main()
93
int mks;
strcpy(grd, “Credit”);
94
{
strcpy(grd, “Fail”);
else
return 0;
The switch - break statements can be used in place of the if - else statements when
Example
#include<stdio.h>
main()
int choice;
95
switch (choice)
{ /* Begin of switch* /
case 1: /* label 1* /
break;
case 2: /* label 2* /
break;
case 3: /* label 3* /
break;
case 4: /* label 4* /
break;
default:
} /* End of switch*/
else
return (0);
96
} /* End of main*/
Explanation
The expression in the parenthesis following the switch is evaluated. In the example
Then the program scans a list of labels (case 1, case 2,…. case 4) until it finds one that
If there is no match, the program moves to the line labeled default, otherwise the
The break statement causes the program to break out of the switch and skip to the next
statement after the switch. Without the break statement, every statement from the
case constant 1:
statement; optional
case constant 2:
statement; optional
97
…………
default: (optional)
statement; (optional)
Note:
(i) The switch labels (case labels) must be type int (including char) constants or
constant expression.
(ii) You cannot use a variable for an expression for a label expression.
(iii) The expressions in the parenthesis should be one with an integer value. (again
#include<stdio.h>
main()
char ch;
scanf(“%c”, &ch);
98
if (ch>=’a’ && ch<=’z’) /*lowercase letters only */
switch (ch)
{ /*begin of switch*/
case `a`:
break;
case ‘b’:
break;
case ‘c’:
break;
case ‘d’:
break;
default:
else
99
return 0;
} /* End of main */
5.2 Looping
C supports three loop versions:
while loop
do while loop
for loop.
The while statement is used to carry out looping instructions where a group of
General form:
while (expression)
statement;
The statement will be executed as long as the expression is true, the statement can be
a single or compound
/* counter.c */
main()
100
{
while (num<10)
num++;
return 0;
Solution
#include<stdio.h>
main()
int n, count = 1;
scanf(“%d”, &n);
101
/*Read in the number */
while (count<=n)
printf(“fnum = “);
scanf(“%f”, &fnum);
sum+=fnum;
count++;
average = sum/n;
return 0;
(Note that using the while loop, the loop test is carried out at the beginning of each loop
pass).
do .. while loop
It is used when the loop condition is executed at the end of each loop pass.
General form:
102
do
statement;
while(expression);
The statement (simple or compound) will be executed repeatedly as long as the value of
Notice that since the test comes at the end, the loop body (statement) must be executed
at least once.
Rewriting the program that counts from 0 to 9, using the do while loop:
/* counter1.c */
main()
do
num++;
103
} while (num<10);
return 0;
Exercise : Rewrite the program that computes the average of n numbers using the do
while loop.
For loop
General form:
for (expression1;expression2;expression3)
statement;
where:
expression3 is used to alter the value of the initial parameter either increasing or
decreasing.
Example
104
Output
01234
/* average.c */
#include<stdio.h>
main()
int n, count;
scanf(“%d”, &n);
for(count=1;count<=n;count++)
printf(“x = “);
scanf(“%f”, &x);
sum+=x;
105
}
average = sum/n;
return 0;
#include<stdio.h>
main()
int number;
for(num=1; num<=6;num++)
return 0;
You can count by any number you wish; two’s threes, etc.
106
You can test some condition other than the number of operators.
Nesting statements
It is possible to embed (place one inside another) control structures, particularly the if
Revision Exercises
1. A retail shop offers discounts to its customers according to the following rules:
Purchase Amount >= Ksh. 10,000 - Give 10% discount on the amount.
Ksh. 5, 000 <= Purchase Amount < Ksh. 10,000 - Give 5% discount on the amount.
Ksh. 3, 000 <= Purchase Amount < Ksh. 5,000 - Give 3% discount on the amount.
2. Write a program that asks for the customer’s purchase amount, then uses if
cater for negative purchase amounts and display the payable amount in each case.
3. Using a nested if statement, write a program that prompts the user for a number and
107
4. Write a while loop that will calculate the sum of every fourth integer, beginning with
the integer 3 (that is calculate the sum 3 + 7 +11 + 15 + ...) for all integers that are
Chapter Objectives
6.1 Introduction
It is often necessary to store data items that have common characteristics in a single
form that supports convenient access and processing e.g. a set of marks for a known
number of students, a list of prices, stock quantities, etc. Arrays provide this facility.
What Is An Array?
108
22 19 20 21 21 22 23 10 19 20
Declaring Arrays
brackets.
Syntax.
Examples:
int is the data type of the array (type of elements held), num is the array name
(ii) static char names[30]; A 30 character-type array called names. The individual array
109
An array’s dimension is the number of indices required to manipulate the elements of
the array.
(i) A one-dimensional array requires a single index e.g. int numbers [10];
Resembles a single list of values and therefore requires a single index to vary
They are defined the same way as a one-dimensional array except that a
separate pair of square brackets is required for each subscript. Thus a two-
dimensional array will require two pairs of brackets, a three dimensional array will
require three pairs of square brackets, etc. but mostly 2D will be used in
and n columns. The number of elements can be known by the product of m (rows) and
n(columns).
float table[50][50];
char page[24][80];
110
Example
Laura 33 41 57 83 32
Lilian 64 50 89 98 60
Rawlynes 56 73 86 69 74
Houghton 72 53 74 63 75
John 45 60 78 70 86
main()
---------
---------
111
Because the array is defined inside main, its an automatic array. The first element
marks[0] is assigned the value of 80 , marks[1] as 50 and so on. Like other types of
variables, you can give the elements of arrays initial values. This is accomplished by
specifying a list of values the array elements will have. The general form of array
The value list is a comma separated list of constants that are type compatible with the
In the following example, a five – element integer array is initialised with the squares of
This means that i[0] will have the value 1 and i[4] will have the value 25.
You can initialise character arrays in two ways. First, if the array is not holding a
null -terminated string, you simply specify each character using a comma separated
list. For example, this initialises a with the letters ‘A’, ‘B’, and ‘C’.
If the character array is going to hold a string, you can initialise the array using a
112
To work with multiple dimensional arrays is the same way as shown.
For example, here the array multval is initialised with the values 1 though 6, using row
order.
int multval[2][3] = {
1, 2, 3,
4, 5, 6,
};
This initialisation causes multval [0][0] to have the value 1, multval [0][1] to contain 2,
If you are initialising a one-dimensional array, you need not specify the size of the array,
If you don’t specify the size, the compiler simply counts the number of initialisation
constants and uses that that value as the size of the array.
#include<stdio.h>
main()
113
int intnum[] = {6,9,5,8,16,32,64,128};
int i;
return 0;
Note:
The number of items in the list should match the size of the array.
#include<stdio.h>
main()
int n,i;
float num[150];
/* Read in a value of n */
114
printf(“ \n How many numbers will be averaged ? “);
scanf(“ %d “, &n);
printf(“ i = %d x = ”, count+1);
scanf(“ %f “, &list[i]);
sum+=list[i];
avg = sum/n;
d = list[i] – avg;
return 0;
} /* End of program */
115
Exercise
Write a program to store even numbers between 10 and 50, The program should store
the numbers on an array named even,the program should also compute the average of
the numbers.
#include<stdio.h>
main()
116
for(cols=0;cols<CATS;cols++) /* Inner loop for cats */
printf(“CAT %d\n”,cols+1);
for(rows=0;rows<STUDENT; rows++)
for(cols=0;cols<CATS;cols++)
117
}
return 0;
Revision Exercises
1. What is an array structure?
NANCY 90 34 76 45
JAMES 55 56 70 67
MARY 45 78 70 89
ALEX 89 65 56 90
MOSES 67 56 72 76
CAROL 70 90 68 56
118
(a) Write a statement that would create the above table and initialize it with
(iii) Write a complete program that initializes the above values in the
table, computes and displays the total mark and average scored
by each student.
4. Show how to initialise an integer array called items with the values 1 through 10.
5. (i) Write a program that defines a 3 by 3 by 3 three dimensional array, and load it
(ii) Have the program in (i) display the sum of the elements.
Chapter Objectives
b) Type of functions.
119
7.1 Introduction
A function is a self-contained program segment that carries out some specific well -
defined task. Every C program consists of one or more functions. One of these
functions must be called main. Execution of the program will always begin by carrying
If a program contains multiple functions, their definitions may appear in any order,
though they must be independent of one another. That is, one function definition cannot
be embedded within another. A function will carry out its intended action whenever it is
accessed (whenever the function is called) from some other portion of the program.
Generally the function will process information that is passed to it from the calling
portion of the program and return a single value. Information is passed to the function
via special identifiers called arguments (also called parameters), and returned via the
return statement. Some functions however, accept information but do not return
anything.
120
identifiable purpose. Thus a C program can be modularized through the intelligent use
of functions.
There are several advantages to this modular approach to program development; for
repeatedly from several different places in the program. The repeated instructions can
be placed within a single function which can then be accessed whenever it is needed.
A function definition has two principle components; the first line (including the argument
declaration), and the body of a function. The first line of a function definition contains the
value returned by the function, followed by the function name, and (optionally) a set of
preceded by its associated type declaration. Any empty pair of parenthesis must follow
the function name if the function definition does not include any arguments.
n)
Where data-type represents the data type of the item that is returned by the function.
functionname represents the function name , and type 1 , type 2 ,…….., type n
121
represents the data types of the arguments, argument 1, argument 2 ,……..argument
n.
The arguments are called formal arguments because they represent the names of data
items that are transferred into the function from the calling portion of the program. The
names of the formal arguments need not be the same as the names of the actual
return (expression);
Only one expression can be included in the return statement. Thus, a function can
Consider a function that accepts two integer quantities, determines the larger of the two
and displays it (the larger one). This function does not return anything to the calling
int z;
z = (x >= y)? x : y;
122
The keyword void added to the first line indicates that the function does not return
anything.
enclosed in parenthesis and separated by commas. If the function call does not require
any arguments an empty pair of parenthesis must follow the name of the function. The
the formal arguments that appear in the first line of the function definition. (They are
r arguments).
#include<stdio.h>
123
int m;
m= (i > = j )? i : j;
return(m);
main()
int a , b , c ,d;
printf(“\n a = ”);
scanf(“%d”, &a);
printf(“\n b = ” );
scanf(“%d”, &b);
printf(“\n c = ”);
scanf(“%d”, &c);
return 0;
124
The function largest is accessed from two different places in main. In the first call to
maximum, the actual arguments are the variables a and b whereas in the second call,
the arguments are c and d. (d is a temporary variable representing the maximum value
of a and b).
d = largest(a, b);
In the previous function examples, the programmer -defined function has always
preceded main. Thus when the programs are compiled, the programmer-defined
function will have been defined before the first function access. However many
programmers prefer a top drawn approach in which main appears ahead of the
main) will precede the function definition. This can be confusing to the compiler unless
the compiler is first alerted to the fact that the function being accessed will be defined
125
Function prototypes are usually written at the beginning of a program ahead of any
is;
n);
Where data_type represents the type of the item that is returned by the function,
function_name represents the name of the function, type 1, type 2, … …., type n
Note that a function prototype resembles the first line of a function definition (although a
Function prototypes are not mandatory in C. They are desirable however because they
further facilitate error checking between the calls to a function and the corresponding
function definition.
Here is a complete program to calculate the factorial of a positive integer quantity. The
program utilises the function factorial defined in example 1 and 2. Note that the function
126
#include<stdio.h>
main()
int n;
return 0;
int i;
if (n >1)
prod *= i;
127
return (prod);
7.1.4 Recursion
Recursion is the process by which a function calls itself repeatedly until a special
condition is satisfied.
Example
e.g. 5 ! = 5 * 4 * 3 * 2 * 1.
Revision Exercises
128
(i) int f(int a);
2. Each of the following is the first line of a function definition. Explain the meaning of
each.
3. Write appropriate function prototypes for each of the following skeletal outlines shown
below.
(a) main()
int a, b, c;
……
c =function1(a,b);
……
int z;
……
129
z = ……
return(z);
(b) main()
int a;
float b;
long int c;
……
c = funct1(a,b);
……
long int z;
……
……
z = ……
return (z);
130
4. Describe the output generated by the followed program.
#include<stdio.h>
main()
int a,count;
a = func(count);
printf(“%d”,a);
return 0;
int func(int x)
int y;
y = x * x;
return(y);
131
(b) State two conditions that must be satisfied in order to solve a problem using
recursion.
Chapter Objectives
Searching for data is one of the fundamental fields of computing. Often, the difference
between a fast program and a slow one is the use of a good algorithm for the data set.
In searching and sorting will use mostly the array data structures so as to enhance
better understanding though even linked list can also be used. A search algorithm is a
starting with the first element.It compares each element with the value being searched
for and stops when that value is found or the end of the array is reached.The most
132
obvious algorithm is to start at the beginning and walk to the end, testing for a match at
each item:
bool jw_search ( int *list, int size, int key, int*& rec )
int i;
if ( key == list[i] )
break;
if ( i < size ) {
found = true;
rec = &list[i];
return found;
133
// performs a linear search on an integer array.
#include <iostream.h>
// Function prototype
void main(void)
int results;
if (results == -1)
cout << "You did not earn 100 points on any test\n";
else
134
// number is found, its array subscript is returned. Otherwise,
if (list[count] == value)
found = true;
position = index;
index++;
return position;
The Output.
135
This algorithm has the benefit of simplicity; it is difficult to get wrong, unlike other more
sophisticated solutions.
1. All search routines return a true/false Boolean value for success or failure.
2. The list will be either an array of integers or a linked list of integers with a key.
3. The found item will be saved in a reference to a pointer for use in client code.
The algorithm itself is simple. A familiar (0 to n-1) loop to walk over every item in the
array, with a test to see if the current item in the list matches the search key.
The loop can terminate in one of two ways. If it reaches the end of the list, the loop
condition fails. If the current item in the list matches the key, the loop is terminated early
with a break statement. Then the algorithm tests the index variable to see if it is less
that size (thus the loop was terminated early and the item was found), or not (and the
The search technique is much more useful for small and unsorted arrays
• It is easy to understand
136
• Easy to implement
If there are 20,000 items in the array and what you are looking for is in the 19,999 th
element, you need to search through the entire list and this is time consuming.
• If the item is less than the middle element, it starts over searching the
• If the item is greater than the middle element, the search starts over
starting with the middle element in the second half of the list.
137
• If equal, match found
• Repeat
#include <iostream.h>
// Function prototype
void main(void)
int tests[arrSize] = {101, 142, 147, 189, 199, 207, 222,234, 289, 296, 310, 319, 388,
cout << "Enter the Employee ID you wish to search for: ";
138
cin >> empID;
if (results == -1)
else
139
int first = 0, last = numelems - 1, middle, position = -1;
{ found = true;
position = middle;
last = middle - 1;
else
return position;
140
Enter the Employee ID you wish to search for: 199
Exercises
1. Write a test program to verify the correct operation of the functions given.
2. Can you think of a more efficient way to perform sequential search? What about
a non-sequential search?
data elements in some given order. Many Sorting algorithms are available to sort the
given set of elements. We will discuss two sorting techniques. The two techniques are:
1. Internal Sorting
2. External Sorting
141
Internal Sorting
Internal Sorting takes place in the main memory of a computer. The internal sorting
methods are applied to small collection of data. It means that, the entire collection of
data to be sorted in small enough that the sorting can take place within main memory.
Sorting algorithms are used to arrange random data into some order,it is Important
computing application,Virtually every organization must sort some data mostly Massive
a) Insertion sort
b) Selection sort
c) Merge Sort
d) Radix Sort
e) Quick Sort
f) Heap Sort
g) Bubble Sort
its proper position. For example, the card player arranging the cards dealt to him. The
player picks up the card and inserts them into the proper position. At every step, we
142
This sorting algorithm is frequently used when n is small. The insertion sort algorithm
scans A from A[l] to A[N], inserting each element A[K] into its proper position in the
previously sorted
Pass 2. A[2] is inserted either before or after A[l] so that: A[l], A[2] is sorted.
Pass 3. A[3] is inserted into its proper place in A[l], A[2], that is, before A[l],between A[l]
Pass 4. A[4] is inserted into its proper place in A[l], A[2], A[3] so that: A[l], A[2], A[3], A[4]
is sorted.…………………………………………………
Pass N. A[N] is inserted into its proper place in A[l], A[2], . . . , A[N - 1] so that: A[l], A[2],
. . . ,A[N] is sorted.
INSERTION ( A , N )
143
[End of loop].
6. Return
elements and B is a sorted list with s elements. The operation that combines the
elements of A and B into a single sorted list C with n = r + s elements is called merging.
After combining the two lists the elements are sorted by using the following merging
That is, at each step, the two front cards are compared and the smaller one is placed in
the combined deck. When one of the decks is empty, all of the remaining cards in the
other deck are put at the end of the combined deck. Similarly, suppose we have two
lines of students sorted by increasing heights, and suppose we want to merge them into
a single sorted line. The new line is formed by choosing, at each step, the shorter of the
two students who are at the head of their respective lines. When one of the lines has no
more students, the remaining students line up at the end of the combined line.
MERGING ( A, R, B, S, C)
144
Let A and B be sorted arrays with R and S elements. This algorithm merges A and B
Else
[End of loop]
If NA > R , then
[End of loop]
Else
[End of loop]
145
4. Exit
• Example:
original: 3 4 2 6 7
pass 1: 3 2 4 6 7
pass 2: 2 3 4 6 7
Do
For count is set to each subscript in Array from 0 to the next-to-last subscript
146
swap them
end if
End for
#include <iostream.h>
// Function prototypes
void main(void)
147
showArray(values, 6);
sortArray(values, 6);
showArray(values, 6);
// order bubble sort on Array. elements is the number of elements in the array.
do
swap = 0;
148
{
temp = array[count];
array[count + 1] = temp;
swap = 1;
// number of elements.
149
cout << endl;
Program Output.
723891
123789
The bubble sort is inefficient for large arrays because items only move by one element
at a time. The selection sort moves items immediately to their final position in the array
For Start is set to each subscript in Array from 0 through the next-to-last subscript
150
For Index is set to each subscript in Array from Start+1 through the next-to-last
subscript
End if
Increment Index
End For
End For
#include <iostream.h>
151
// Function prototypes
void main(void)
showArray(values, 6);
selectionSort(values, 6);
showArray(values, 6);
152
{
{ minIndex = startScan;
minValue = array[startScan];
minValue = array[index];
minIndex = index;
array[minIndex] = array[startScan];
array[startScan] = minValue;
153
// Definition of function showArray.
// number of elements.
Program Output
572891
125789
154
sorted is too large. These methods involve as much external processing as processing
in the CPU. To study the external sorting, we need to study the various external devices
used for storage in addition to sorting algorithms. This sorting requires auxiliary storage.
Revision questions
155
Model examination Papers
Paper One
QUESTION ONE
[2marks]
e. Identify the errors in the following program and write a correct program:
Main( )
Scanf(“%c”, legs);
cows = legs/4;
[4 marks]
f. Write a program that ask the user for an integer and then tells the user if that
number is even or odd. [5m marks]
156
QUESTION TWO
c. Write a program that prompts the user to enter the radius of a circle and computer the area and
circumference of the circle the program should display the computed value on the screen declare PI as a
constant . [5marks]
d. Explain briefly the meaning of the following escape sequence characters
i. \a
ii. \r [2 marks]
QUESTION THREE
a. A program is required to accept two numbers A and B, if the value of A is greater Than that of B then they
are added together otherwise the value of A is subtracted from B required:
i. Write the pseudo code for you solution [4 marks]
ii. Write the program code to accomplish this [6 marks]
b. Explain any two type of tools of algorithm that are using during software development.
[2 marks]
int a,b;
a=2;
b=0
a++;
157
--b
Printf(a+b);
QUESTION FOUR
d. Describe briefly any two categories of operators that are used in C programming language. [2 marks]
g. List and explain the two main types of function found in C program [4 marks]
QUESTION FIVE
c. Write a program that inputs numbers and stores in an even and odd number array structure.
Display the content of each array assume that the two arrays can stores up to100 elements each.
The program should ask the user how many numbers he/she would want to work with. [6 marks]
Question 1
a) Write a program that calculates the product of Two numbers by allowing the user to enter them on the
keyboard, then calculate the result and output it to the user. (6 marks)
158
b) Mention and briefly discuss the basic C data types (8 marks)
- Variable
- Arrays
- Functions
d) A program error can either be syntax, logic or semantic. Classify the errors below
i) An indefinite loop
ii) Misspelling keywords
iii) Division by zero error (3 marks)
e) Using 3.14 as pie value demonstrate how you create symbolic constants (2 marks)
f) Provide a C statements to declare an int array and initialize its’ elements to 10 , 20 , 30, 40 and 50 respectively
(4 marks)
g) Provide function prototype for a function to calculate and return the product of three integer values (3 marks)
h) Create a simple c program to that allows user to enter name and display the name on the screen. (3 marks)
Question 2
b) Write program to read the values a, b and c and display the value of x, when x = a / b – c (6 marks)
159
printf("%d\n", i);
ii) for(i = 100; i >= 0; i = i - 7)
printf("%d\n", i);
iii) for(i = 1; i <= 10; i = i + 1)
printf("%d\n", i);
iv)for(i = 2; i < 100; i = i * 2)
printf("%d\n", i); (8 marks)
Question 3
a) Write a program that uses a function to return the sum of two numbers. (6 marks)
b) Write a function celsius() to convert degrees Fahrenheit to degrees Celsius. (The conversion formula is °C = 5/9 *
(°F - 32).). (6 marks)
c) Explain how while is different from do...while (2 marks)
d)
i) What is a pointer variable (2 marks)
ii) Provide program statements to demonstrate how to create a pointer variable , assign address to a pointer
variable and output the value at the memory location pointed to by the pointer variable (4 marks)
Question 4
a) Write a c program that asks the user to enter the total marks of the student. The program then prints
‘proceed’ if the marks are greater than 40 otherwise it prints ‘fail’. (6 marks)
b) Write a program that prompts for circle diameter, then calculates and outputs both circle radius and area
(6 marks)
c) Why is the function main() special in a c program? (2 marks)
d) Discuss the two methods of including comments in your C program (2 marks)
e) Write a program that outputs the string “C is a structured programming language” on the screen. (4
marks)
Question 5
a) Define a function that returns the factorial of a number (you have to use a loop). The argument to the
function is an integer whose factorial is to be found. Use the function in a main program where you ask the
user to enter a number then your program outputs the factorial. (10 marks)
b) Write a program that uses an array to read marks scored by a diploma student in 4 subjects, and then
calculates the mean score. The program should finally output the scores in the four subjects and the mean
(10 marks)
160
161