Programming Methodologies Notes
Programming Methodologies Notes
Programming Methodologies Notes
Course Objectives
By the end of the course, students should:-
a) Understand the concept of a program in high level design.
b) Understand principles of good program design.
c) Develop skills of developing algorithms and transforming algorithms into a plan for solution and
a few specific examples of algorithms (for example, finding an average, evaluating conditions
etc).
d) Understand the concept of a variable holding a value, how a variable is declared and how it can
change.
e) Be able to work with both character and numerical data.
f) Be able to use a conditional statement to select a choice from two or more alternatives.
g) Understand the concept of a loop – that is a series of statements which is written once but
executed repeatedly – and how to use it in a programming language.
h) Be able to break a large problem into smaller parts, writing each part as a module on function.
i) Be able to use an array to store multiple pieces of homogeneous data, and use structure to store
multiple pieces of heterogeneous data.
1
COMPUTER PROGRAMMING
Week -Arrays and strings
13, 14 -Single Dimension Arrays 4
-Two Dimensional Arrays
Reference Materials:
C How to program by Deitel and Deitel
The C language trainer with Graphics and C++ by jayasiri
Programming in C by Stephen G. Kochan
Programming in ANSI C by E Balagurusany
Any relevant C book
Internet Resources
http://www.cs.cf.ac.uk/Dave/C/CE.html
2
COMPUTER PROGRAMMING
Definitions
Program
This is a complete set of step-by-step instructions that control and direct the computer hardware in
carrying out a given task. Tasks may vary from very simple e.g. computing surface area to complex ones
like statistical analysis.
Software
This term refers to all programs.
Programming Language
This is a set of symbols and the rules are employed in the construction of a computer program.
Programmer
This is a person who is trained and/or specializes in the technique of creating, maintaining and
modifying computer programs.
Programming Languages
Programming languages provide the basic building block for all software. They are the means by which
people can tell the computer how to carry out a task.
A program can be written ina variety of programming languages. The languages can broadly be
classified into two categories:
Low-level language – which refers to the machine language and assembly language.
High-Level languages: - which refers to languages such as COBOL, FORTRAN, BASIC
Advantages
Program translation was fast because no translation was required.
The program could directly address and control the internal circuitry meaning that these
programs were more effective in hardware usage and control.
Disadvantages
Writing programs was time consuming
Tracing errors in a program was extremely difficult.
Difficult to learn and use.
3
COMPUTER PROGRAMMING
Program modification was cumbersome.
They were machine dependent i.e. a program created for one type of machine would not work
on a different type of machine.
To write an effective program the programmer had to have expert knowledge on the computer’s
internal workings.
This language was more user oriented than machine language. Instructions are represented using
mnemonic code and symbolic addresses. Words like add, sum etc could be used in programs. An
assembler translated these codes into machine language.
Advantages
Much easier to learn compared to machine language.
Coding took less time than coding using machine language.
Error correction was less cumbersome.
Disadvantages
Were also machine specific
Execution took longer than machine language programs due to the translation process.
These languages are user friendly and problem oriented compared to the low level languages. Programs
written in high level languages are shorter than the machine language programs.
They have an extensive vocabulary of words and symbols therefore program instructions are written
using familiar English-like statements and mathematical statements.
A single high-level language program is translated into multiple machine code instructions.
Advantages
They are portable i.e. they can be used on more than one type of machine.
Creating program and error correction takes less time.
Are relatively easy to learn and use.
The programmer does not have to be an expert on the internal workings of the machine.
Disadvantages
Program execution takes more time due to the translation process.
They do not address the internal circuitry of computers as effectively as the low level languages.
A translated program will occupy more space.
Procedural Languages
4
COMPUTER PROGRAMMING
They require the programmer to specify step-by-step how the computer will accomplish a specific task.
Program execution follows the exact sequence laid down by the programmer during coding. Examples
include FORTRAN, PASCAL, BASIC,
Non-Procedural Languages
They allow the programmer to specify the desired result without having to specify the detailed
procedure needed to achieve the result.
They are more user oriented and allow programmers to develop programs with fewer commands
compared with 3rd generation languages. They are called non procedural because programmers can
write programs that need only tell the computer what they want done, not all the procedures of doing
it.
Definitions:
Syntax
These are the rules of a language that govern the ways in which words, symbols, expressions and
statements may be formed and combined in that language.
Semantics
These are the rules of language that govern meaning of statements in any language.
Language Translators
These are programs that translate programs written in a language other than machine language into
machine language programs for execution. Programs written in assembly or high level languages are
called source programs or source code before they undergo translation. After the translation the
machine language version of the same program is called object program or object code. Language
translators can be classified into
Assemblers
Compilers
Interpreters
Assembler
5
COMPUTER PROGRAMMING
This is a program that translates a source program written in assembly language into its equivalent
machine code (object code).
Compiler
During compilation both the high level source program and the compiler are loaded into the RAM. The
compiler reads through the source program statement by statement, converting each correct statement
into multiple machine code instructions. The process continues until the compiler has read through the
entire source program or it encounters an error. An erroneous statement is not translated but is placed
on the source program error listing, which will be displayed to the programmer at the end of the
translation process. Where there are no errors the compiler will generate a machine code (object
program) which is stored for subsequent execution.
The first two stages of compilation are carried out by a part of the compiler known as the parser and can
be referred to as parsing.
The optimized code is then used to generate the object program which is stored on media such as disk
to await subsequent execution.
Interpreter
It is similar to the compiler in that it translates high level language programs into machine code for
execution but no object code is generated. An interpreter translates the program one statement at a
time and if it is error free it executes the statement. This continues till the last statement in the program
has translated and executed. Thus an interpreter translates and executes a statement before it goes to
the next statement. When it encounters an error it will immediately stop the execution of the program.
6
COMPUTER PROGRAMMING
Program Development
2. 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. At this point, you should also be thinking generally although some of your
decisions may be based on some general characteristics of the C language.
7
COMPUTER PROGRAMMING
Algorithms
An algorithm is a sequence of steps which results to a plan or strategy on how to go about solving a
problem. There are different ways of presenting an algorithm. Some common ways include:-
Pseudocode
Flow charts
Pseudocode
This is a case where an algorithm is expressed in English like statements (descriptions). For example the
following pseudocode calculates the pay amount for five employees.
Start
Initialize counter to 1
Enter employee details
Computer pay amount
Print the pay amount
Increment counter by one
Check the value of the counter
If counter < 6
Loop to step 3
End
Flow Chart
This is a symbolic representation of an algorithm sequence. A flow chart uses predefined symbols to
represent the various actions in an algorithm. The arrangement of the symbols indicates the flow of
logic in the algorithm.
Start or end – They are used in a flow chart to mark the beginning and the end.
Process – used to represent operations on data e.g. computations. Details are written in
a rectangular box.
8
COMPUTER PROGRAMMING
Decision – This symbol is used to indicate decision making and branching. The criterion is shown inside
the symbol and the lines (paths) out show the results.
Connectors – A small circle containing a number or letter that is used to split a large flow chart
into smaller parts.
Example
9
COMPUTER PROGRAMMING
modularity. Programs designed this way can be developed faster. When modules are used to
develop large programs, several programmers can work on different modules, thereby
reducing program development time.
Modular Programming
This is a technique that involves breaking down the entire problem into smaller, more manageable units.
Features
Each module within the application carries out a singular task.
Each module runs independently of the other modules.
Since each module is independent, a breakdown in any module does not greatly affect the
running of the application.
Debugging is easier since errors can be traces to individual modules.
Top-Down Approach
In this approach an outline program is designed first, showing the main tasks and components of the
program, and the order in which they are to be executed. Each main component is then reduced to a
number of smaller, simple and more manageable components and this process continues at each level
until there is sufficient detail to allow the coding stage to proceed.
The process of reducing components into sequences of smaller components is often referred to a
stepwise refinement and forms the basis of structured programming.
Bottom-up Approach
In this design approach, the application is developed starting at the bottom of the the hierarchy i.e. the
single task modules. As each category of programs is completed on the hierarchy, the controlling
program for that category is created.
10
COMPUTER PROGRAMMING
Testing is part of the procedures that ensure that corresponds with original specification and that it
works in its intended environment. It is the process of running software to find errors (or bugs), though
it is possible that some errors will get through the testing process without being found.
Types of Errors
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. You should look
for the error in the line suggested by the compiler. Syntax errors include;
Missing semi colon at the end of a statement e.g. Area = Base * Length
Use of an undeclared variable in an expression
Illegal declaration e.g. int x, int y, int z;
Use of a keyword in uppercase e.g. FLOAT, WHILE
Misspelling keywords e.g. init instead of int
Note:
The compiler may suggest that other program line statements have errors when they may not. This will
be the case when a syntax error in one line affects directly the execution of other statements, for
example multiple use of an undeclared variable. Declaring the variable will remove all the errors in the
other statements.
Logic Errors
These occur from the incorrect use of control structures, incorrect calculation, or omission of a
procedure. Examples include: An indefinite loop in a program, generation of negative values instead of
positive values. The compiler will not detect such errors since it has no way of knowing your
intentions. The programmer must try to run the program so that he/she can compare the
program’s results with already known results.
Semantic errors
11
COMPUTER PROGRAMMING
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 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.
12
COMPUTER PROGRAMMING
C is a general purpose programming language, unlike other languages such as 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:
Operating systems: Unix and Windows.
Application packages: WordPerfect and Dbase.
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 - the executable file.
*
Code that acts as interface between the program and the operating system.
13
COMPUTER PROGRAMMING
C Programs’ Components
Keywords
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 be used in lowercase otherwise they will not be
recognized.
Examples of keywords
auto break case else int void
default do double if sizeof long
float for goto signed unsigned
register return short union continue
struct switch typedef const extern
volatile while char enum static
Sample Program
This program will print out the message: This is a C program.
#include<stdio.h>
main()
{
printf("This is a C program \n");
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. You will find it 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. Curly brackets in C are used to group statements together as in a function, or in
the body of a loop. Such a grouping is known as a compound statement or a block.
printf("This is a C program \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 print a new line as part of
the output.
14
COMPUTER PROGRAMMING
Most C programs are in lower case letters. You will usually find upper case letters used in
preprocessor definitions (which will be discussed later) or inside quotes as parts of character
strings.
C is case sensitive, that is, it recognises a lower case letter and it's upper case equivalent as
being different.
/ Sample Program/
#include<stdio.h>
main()
{
int num; / define a variable called num */
num = 1; / assignment /
printf(“ This is a simple program ”);
printf(“to display a message. \n”);
printf (“My favorite number is %d because ”, num);
printf(“ it is first.\n ”);
return 0;
}
On running the above program, you get the following output.
Functions
All C programs consist of one or more functions, each of which contains one or more statements. In C, a
function is a named subroutine that can be called by other parts of the program. Functions are the
building blocks of C.
A statement specifies an action to be performed by the program. In other words, statements are parts of
your program that actually perform operations.
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. Also you may place two
or more statements on one line.
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 your program terminates when the closing brace
is reached.
15
COMPUTER PROGRAMMING
Another important component of all C programs is library functions. The ANSI C standard specifies a
minimal set of library functions to be supplied by all C compilers, 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 your program is
compiled, the code for library functions is automatically added to your program.
One of the most common library functions is called printf( ). This is C’s general purpose output function.
Its simplest form is
printf(“string – to – output”);
The printf( ) outputs the characters that are contained between the beginning and ending double
quotes.
For example, printf(“ This is a C program “);
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 parenthesis is called an argument
to printf( ). In general, information passed to a function is called an argument. In C, calling a library
function such as printf( ) is a statement; therefore it must end with a semicolon.
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 than one argument, the
arguments must be separated by commas.
In the above program, line 7 causes the message enclosed in speech marks “ ” to be printed on
the screen. Line 8 does the same thing.
The \n tells the computer to insert a new line after printing the message. \n is an example of an
escape sequence.
Line 9 prints the value of the variable num (1) embedded in the phrase. The %d instructs the
computer where and in what form to print the value. %d is a type specifier used to specify the
output format for integer numbers.
Line11 indicates the value to be returned by the function main( ) when it is executed. By
default any function used in a C program returns an integer value (when it is called to execute).
Therefore, line 3 could also be written int main( ). If the int keyword is omitted, still an integer
is returned.
Then, why return (0); ? Since all functions are subordinate to main( ), the function does not
return any value.
16
COMPUTER PROGRAMMING
Note:
(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 return 0; is not
necessary.
(ii) While omitting the keyword int to imply the return type of the main( ) functiondoes
not disqualify the fact that an integer is returned (since int is default), you should
explicitly write it in other functions, especially if another value other than zero is to
be returned by the function.
The preprocessor directive #include is an instruction to read in the contents of another 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
Comments are non – executable program statements meant to enhance program readability and allow
easier program maintenance, i.e. they document the program. They can be used in the same line as the
material they explain (see lines 4, 6, 7 in sample program).
A long comment can be put on its own line or even spread on more than one line. Comments are
however optional in a program. The need to use too many comments can be avoided by good
programming practices such as use of sensible variable names, indenting program statements, and good
logic design. Everything between the opening /* and closing */ is ignored by the compiler.
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 types of the variables. Line 6 is a
declaration for an integer variable called num.
17
COMPUTER PROGRAMMING
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 right. The statement num =1;
(Line 6) is an assignment statement.
Escape sequences
Escape sequences (also called back slash codes) are character combinations that begin with a backslash
symbol (\) used to format output and represent difficult-to-type characters.
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.
Char ch;
ch = ‘\t ’ /*assign ch the tab character */
18
COMPUTER PROGRAMMING
Revision Exercises
1. Outline the logical stages of C programs’ development.
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()
{
int , int n2, n3;
n = 5;
n2 = n *n
n3 = n2 * n2;
printf(“ n = %d, n squared = %d, n cubed = %d \ n”, n, n2, n3);
return 0;
}
3. Give the meaning of the following, with examples
(i) Preprocessor command
(ii) Keyword
(iii) Escape sequence
(iv) Comment
(v) Linking
(vi) Executable file
19
COMPUTER PROGRAMMING
4. Provide the meaning of the following keywords, giving examples of their use in C programs.
(i) void
(ii) return
(iii) extern
(iv) struct
(v) static
5. C is both ‘portable’ and ‘efficient’. Explain.
6. C is a ‘case sensitive’ language. Explain.
7. The use of comments in C programs is generally considered to be good programming
practice. Why?
20
COMPUTER PROGRAMMING
DATA HANDLING
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 start of any
block of code.
A declaration begins with the type, followed by the name of one or more variables. For
example,
int high, low, results[20];
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 and the required
value after the declaration.
Variable Names
Every variable has a name and a value. The name identifies the variable and the value stores
data. There is a limitation on what these names can be. Every variable name in C must start
with a letter; the rest of the name can consist of letters, numbers and underscore characters.
C recognizes upper and lower case characters as being different (C is case- sensitive). Finally,
you cannot use any of C's keywords like main, while, switch etc as variable names.
It is conventional to avoid the use of capital letters in variable names. These are used for names of
constants. Some old implementations of C only use the first 8 characters of a variable name. Most
modern ones don't apply this limit though. The rules governing variable names also apply to the names
of functions.
C supports five basic data types. The table below shows the five types, along with the C keywords that
represent them. Don’t be confused by void. This is a special purpose data type used to explicitly declare
functions that return no value.
Type Meaning Keyword
Character Character data char
21
COMPUTER PROGRAMMING
Integer Signed whole number int
Float floating-point numbers float
Double double precision floating-point double
numbers
Void Valueless void
Integer variables may hold signed whole numbers (numbers with no fractional part). Typically, an
integer variable may hold values in the range –32,768 to 32,767 and are 2 bytes long.
You can use printf( ) to display values of characters, integers and floating - point values. To do
so, however, requires that you know more about the printf( ) function.
For example:
printf(“This prints the number %d ”, 99);
22
COMPUTER PROGRAMMING
displays This prints the number 99 on the screen. As you can see, this call to the printf( ) function
contains two arguments. The first one is the quoted string and the other is the constant 99. Notice that
the arguments are separated from each other by a comma.
In general, when there is more than one argument to a function, the arguments are separated from
each other by commas. The first argument is a quoted string that may contain either normal characters
or formal specifiers that begin with a percent (%) sign.
Normal characters are simply displayed as is on the screen in the order in which they are encountered in
the string (reading left to right). 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.
If you want to specify a character value, the format specifier is %c. To specify a floating-point value, use
%f. The %f works for both float and double. Keep in mind that the values matched with the format
specifier need not be constants, they may be variables too.
Code Format
%c Character
%d Signed decimal integers
%i Signed decimal integers
%e Scientific notation (lowercase ‘e’)
%E Scientific notation (lowercase ‘E’)
%f Decimal floating point
%s String of characters
%u Unsigned decimal integers
%x Unsigned hexadecimal (lowercase letters)
%X Unsigned hexadecimal (Uppercase letters)
Examples
1. The program shown below illustrates the above concepts. First, it declares a variable called num.
Second, it assigns this variable the value 100. Finally, it uses printf( ) to display the value is 100 on the
screen. Examine it closely.
#include<stdio.h>
main()
{
int num;
23
COMPUTER PROGRAMMING
num = 100;
printf(“ The value is %d “, num);
return 0;
}
2. This program creates variables of types char, float, and double assigns each a value and outputs
these values to the screen.
#include<stdio.h>
main()
{
char ch;
float f;
double d;
ch = ‘X’;
f = 100.123;
d = 123.009;
printf(“ ch is %c “, ch);
printf(“ f is %f “, f);
printf(“ d is %f “, d);
return 0;
}
Exercises
1. Enter, compile, and run the two programs above.
2. Write a program that declares one integer variable called num. Give this variable the 1000 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 use another of C’s
standard library functions called scanf( ).
To use scanf( ) to read an integer value from the keyboard, call it using the general form:
scanf(“%d”, &int-var-name);
24
COMPUTER PROGRAMMING
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 integer value entered in decimal format.
The fragment below, for example, reads an integer entered from the keyboard.
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 value into one of its arguments.
When you enter a number at the keyboard, you are simply typing a string of digits. The scanf( ) function
waits until you have pressed <ENTER> before it converts the string into the internal format used by the
computer.
The table below shows format specifiers or codes used in the scanf() function and their meaning.
Code Meaning
%c Read a single character
%d Read a decimal integer
%i Read a decimal integer
%e Read a floating point number
%f Read a floating point number
%lf Read a double
%s Read a string
%u Reads an unsigned integer
Examples
1. This program asks you to input an integer and a floating-point number and displays the value.
#include<stdio.h>
main()
{
int num;
float f;
printf(“ \nEnter an integer: “);
scanf( “%d “, &num);
printf(“\n Enter a floating point number: “);
scanf( “%f “, &f);
printf( “%d ”, num);
printf( “\n %f ”, f);
return 0;
25
COMPUTER PROGRAMMING
}
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()
{
int len, width;
printf(“\n Enter length: “);
scanf (“%d “, &len);
printf(“\n Enter width : ” );
scanf( “ %d “, &width);
printf(“\n The area is %d “, len * width);
return 0;
}
Exercises
Types of Variables
There are two places where variables are declared: inside a function or outside all 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.
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 aware of two important points
about local variables.
(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 variables are completely separate from and unrelated to
one another.
(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.
Constants
26
COMPUTER PROGRAMMING
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.
Integer constants are specified as numbers without fractional components. For example –10,
1000 are integer constants.
Floating - point constants require the use of the decimal point followed by the number’s
fractional component. For example, 11.123 is a floating point constant. C allows you to use
scientific notation for floating point numbers. Constants using scientific notation must follow
this general form:
number E sign exponent
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 1234.56 using scientific notation.
123.456E1
Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'.
ch = ‘z’;
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 two assignments
are equivalent.
char ch;
ch = “A’;
ch = 65;
Types of Constants
Constants can be used in C expressions in two ways:
Directly
Here the constant value is inserted in the expression, as it should typically be.
For example:
Area = 3.14 * Radius * Radius;
The value 3.14 is used directly to represent the value of PI which never requires changes in the
computation of the area of a circle
27
COMPUTER PROGRAMMING
A symbolic constant is an identifier that is replaced with replacement text by the C preprocessor before
the program is compiled. For example, all occurrences of the symbolic constant SIZE are replaced with
the replacement text 10.
This process is generally referred to as macro substitution. The general form of the #define statement is;
#definemacro-name string
Notice that this line does not end in a semi colon. Each time the macro - name is encountered in the
program, the associated string is substituted for it. For example, consider the following program.
28
COMPUTER PROGRAMMING
#include<stdio.h>
#define PI 3.14
main()
{
float radius, area;
printf(“Enter the radius of the circle \n”);
scanf(“%f”, &radius);
area = PI * radius * radius; /* PI is a symbolic constant */
printf(“Area is %.2f cm squared“,area);
return 0;
}
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. The preprocessor does not convert a number into any sort of internal format.
This is left to the compiler.
Revision Exercises
1. Discuss four fundamental data types supported by C, stating how each type is stored in memory.
2. Distinguish between a variable and a constant.
3. Suggest, with examples two ways in which constant values can be used in C expression
statements.
4. Give the meaning of the following declarations;
(i) char name[20];
(ii) int num_emp;
(iii) double tax, basicpay;
(iv) char response;
29
COMPUTER PROGRAMMING
OPERATORS
Operators And Operands
An operator is a component of any expression that joins individual constants, variables, array elements
and function references.
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).
Examples
(i) x + y ; x, y are operands, + is an addition operator.
(ii) 3 * 5; 3, 5 are constant operands, * is a multiplication operator.
(iii) x % 2.5; x, 5 are operands, % is a modulus (remainder) operator.
(iv) sizeof (int); sizeof is an operator (unary), int is an operand.
Arithmetic Operators
There are five arithmetic operators in C.
Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder after integer division
Note:
(i) There exists no exponential operators in C.
(ii) The operands acted upon by arithmetic operators must represent numeric
values, that is operands may be integers, floating point quantities or characters
(since character constants represent integer values).
(iii) The % (remainder operator) requires that both operands be integers.
Thus;
5%3
int x = 8;
int y = 6 ; x % y are valid while;
8.5 % 2.0 and
float p = 6.3, int w = 7 ; 5 %p , p % w are invalid.
(iv) Division of one integer quantity by another is known as an integer division. If the
quotient (result of division) has a decimal part, it is truncated.
30
COMPUTER PROGRAMMING
(v) Dividing a floating point number with another floating point number, or a
floating point number with an integer results to a floating point quotient .
Exercise
Suppose a = 10, b = 3, v1 = 12.5, v2 = 2.0, c1 =’P’, c2 = ‘T’. Compute the result of the following
expressions.
a+b v1 * v2
a-b v1 / v2
a*b c1
a/b c1 + c2 +5
a%b c1 + c2 +’9’
Note:
(i) c1 and c2 are character constants
(ii) ASCII codes for 9 is 57, P = 80,T = 84.
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 their usual rules of algebra. Thus if
a b, and c are 11, -3 and –11 respectively, then
a+b =8
a – b = 14
a * b = -33
a / b = -3
a % b = -2
c % b = -2
c/b=3
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 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 other is a
character or integer (including short or long integer), the character or integer will be
converted to the floating point type and the result will be expressed as such.
31
COMPUTER PROGRAMMING
(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 and a
long int, the long int will be taken).
(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:
Operator Precedence
The order of executing the various operations makes a significant difference in the result. C assigns each
operator a precedence level. The rules are;
(i) Multiplication and division have a higher precedence than addition and subtraction, so they
are performed first.
(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.
32
COMPUTER PROGRAMMING
Note that it is possible for the programmer to set his or her own order of evaluation by putting, say,
parenthesis. Whatever is enclosed in parenthesis is evaluated first.
Exercise
Write a program that calculates the two roots x1 x2 with double precision, and displays the roots on the
screen.
33
COMPUTER PROGRAMMING
printf(“ Converting seconds to minute and seconds \n “) ;
printf( “Enter number of seconds you wish to convert \n “) ;
scanf(“% d” , &sec ) ; /* Read in number of seconds */
min = sec / SEC_PER_MIN ; / * Truncate number of seconds */
sec_left = sec % SEC_PER_MIN ;
printf(“% d seconds is % d minutes,% seconds\n “ ,sec,min,sec_left);
return 0;
}
The sizeof operator
sizeof returns the size in bytes, of its operand. The operand can be a data type e.g. sizeof (int), or a
specific data object e.g. sizeof n.
If it is a name type such as int, float etc. The operand should be enclosed in parenthesis.
Assignment expressions that make use of the assignment operator (=) take the form;
identifier = expression;
where identifier generally represents a variable, constant or a larger expression.
Examples of assignment;
a=3;
x=y;
pi = 3.14;
sum = a + b ;
area_circle = pi * radius * radius;
34
COMPUTER PROGRAMMING
Note
(i) You cannot assign a variable to a constant such as 3 = a ;
(ii) The assignment operator = and equality operator (= =) are distinctively different. The
= operator assigns a value to an identifier. The equality operator (= =) tests whether
two expressions have the same value.
(iii) Multiple assignments are possible e.g. a =b = 5 ; assigns the integer value 5 to both a
and b.
(iv) Assignment can be combined with +, -, /, *, and %
evaluate expression1. If expression1 evaluates to true ( value is 1 or non zero) then evaluate
expression 2, otherwise (i.e. if expression 1 is false or zero ) , evaluate 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.
Unary Operators
These are operators that act on a singe operand to produce a value. The operators may precede the
operand or are after an operand.
Examples
(i) Unary minus e.g. - 700 or –x
(ii) Incrementation operator e.g. c++
(iii) Decrementation operator e.g. f - -
(iv) sizeof operator e.g. sizeof( float)
Relational Operators
35
COMPUTER PROGRAMMING
= = Equal to
!= Not equal to
A logical expression represents conditions that are either true (represented by integer 1) or
false (represented by 0).
Example
Consider a, b, c to be integers with values 1, 2,3 respectively. Note their results with relational operators
below.
Expression Result
a<b 1 (true)
(a+ b) > = c 1 (true)
(b + c) > (a+5) 0 (false)
c:=3 0 (false)
b==2 1 (true)
Logical operators
The two operators act upon operands that are themselves logical expressions to produce more complex
conditions that are either true or false.
Example
Suppose i is an integer whose value is 7, f is a floating point variable whose value is 5.5 and C is a
character that represents the character ‘w’, then;
Revision Exercises
36
COMPUTER PROGRAMMING
Further suppose that c1, c2, c3 are character-type variables assigned the values E, 5 and ? respectively.
37
COMPUTER PROGRAMMING
Introduction
Control structures represent the forms by which statements in a program are executed.
This is the simplest control structure. It dictates the order of execution from one statement to the next
within the program. In the absence of repetition or branching, the program instructions will be
executed in the order in which they were coded.
Basically, program statements are executed in the sequence in which they appear in the program.
The structure is used for decision making within a program. It allows alternative actions to be taken
according to conditions that exist at particular stages within a program.
The structure uses a test condition statement, which upon evaluation by the computer gives rise to
certain conditions which may evaluate to a Boolean true or false. Based on the outcome of the test
condition, the computer may execute one or more statements.
In reality, a logical test using logical and relational operators may require to be used in order to
determine which actions to take (subsequent statements to be executed) depending on the outcome of
the test. This is selection. For example:
In addition, a group of statements in a program may have to be executed repeatedly until some
condition is satisfied. This is known as looping. For example, the following code prints digits from 1 to 5.
for(digit = 1; digit < = 5; digit++)
printf(“\n %d”, digit)
Selection Structure
The if statement
The if statement provides a junction at which the program has to select which path to follow. The
general form is :
38
COMPUTER PROGRAMMING
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 quantities ( For example x > y
or c = = 6)
Examples
(i) if (x<y)
printf(“x is less that y”);
The statement in the if structure can be a single statement or a block (compound statement).
If the statement is a block (of statements), it must be marked off by braces.
if(expression)
{
block of statements;
}
Example
if(salary>5000)
{
tax_amt = salary *1.5;
printf(“Tax charged is %f”, tax_amt);
}
if - else statement
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 compound) or skipping it.
39
COMPUTER PROGRAMMING
If expression is true, statement1 is executed. If expression is false, the single statement following the
else (statement2) is executed. The statements can be simple or compound.
Example:
if(x >=0)
{
printf(“let us increment x:\n”);
x++;
}
else
printf(“x < 0 \n”);
if (expression)
statement;
else if (expression)
statement;
else if (expression)
statement;
else
statement;
Example
if(sale_amount>=10000)
Disc= sal_amt* 0.10; /*ten percent/
else if (sal_amt >= 5000 && sal_amt < 1000 )
printf (“The discount is %f “,sal_amt*0.07 ); /*seven percent */
40
COMPUTER PROGRAMMING
else if (sal_amt = 3000 && sal_amt < 5000)
{
}
else
printf ( “ The discount is 0”) ;
41
COMPUTER PROGRAMMING
#include<stdio.h >
#include<string.h >
main()
{
int marks;
char grade [15];
printf (“ Enter the students marks \n”);
scanf( “%d “,&marks ) ;
if ( marks > =75 && marks <=100)
{
strcpy(grade, “Distinction”); /* Copy the string to the grade */
printf(“The grade is %s” , grade);
}
else if( marks > = 60 && marks < 75 )
{
strcpy(grade, “Credit”);
printf(“The grade is % s” , grade );
}
else if(marks>=50 && marks<60)
{
strcpy(grade, “Pass”);
printf(“The grade is % s” , grade );
}
else if (marks>=0 && marks<50)
{
strcpy(grade, “Fail”);
printf (“The grade is % s” , grade) ;
}
else
printf(“The mark is impossible!” );
return 0;
42
COMPUTER PROGRAMMING
}
The switch - break statements can be used in place of the if - else statements when there are several
choices to be made.
43
COMPUTER PROGRAMMING
printf(“Your choice is out of range”);
return (0);
} /* End of main*/
Explanation
The expression in the parenthesis following the switch is evaluated. In the example above, it has
whatever value we entered as our choice.
Then the program scans a list of labels (case 1, case 2,…. case 4) until it finds one that matches the one
that is in parenthesis following the switch statement.
If there is no match, the program moves to the line labeled default, otherwise the program proceeds to
the statements following the switch.
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 matched label to the end of the
switch will be processed.
For example if we remove all the break statements from the program and then run the program using
the number 3 we will have the following exchange.
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.
44
COMPUTER PROGRAMMING
(iii) The expressions in the parenthesis should be one with an integer value. (again including type
char)
#include<stdio.h>
main()
{
char ch;
printf(“Give me a letter of the alphabet \n”);
printf(“An animal beginning with letter”);
printf (“is displayed \n “);
scanf(“%c”, &ch);
if (ch>=’a’ && ch<=’z’) /*lowercase letters only */
switch (ch)
{ /*begin of switch*/
case `a`:
printf(“Alligator , Australian aquatic animal \n”):
break;
case ‘b’:
printf(“Barbirusa, a wild pig of Malaysia \n”);
break;
case ‘c’:
printf(“Coati, baboon like animal \n”);
break;
case ‘d’:
printf(“Desman, aquatic mole-like creature \n”);
break;
default:
printf(“ That is a stumper! \n”)
}
else
printf(“I only recognize lowercase letters.\n”);
45
COMPUTER PROGRAMMING
return 0;
} /* End of main */
Like the break statement the continue statement is a jump that interrupts the flow of a program. It is
used in loops to cause the rest of an iteration to be skipped and the next iteration to be started.
Example
goto part2;
part2: printf(“programming in c”\n”;)
In principle you never need to use goto in a C statement. The if construct can be used in its place as
shown below.
Alternative 1 Alternative 2
if (a>14) if (a>14)
goto a; sheds=3;
sheds=2; else
goto b; sheds=2;
a: sheds=3; k=2*sheds;
b: k=2 * sheds;
46
COMPUTER PROGRAMMING
The while statement is used to carry out looping instructions where a group of instructions executed
repeatedly until some conditions are satisfied. This is a pretest loop in that the test condition is placed
before the statement block that is to be repeatedly executed. The computer evaluates the test
condition statement and as long as it returns the Boolean value of true the statement block is executed
then control returns to the test condition statement for re-evaluation. Repetition will terminate when
the test condition statement returns false.
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 */
/* Displays the digits 1 through 9 */
main()
{
int digit=0; /* Initialisation */
while (digit<=9)
{
printf(“%d \n”, digit);
digit++;
}
return 0;
}
Algorithm:
(i) Initialise an integer count variable to 1. It will be used as a loop counter.
(ii) Assign a value of 0 to the floating-point sum.
(iii) Read in the variable for n (number of values)
(iv) Carry out the following repeatedly (as long as the count is less or equal to n).
(v) Read in a number, say x.
(vi) Add the value of x to current value of sum.
(vii) Increase the value of count by 1.
47
COMPUTER PROGRAMMING
(viii) Calculate the average: Divide the value of sum by n.
(ix) Write out the calculated value of average.
Solution
(Note that using the while loop, the loop test is carried out at the beginning of each loop pass).
In this structure the test condition is placed after the block of code that is to be repeatedly executed.
The computer first executes the block of code then evaluates the test condition statement.
48
COMPUTER PROGRAMMING
General form:
do
statement;
while(expression);
The statement (simple or compound) will be executed repeatedly as long as the value of the expression
is true. (i.e. non zero).
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 */
/* Displays the digits 1 through 9 */
main()
{
int digit=0; /* Initialisation */
do
{
printf(“%d \n”, digit);
digit++;
} while (digit<=9);
return 0;
}
Exercise: Rewrite the program that computes the average of n numbers using the do while
loop.
General form:
for (expression1;expression2;expression3)
statement;
where:
expression1 is used to initialize some parameter (called an index). The index controls the loop action. It
is usually an assignment operator.
49
COMPUTER PROGRAMMING
expression2 is a test expression, usually comparing the initialised index in expression1 to some maximum
or minimum value.
expression3 is used to alter the value of the parameter index initially assigned by expression and
is usually a unary expression or assignment operator);
Example
Output
0
1
2
3
4
5
50
COMPUTER PROGRAMMING
main()
{
int n, count;
float x, average, sum=0.0;.
51
COMPUTER PROGRAMMING
}
Also note the following points about the for structure.
You can count down using the decrement operator
You can count by any number you wish; two’s threes, etc.
You can test some condition other than the number of operators.
A quantity can increase geometrically instead of arithmetically.
Nesting statements
It is possible to embed (place one inside another) control structures, particularly the if and for
statements.
Example
if (number>6)
if (number<12)
printf(“You are very close to the target!”);
else
printf(“Sorry, you lose!”);
52
COMPUTER PROGRAMMING
/*Read in the number of loops */
printf(“How many lists? “);
scanf(“%d”, &loops);
/*Outer loop processes each list of numbers */
for (loopcount=1; loopcount<=loops; loopcount++)
{
/* initialise sum and read in a value of n */
sum=0.0;
printf(“List number %d \n How many numbers ? “,loopcount);
scanf(“%d”, &n);
/*Read in the numbers */
for(count=1;count<=n; count++)
{
printf(“x = “);
scanf(“%f”, &x);
sum+=x;
} /* End of inner loop */
/* Calculate the average and display the answer */
average = sum/n;
printf(“\n The average is %f \n”, average);
} /*End of outer loop */
return 0;
}
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.
0 > Purchase Amount < Ksh. 3,000 - Pay full amount.
2. Write a program that asks for the customer’s purchase amount, then uses ifstatements to
recommend the appropriate payable amount. The program should cater for negative purchase
amounts and display the payable amount in each case.
3. In what circumstance is the continue statement used in a C program?
53
COMPUTER PROGRAMMING
4. Using a nested if statement, write a program that prompts the user for a number and then reports if
the number is positive, zero or negative.
5. Write a while loopthat 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 less than 30.
ARRAYS
54
COMPUTER PROGRAMMING
Introduction
It is often necessary to store data items that have common characteristics in a 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?
An array is a homogeneous ordered set of elements or a series of data objects of the same type stored
sequentially. That is to say that an array has the following characteristics;
Example
Because the array is declared as type float, each element can be assigned a float value such as debts[5]
= 32.54;
Other examples;
int emp_no[15]; /*An array to hold 15 integer employee numbers */
char alpha [26]; /*an array to hold 26 characters */
Declaring Arrays
55
COMPUTER PROGRAMMING
Examples:
(ii) staticchar message[20]; A 20 character-type array called message. The individual array values persist
within function calls (static).
Array Dimensions
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 between 0
to (array size -1).
(ii) Multi dimensional arrays
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.
An m by n two-dimensional array can be thought of as a table of values having m rows 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];
Static double records[100][60][255];
Example
Two-dimensional array representing sales ( ‘000 tonnes for a product in four months for five years).
Yr1 Yr2 Yr3 Yr4 Yr5
Month 1 23 21 27 23 22
Month 2 24 20 19 18 20
Month 3 26 23 26 29 24
Month 4 27 25 24 23 25
An automatic array is one defined inside a function including formal arguments. C allows us to initialise
automatic array variables as follows.
main()
56
COMPUTER PROGRAMMING
{
Because the array is defined inside main, its an automatic array. The first element marks[0] is
assigned the value of 30 , marks[1] as 40 and so on.
They
(i) are known to all functions following them in a file e.g. from above, both main ( ) and feed ( ) can
use and modify the array SOWS.
(ii) Persist (retain values) as long as the program runs. Because they are not defined in any
particular function, they don’t expire when a particular function terminates.
----------
----------
int feed(int n)
{
---------
---------
(iii) A static array is local to the function in which it is declared but like an external array, it retains its
values between function calls and is inititialised to zero by default.
Example
57
COMPUTER PROGRAMMING
---------
}
Initialising Arrays
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 initialisation for a one-
dimensional array is shown below.
The value list is a comma separated list of constants that are type compatible with the base
type of the array. The first constant will be placed in the first position of the array, the second
constant in the second position and so on. Note that a semi colon follows the }.
In the following example, a five – element integer array is initialised with the squares of the number 1
though 5.
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 quoted string, as
shown here.
Notice that no curly braces surround the string. They are not used in this form of initialisation. Because
strings in C must end with a null, you must make sure that the array you declare is long enough to
include the null. This is why name is 6 characters long, even though “Peter” is only 5 characters. When
a string constant is used, the compiler automatically supplies the null terminator.
For example, here the array sqr is initialised with the values 1 though 9, using row order.
58
COMPUTER PROGRAMMING
This initialisation causes sqr[0][0] to have the value 1, sqr[0][1] to contain 2, sqr[0][2] to contain 3,
and so forth.
If you are initialising a one-dimensional array, you need not specify the size of the array, simply put
nothing inside the square brackets. 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.
For example int p[] = {1,2,4,8,16,32,64,128}; causes the compiler to create an initialised array eight
elements long.
Arrays that don’t have their dimensions explicitly specified are called unsized arrays. An unsized array is
useful because it is easier for you to change the size of the initialisation list without having to count it
and then change the array dimension dimension. This helps avoid counting errors on long lists, which is
especially important when initialising strings.
If at a later date, you wanted to change the prompt to “Enter your last name: “ , you would not have to
count the characters and then change the array size.
For multi dimensional arrays, you must specify all but the left dimension to allow C to index the array
properly. In this way you may build tables of varying lengths with the compiler allocating enough storage
for them automatically.
For example, the declaration of sqr as an unsized array is shown here.
int sqr[][3] = {
1, 2, 3,
4, 5, 6,
7, 8, 9
};
The advantage to this declaration over the sized version is that tables may be lengthened or shortened
without changing the array dimensions.
59