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

Structured Programming Notes

structured-programming-notes

Uploaded by

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

Structured Programming Notes

structured-programming-notes

Uploaded by

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

INTRODUCTION TO STRUCTURED PROGRAMMING

TERMINLOGIES
I. Computer hardware- It is the physical part of the computer that you can see
and touch.
II. Computer software- It is a set of instructions that instruct the computer
hardware on what to do and how to do it.
III. Program/software- It is a set of instructions that instruct the computer
hardware on what to do and how to do it.
IV. Programming- It is the act of developing software to carry out specific task.
V. Programming language-It is a language used in programming.

Classification of soft wares


There are three major classifications of computer software’s
i. System software
ii. Application software
iii. Programming languages

SOFTWARES

Application Programming
System Software languages
Software

Application
System Operating Inhouse/Tai Lowlevel High level
Firmware package/off
utilities system lormade languages languages
shelve

-merge MS OFFICE -voter registraition uses english like


-windows
-copy -word processing system statement
03,07,08,xp
-backup -spreadsheets -school mgt -machine language
-linux -POST -c
-loader -Desktop system -Assembly
-unix -BIOS -c++
-translators publishing -hospital mgt language
-novel -pascal
-presentation system -vb
-solaries
software -Java

VI.

1 Compiled by Mr.Rutoh Mike


ENTER/EDIT THE PROGRAM

SAVE

SOURCE FILE (CCP)

COMPILE

OBJECT(OBJ) FILE
FAIL
CORRECT
ERRORS
LINK

EXECUTABLE (EXE) FILE

HISTORY OF PROGRAMMING LANGUAGES

2 Compiled by Mr.Rutoh Mike


Many programming languages have been developed over the years. These are classified into two
major languages namely:

(a)Low level languages

(b)High level languages

These two levels are further sub-classified into 5 generations. The first and the second
generation consist of low level whilst 3rd to 5th generation consist of high level languages

(1)Low level languages

These are classified as low level because they can be easily understood directly or they require
little effort to translate into computer understandable form. There are two types of low level
languages:

(i)Machine languages

(ii)Assembly languages

(I)Machine Language

Digital computers represent and process data instruction using binary numbers (0, 1).Machine
language make use of zeros and ones program statement appearing as a long string of binary
digits.

With Machine language execution is direct since machine language needs no translation. It
occupies little computer memory .Machine language was created by the computer maker and
was sold with machine.

Advantages of Machine language

(i)Program executed was passed because no translation process was required.

(ii)The program would directly address and control internal circuitry of hardware usage and
control

(iii)It uses very little computer memory.

Disadvantages of Machine language

(i)Writing program was extremely time consuming since each instruction was made up of
binary digits.

(ii)Tracing of errors was extremely difficult.

(iii)Program modification was cumbersome; it calls for rewriting the whole program.

(iv)Program written in Machine language is machine dependent

(v)They are extremely difficult to learn and use.

3 Compiled by Mr.Rutoh Mike


(II) Assembly language

These were developed in order to overcome the difficulties of understanding and using the
machine language. Assembly language is a language that makes use of Mnemonics. An
Assembler translates assembly language to machine language i.e translate low level language
into high level language.

Examples

Binary Assembly language High level

01001100 Movbx offset value x=z

1101001 Mov ax [5x] if(x<=y)

10101010 Add ax,5 x=x+1

Advantages of Assembly language

(i)Compared to Machine language, Assembly language is much easier to learn and use.

(ii)Coding takes less time than machine language.

Disadvantages of Assembly language

(i)They are machine specific language; programmers to use Assembly language must be an
expert.

(ii)Execution of Assembly language takes a lot of time because of translation.

(iii)Locating errors and correcting still a major problem.

(2)High level languages

These are languages which move from Machine to dependent and focus their strength on
problem oriented and user. Programs are instructions that are written in English or
Mathematical statement e.g if x<=y, x=x+1, x=z.

They are design to reduce ambiguity and has developed in late 1950s.It needs translations by
use of compilers and interpreters.

Advantages of high level languages

(i)Program code is shorter than Assembly language and Machine language.

(ii)They used English like statement hence programmers focus on the functional details of
program rather than h/w detail.

(iii)The data are given names described as variables that are descriptive in nature hence
promote debugging.

4 Compiled by Mr.Rutoh Mike


(iv)High level languages are self-documenting hence promote readability.

(v)The program of high level language can be easy to adapt to a new h/w because there is no
need to worry of h/w designs.

(vi)Programmers can easily train using high level language.

Disadvantages of high level languages

(i)The source program written in high level language needs a compiler which should be loading
to the main memory of the computer language hence occupying a lot of space.

(ii)High level instructions be translated into machine instructions takes a lot of computer time.

(iii)Tends to be less efficient in the use of CPU by being machine oriented i.e more machine
codes instructions are produced so more time is taken to run the program.

(1)3rd Generation Language:


Are problem oriented language .Program instructions can be run in any family of computers
provided that the program on instructions is stored in the original source code.
3rd generation language allow problem solution to be specified in human language form also
referred to as structured programming.
Structural programming approach emphasizes the following;
(i)Large programs can be broken into smaller sub-programs each performing a single task.
(ii)Use of a few simple control structures in solving problems. These control structures include:
(a)Sequence
(b)Selection
(c)Iteration 
Structured programming offers many benefits because it is flexible, easier to read and modify.
Examples of 3rd generation programming language are:
(i) Pascal
(ii) Fortran
(iii) Cobol
(iv) Basic
(v) C
(vi) AdA

N/B: 3rd generation languages are also called Structured or procedural language. A procedural
language makes it possible to break a program into components called modules each
performing a particular task.

(2)4th Generation Language:

(i)They are user oriented language

(ii)They are mainly used to enquire database system and they are called query language.

(iii)They are easy to learn and understand because they are user based

(iv)The language syntax or grammar is nature near normal English.

5 Compiled by Mr.Rutoh Mike


(v)They make use of menus and prompts to guide non-specialist to retrieve data with a lot of
ease.

(vi)Very little training is essential before this language program can be used. 

(3)5th generation language:They are the languages that are still in state of development even
source companies have come up with 5th generation language .Programming language
(programming logic) is an example of 5th generation language and is used in the following:

(a)Scientific language: They are languages that contain facilities that support scientific and
Engineering Applications.

(b)They are commercial language:i.e

(i)General purpose language –These are languages that display features of commercial
e.g Pascal

(ii)Procedural language – It accomplishes a specified task program execution and follow


the exact sequence laid down during coding. Deviation from the laid down sequence cannot
occur unless they have been gathered during coding.

(iii)Non procedural language –This allows the programmer to specify the closure results
without having to specify the detail procedures need to achieve the results .procedural language
is oriented to how the results can be produced whilst non procedural language is oriented to
what the results is required.

computer hardware and software consideration

Factors to be considered when choosing computer hardware /hardware


consideration

(1) Warranty: When you buy a computer, you do not except to break but sometimes things
do go wrong and it is advisable to have a protection of some kind. A new computer
usually comes with warranty. When you get a warrant, the seller or manufacturer of
the computer agrees to repair or replace it if something go wrong during the given time
frame.
(2) Expansion/Upgrading: When you buy a computer system, the specification are usually
enough to meet the current requirements. But as time goes on you find that it is not big
or fast enough at this point. There are two options:
(a) Buy the entire system which is expensive
(b) Upgrade the existing system which is usually cheaper
(3) User needs: Focus around what the main reasons are for buying the computer system.
(4) Cost: This calls for how much money you are willing to spend in purchasing the
machine.

6 Compiled by Mr.Rutoh Mike


(5) Compatibility: It is important to ensure that the new computer system that is
purchased can interact with the existing hardware that is compatible. This is important
especially in network environment where the computer must communicate with other
computers on the network.
(6) Portability: If you travel a lot and you need to access your computer and files you are or
your job may require having files available at the client’s side, then you need a
computer that you can carry with you eg laptop or handheld device depending on the
power and storage capacity requirements.
(7) Processing speed and Memory capacity
Factors to consider when choosing software/software consideration
(1) Cost: Cost of software is a major contributing factor in deciding whether to purchase
general or not. Usually cheaper to purchase general purpose s/w in circumstances
where it is able to meet the user requirements.
(2) Compatibility: When upgrading s/w it is essential that upgrades are backward
compatible eg Microsoft Access 2000(Database) can convert to Access 97.
(3) Documentation: It is important and should tell whether the program can be used to
solve your particular problem as well as providing the user with a program.
(4) Authenticity: It is how genuine is the software.
(5) User needs: What you want to use the computer for eg banking or Accounting.
(6) User friendliness: How good the s/w should be, the one that allows one to learn and
think own their own and should have help facilities eg the manual.
(7) System requirement: Some of the needs that the user wants to achieve using the
computer system.

PROGRAMMING PARADIGMS

(1) Unstructured programming:

The process of designing program without the use of structured steps is referred in strictly
sequential manner, each executed exactly once. In this approach, programmers put all their
code in one place or say in one program. This approach is totally useless if working on large
project.

(2) Structured programming:

It helps break it down into smaller chunks (modules) which mean the amount of code that the
programmer has to deal with for any one module is much less than deciding with the system as
a whole.

(3) Visual programming: These are languages that have extra features to allow
programming application to use components of visual language eg Visual
interface, Multiple document and object linking & embedding (OLE). Is the
creation of computer programs by utilizing pictorial element. Visual language
manipulates visual information or support visual interaction or programming
with visual expression.

7 Compiled by Mr.Rutoh Mike


(4) Internet based programming: Internet program is a programming techniques
which allows connection to internet server by use of internet server. API or
windsock or any other wrapper classes provided by any third particular thus
type of programs may be able to send and received pocketed data across
network. These are not all programming languages and this list does not have
every web programming languages possible on it but this is generally (in no
particular order) what you will encounter in the world web design
development or whatever else you want to call making things online. This list
is more like what you would see in a job description or on a resume as
opposed to purely being a list of programming languages eg html, php,
javascript etc.

PROGRAM DEVELOPMENT AND DESIGN

(1)PROGRAM DEVELOPMENT:

In program you must solve a particular problem or accomplish a task hence therefore
developing a program, the requirement of the eventual user and its expected function should be
fully understood. A program development can be broken into the following stages:-

(i) Problem recognition


(ii) Problem definition
(iii) Program design
(iv) Program coding
(v) Program testing & debugging
(vi) Implementation & maintenance
Documentation
Problem
recognition
Problem
definition
Program
design
Program
coding
Program
testing
Program
implementation

Explanation:

8 Compiled by Mr.Rutoh Mike


Arrows show the next step in order of the program development.

The downward reversed arrows show a review of one step with previous to see
whether specification has been met.

(2) PROGRAM DESIGN:

A program design is an actual development of the program processing or problem solving logics
called a

Algorithm.

Algorithm: It is a step by step instruction that produce a solution to a problem. The design phase
enables the programmer to come up with models of expected programs

The models show the flow of events and data throughout the entire program from the time data
is input to the time program gives out expected information.

PROGRAM DEVELOPMENT CYCLE

This is the cycle stage in programming .These stages are:-

(a) Problem understanding


(b) Planning methods of solution
(c) Developing the methods using suitable Aids
(d) Coding stage (typing or keying the instructions into the computer program)
(e) Testing
(f) Document
(g) Maintenance
(1) Problem understanding: The programmer needs to know exactly what the program is
needed to do in most cases understanding the problem is derived from program
specifications.Program specification is normally part of the system of which program
may only play a small part .Broadly speaking, program specification may define input
processing and output.In program development life cycle, understanding the problem at
hand is simply defining the problem saying exactly what the problem is.
(2) Planning methods of solution: Depending on the extend of the activities, program
preparation may be done by one person or shared by a programmers. Incase a number
of programs, proper planning must be done. Large programs may require each
programmer to write a separate part of the program. This separate part of this is often
called modules or segments. These modules may be prepared and tested separately then
they are linked together to be tested as a unit.
(3) Developing the methods using suitable Aids: Modern approach to programming
recognize the fact that complicated problems can be solved mostly if they are broken
into simpler, more manageable task in step by step version. At each step, problems can
be broken down into further considering the necessary details where possible. This
general approach is called step down program/step down-refinement. At this stage
appropriate algorithm must be choosen depending on the problem at hand.
(4) Coding stage: It is the process of typing instructions in programming languages. This
stage should be purely mechanical. The instructions written or developed in algorithm is
put in a computer sensible form using program language.

9 Compiled by Mr.Rutoh Mike


There are different types of programming that can be used. Initially, programming
instructions were written in special form called coding sheet. Now days coding sheets are
not common because most programmers type their own language.

(5) Testing: Once the program has been written the program has to be subjected to various
test to check if they have been written out correctly and transcribed correctly at the
same time to check whether it does exactly what is expected to be done (whether it is
correct). It is good practice to test each component of the program produced as well as
testing computed programs.

Types of testing

(1) Unit testing: This involves testing the separate component of the program as they are
produced.
(2) Integrated testing: This involves testing the whole program once it is in the final form.
(3) System testing: This involves testing the whole system after integration.
(4) User acceptance testing: This involves the user of the program testing the program. The
program must do what is expected to do.

N/B: The data to be used for testing the program can be

(1) Real Data


(2) Dummy Data
(a) Real Data: Real data is the actual data that comes from the user
(b) Dummy data: it is the imaginary data normally supplied by analyst and programmers.

Methods of error testing

(1) Desk checking (Dry-run): It involves going through the program while on paper before
entering it in the program editor. This helps the programmer to detect the most
obvious syntax and logical errors.
(a) Syntax error: Is the error emanating from improper use of language eg
grammatical mistakes, punctuation, improper naming of variables and
spelling of user defined and reserved words.
(b)Logical error: Is an error not detectable by the translator; the program
runs but gives out wrong output and halts during program execution. Such
errors that occur during execution are sometimes called Runtime or
Execution errors.

(2) Using Debugging utilities: After entering the program editor, you can run the debugging
during translation to detect the syntax errors in order to correct them before execution.

(3) Using test data: The programmer carries out trial run of the new program> At each run the
programmer enters various variations and at times including data with errors to test whether
the system will grind to halt.

(6).Documentation: It is very important stage that the work of the programmer is produced in
awritten form. A completed program must be fully documented

10 Compiled by Mr.Rutoh Mike


Documentation may include the following:-

(a) Statement of the problem system documentation


(b) It should have algorithm
(c) It should have coding sheet
(d) It should have test data and reserves
N/B: producing this document should be done at each step and not after thought.

All stages of the program development should be documented in order to help during future
modification of the program. Documentation can be either internal or external.

(i)Internal documentation: It is written, non-executable lines (comments in the source


program that help other programmers to understand the code statement).
(ii) External documentation: Refers to the reference materials such as users manuals
printed as booklets. User manuals are common example of external documentation.
There are three target groups of any type of documentation;
(a) User oriented documentation: This type enables the user to learn how to use the
program as quickly as possible and little help from program developer.
(b) Operator oriented documentation: It is meant for computer operators such as the
technical staff. It helps to install and maintain the program.
(c) Program oriented documentation: It is detailed documentation written for skilled
programmers. This documentation provides necessary technical information to help
the future modification of the program. In this type of documentation, all the stages
of the program development should be documented because:-
(i)They may be a need to reserve and modify the program
(ii)Other programmers may think of ways of improving the program.
PROGRAM SPECIFICATION
This is the definition of input processing steps and output requirements of the program. A good
specification specify that input are expected ,what processing is needed by giving exact
relationship between I/O and what output should attain first. It is the work of system analyst to
write the program specification. Program specification guides the programmers in providing
instructions to computer system. Programs are written from program specification.
Specification gives programmers a good framework within which to work. The framework is
much like architecture, a rough sketch of the house.
The programmers must work from the sketch to provide detailed structure that can be
transformed in the computer program.

STRUCTURED PROGRAMMING

Structured programming was developed in 1960’s by Nicklaus writh but its use in 1980’s. It is
because as the program became more and more complicated and lack of structuring made it
difficult to understand and maintain into understandable chunks called modules. Structuring
design cannot reduce the overall complexity of the system but it breaks into chunks which can
be dealt with easily. The process of reducing components into sequence of components is
known as structured programming.

Types of structured programming;-

I. Modularity (modular design)


II. Jackson’s structured programming

11 Compiled by Mr.Rutoh Mike


III. Bottom-up design/structured
IV. Monolithic design.

(1) Modularity/Modular design: Modular is a small creation of a program. It is the process


of splitting a program into smaller sections called chunks which will promote
understandability.
Importance of using modules:
(a) It reduces the effort required later to change the program since changes are only
made in specified modules.
(b) Testing and removal of errors is achieved easily.

Rules for modularization:

(a) Each module should contain one program function


(b) The maximum instruction by module should not exceed 100 instructions.
(c) Each module should take entry and exit point.

Advantages of using modules:

i. Modules can be reused in program thus saving divert time


ii. Testing individual module in isolation making tracking of mistakes easier.
iii. Amendment to single module do not affect the rest of the program
iv. Ability to create libraries of often used routines
v. Modules can be named in such a way that is easy to finalize hence assist in
documentation.

Disadvantage of modules:

i. They have limited number of instructions’

(2) Jackson’s structured programming:

It is the type of data structure by Michael Jackson. It makes used of 3 Structure diagram called
Notation.

(a) Notation for sequence


(b) Notation for iteration
(c) Notation for selection

(1) Notation for sequence


Start
12 Compiled by Mr.Rutoh Mike
Flowchart:

A
Input

Process

Output
B C

stop

Component A is the sequence of B&C which represent components:


parts of sequence no further definition is given hence no structure of
their own. A is the sequence of the two components followed by Notation for iteration (repeat).

(2) Notation for iteration:


Flowchart

Start E

Decision
F X
Test

Loop body

Component box E is iteration. Box F is the iteration component part E is the iteration number of
times (possible) zero of F. The number of F is controlled by specified number

13 Compiled by Mr.Rutoh Mike


(3) Notation for selection:
Flowchart
X
Start

Decision

Y Z

Process Process

Stop

Box X is selection. Box Y & Z are compounds


Part of selection X is
Selection choice of Y, the
Condition of Y is specified if this condition is not
True, Z is chosen.

(4) Bottom-up design: It starts solving the smaller tasks till the larger task.
(5) Top-down design: Sub divide the program into major task is solved. The process of
reducing into sequence of smaller components is often called stepwise refinement of the
structured programming. Top- down design approach allows a program to be designed
methodically by providing a complete definition of the program at each level of
complexity.

N/B: An outline program is design first showing the main task or component of the program
and order in which they are to be executed. Each main component is reduced to a number of
smaller, simpler and more manageable components and this process continues at each level
until there is sufficient detail to allow the coding stage to proceed.

(6)Monolithic design: It is the process of designing any procedure eg analysis, coding,


testing and debugging.

PROGRAM DESIGN TOOLS:

14 Compiled by Mr.Rutoh Mike


(1)Algorithm: It is a series of step by step instruction that produce a solution to a problem.

(2)Flowchart: It is the pictorial representation of a program logic

Steps to be followed when designing a flowchart

(a) Design on Algorithm representing a solution of a problem.


(b) Representing this Algorithm using any tool to promote under stability.
(c) Convert the Algorithm into code.
(d) Execute or run the program.

Symbols used in flowchart

Start & Stop

Input & Output

Decision/Test

Process

Connectors

Flow direction

Example
A program to calculate an area of rectangle:
Sln:
#include<stdio.h>
Int main( ){

15 Compiled by Mr.Rutoh Mike


Int length, width;
Float Area;
Printf(“enter the length and width\n”);
Scanf(“%d%d”,&length,&width);
Area=length*width;
Printf(“Area is %f”,Area);
}

Using Flowchart
Start

Input length &width

Area:=
length*width

Area

Stop

Advantages of flowchart

i. It is pictorial hence easy to understand


ii. It uses/utilizes standardized symbols hence easy to enforce
iii. It is two –dimension tool
iv. Information can be attended

Disadvantages

(1) It is very tiresome to come up with a flowchart


(2) There is no direct relationship between flowchart and codes

Structured chart

 They show the overall frame of the program with each level showing progressing more
details .The program is separated into modules one for each main functions
 Structured charts are used mainly to show relationship between program modules and
graphics depicts the breakdown of modules
 It is often used with other design tools such as pseudo code and flowcharts to express
the process or procedure logics.

16 Compiled by Mr.Rutoh Mike


Pseudo code /structured English

 It’s aim providing programmers with clear and unambiguous process specification
 Pseudo code is usually preceded by hierarchy of module using structured charts
 Process logic in pseudo code is express as a combination of sequence of events
decision that needs to be implemented and action that may have to be repeated.

Examples

Start

Input length ,width

Area=length*width

Output area

Stop

INTRODUCTION TO C PROGRAM

- C language is basically a very small instruction set, coupled with few standards rules
and predefined formats.
- To make the C programming easy, many programs for primitive functions (that need
to be performed in most of the cases) have already been written and compiled in the
form of libraries (also called header files).
- Programs of these libraries are so commonly used that they are almost considered part
of C language. Stdio.h, string h, stdlib.h etc are the names of few standard libraries.

Structure of the C program

#include<library-name>
main ()
{
Statement-1;
Statement-2;
.
.
.
.
Statement-n
}
The above illustration structure of C program and note that all the libraries that need
to be used within the program are include at the beginning of the program , using
#include statement. The function from where the execution will start is named as

17 Compiled by Mr.Rutoh Mike


main () . The scope of main () function extends from a open curly bracket ({) to closing
curly (}) bracket.

C programming rules
1. A C program may consist of one or more functions. One of them must be named
as main() . Execution of the program always start from main () function.
2. All the statements of main () function should be written, within the opening and
closing brackets, which mark the beginning and end of the function, respectively.
3. Practically there is no limit to the number of statements that could include in the
main () function. However to make the program manageable, use of multiple
functions should be promoted instead of too many lines in one function.
4. Each statement should be terminated with a semicolon sign (;).
5. C is case sensitive language. A differentiation is always made between upper case
and lower case letters.
6. Comments can always be included in the program by placing the matter in
between /* and*/ delimiters. Following is the general format for placing
comments in the program :
7. /* comments */
e.g. /* this program calculates simple interest*/

Operators used in C
Types of operators used in C
a) Arithmetic operators
b) Assignment operators
c) Comparison operators
d) Logical operators
e) Relational operators
Arithmetic operators
They are used to perform arithmetic operations such as addition and
subtraction

Operator name Example


+ Addition Addition 12+4.9// gives 16.9
-Subtraction Subtraction 3.98-4// gives -0.02
* Multiplication multiplication 2*3.4// gives 6.8
/ Division Division 9/2.0// gives 4.5
% Remainder Modulus 13%3 // gives 1

Relational operators

18 Compiled by Mr.Rutoh Mike


C provides six relational operators for comparing numeric quantities.
Relational operators evaluate to 1 (representing the true outcome) or 0
(representing the false outcome).
Operator Name Example
== Equality 5==5// gives 1
!= inequality 5! =5 // gives 0
< Less than 5<5.5 // gives 1
<= less than or equal 5 <= 5// gives 1
>Greater than 5>5.5 // gives 0
>= greater than or equal 6.3 >=5// gives 1

Assignment operators
The assignment operator is used for storing a value at some memory location
(typically denoted by a variable). Its left operand should be a 1 value, and its
right operand may be an arbitrary expression. The latter is evaluated and the
outcome is stored in the location denoted by the 1 value.
Operator
=
+=
-=
*=
/=
%=
&=
!=
^=
<<=
>>=

Logical operators
C++ provides three logical operators for combining logical expression .
Logical operators evaluate to 1 or 0.
Operator Name
! Logical Negation
&& Logical And
|| Logical Or
Logical negation is a unary operator, which negates the logical value of its
single operand. If its operand is nonzero it produces 0, and if it is 0 it produces
1.
Logical and produces 0 if one or both of its operands evaluate to 0.
Otherwise, it produces 1. Logical or produces 0 if its operands evaluate to 0.
Otherwise, it produces 1.
Note that here we talk of zero

19 Compiled by Mr.Rutoh Mike


Bitwise operators
Provides six bitwise operators for manipulating the individual bits in an integer
quantity.
Bitwise operators
~ Bitwise Negation
& Bitwise And
| Bitwise Or
^ Bitwise Exclusive Or
<< Bitwise Left Shift
>> Bitwise Right Shift
Operator order of precedence

Operator Rank
() 1
[]
++ 2
--
! (logical negation)
*(pointer reference)
&(address of)
Size of
* 3
/
%
+ 4
-
< 5
>
<=
>=
= 6
!=

&& 7
|| 8
?= 9
= 10
*=
/=
_=
+=
&=
%=
, 11

20 Compiled by Mr.Rutoh Mike


Assignment operator
The assignment statement is used to assign the variable on the left hand side of
the expression to the right hand side.
The assignment operator is a replacement operator which overwrites a
previous value of a variable.
Multiple assignments
Assignment statement can be used to assign several variables to a single value.
The reference operator
It used to create a copy of another variable (alias). A new variable is declared
as an alias of another variable.
Both variables will always have the same value.
This implies that when one value of the two variables changes the other also
changes to the same value.
How to create an alias variable
The & operator is used before the variable name.

Example of alias declaration


Int &y=x; hence y is also known as reference variable of x.

UNARY OPERATORS

The unary ++ and--! Operators increment or decrement the value in a


variable. There are “pre” and “post” variants for both operators which do
slightly different things.

Examples of unary expression


++
--
!
var++ increment “post” variant
++var increment “pre” variant
&
Var-- decrement “post” variant
--var decrement “pre” variant

Difference between unary and binary operators


Unary operator takes only one operand while binary operator takes two
operands.

Example of unary
++m
m++
--m

21 Compiled by Mr.Rutoh Mike


--m

Example of binary
Arithmetic operators are binary operators
Example
F=m+k
Bitwise operators
C includes operators to manipulate memory at the bit level. This is useful for
writing low level hardware or operating system code where the ordinary
abstractions of numbers , characters , pointers , etc.. are insufficient
bit manipulation code tends to be less “portable”. Code is “portable “ if with
no programmer intervention it compiles and runs correctly on different types
of computers.
The bitwise operators are 1 0 typically used with unsigned types.
~ Bitwise negation (unary) – flip 0 to 1 and 1 to 0 throughout
& Bitwise And
| Bitwise Or
^ Bitwise Exclusive Or
>> Right Shift by right hand side (RHS) (divide by power of 2)
<< Left Shift by RHS (multiply by power of 2)

NB: Do not confuse the Bitwise operators with the logical operators. The
bitwise connectives are one character wide (& , |) while the Boolean
connectives are two characters wide (&&, ||).The bitwise operators have
higher precedence than the Boolean operators. The compiler will never help
you out with a type error if you us & when you meant &&

INPUTTING VALUES FROM AND INPUT DEVICE SEQUENCE


CONTROL STRUCTURE

Scanf and printf functions


C program contains inbuilt functions named scanf () and printf () that are used
to achieve input and output respectively.
The functions are include in the header file <stdio.h>

Meaning of inputting
During inputting , data is obtained from the input device into the computer
memory where it is stored in the memory unit called variable.
The input from the keyboard is usually confirmed when the user presses the
enter key.

Inputting syntax
Scanf(“%t”,&variable_name);

22 Compiled by Mr.Rutoh Mike


Where t is the type identifier which can either be d,c,s,f
Example
To input a value and store it in a variable named y ( of float type-numbers
with decimal places)
Scanf(%f”,&y);

Inputting several variables using one statement


Many variables can be input using one statement.
Example
a) Write a statement to input the float numbers x, y, z
Scanf(“%f%f%f”,&x,&y,&z);

Outputting values
Outputting means sending some data or information from memory to an
output device eg. Monitor.
The data can be :-
a) A message piece of text

Example

Printf(“This is my first program);

b) Value of a variable
Example
Printf(“%f”,b)
c) Value of a constant
Const float pi=3.14
Printf(“%f”,pi);
Printing specific number of characters and decimal places
A number of characters to be printed in the printf() statement
Examples
%5d when used with scanf () specifies that a maximum of five digits
should be entered e.g. scanf
(“%5d”,&k);
%5d when used with printf () specifies that the output integer is
allocated five character positions e.g. printf(“%5d”,k);
%7.2f when used with printf() statement specifies that the output is
allocated seven character positions two of which are fractional part e.g.
printf(“%7.2f”,k);
Escape characters
Escape characters modifies the way the output is presented
Escape sequence meaning
\n new line
\t horizontal tab space

23 Compiled by Mr.Rutoh Mike


\v vertical tab space
\b backspace
\f form feed
\a alert of bell
\r carriage return
\\ backslash
\’ single quote
\’’ double quote
\? Question mark

NB
The most commonly used escape characters are:-
\n takes the cursor to the new line
\t leaves the horizontal tab space
Examples
i) Printf(“my first string ”);
Printf (“my second string”);

Output
My first stringmy second string
ii) Printf(“my first string”);
Printf(“\n my second string ”);
Output
My first string
My second string

CONTROL STRUCTURES

A program control structures are block of statements that determine how statements are to be
excuted.In structured program, there are three control structures

(i) Selection
(ii) Sequence
(iii) Iteration(looping)

(i) Selection control structure

In selection control structure, execution of statement depends on a condition that returns true
or false. The condition must be a Boolean expression is .one example of Boolean expression is
x>=20. In such case the condition is true, if x is equal to or greater than 20.Any other value that
is less than 20 is therefore false.

Generally the four types of selection control is used in high level program languages are

24 Compiled by Mr.Rutoh Mike


(i) IF
(ii) IF...ELSE
(iii) NESTED IF..ELSE
(iv) SWITCH CASE

(I) If….Statements
Expression is evaluated first if it is true, then the body of if is excuted.if the expression is
false, then the body of if is skipped and execution continues with the next statement.
Syntax
IF (Expression)
Statements

flowcharts

start

Exp
False

True
Body of if

Example 1

A program to determine which of the two numbers entered by the user is the greatest

Sln

#include<stdio.h>
Int num (){
Int num1,int num2,greatest;
Printf(“input the first number and second number/n”);
Scanf(“%d%d”,&num1,&num2);
If(num1>num2){

25 Compiled by Mr.Rutoh Mike


Greatest=num1;
}
Printf(“greatest is %d”,greatest);
Return 0;
}

(ii) If…..Else
Expression evaluated first if that is true then the body of if is executed otherwise else body
is executed.

Flowchart

Start

EXP
False

True
Body of if Body of ELSE

Syntax

If (Expression)

Body of if statement

26 Compiled by Mr.Rutoh Mike


Else

Body of else statement

Example

A program to determines which of the two numbers entered by user is the greatest

#include<stdio.h>
Int main(){
Int num1,num2,greatest;
Printf(“input the two numbers/n”)
scanf(“%d%d”, &num1,&num2);
if(num1>num2){
greatest=num1;
}
Else{
greatest=num2;
}
Printf(“greatest is %d”,greatest);
}
Return 0;
}

Example 2
Write a c program to calculate and display the wage of an employee based on the table
below
Hint . wage= no. hours * rate of payment per hour
HOURS RATE(PER HOUR)
1-3 350
4-7 650
7-10 740
11 and over 1000
sln

# include<stdio.h>
Int main(){
Int hours, wages;
Printf(“enter the hours/n”);
Scanf(“%d”,&hours);
If(hours>=1 && hours<=34){
Wages=hours *350;
Printf(“wage is %d”,wage);
}

27 Compiled by Mr.Rutoh Mike


Else if(hours>=4 && hours<=7){
Wages=hours * 650;
Printf(“wage is %d”,wage);
}
Else if(hours>= 7 && hours<= 10){
Wages=hours * 740;
Printf(“wage is %d”,wage);
}
Else if(hours>=11){
Wages=hours*1000;
Printf(“wages is %d”,wages);
}
Else {
Printf(“invalid hours entered/n”);
}
Return 0;
}

(iii). Nested if…Else

Nested control structure enables us to do multiple selection choosing one item among
alternatives.

Example 1

MARKS GRADE
70-100 A
60-69 B
50- 59 C
40- 49 D
0-39 F

# include<stdio.h>
Int main(){
Int marks;
Char grade;
Printf(“input the marks/n”);
Scanf(“%d”,&marks);
If(marks>=70 && marks<=100){
Grade=’A’;
}

28 Compiled by Mr.Rutoh Mike


Else if(marks >=60 && marks<=69){
Grade=’B’;
}
Else if(marks>=50 && marks <=59){
Grade=’C’;
}
Else if(marks>=40 && marks<=49){
Grade=’D’;
}
Else {
Grade=’F’;
}
Printf(“Grade is % c”,Grade);
Return 0;
}

(iii) Switch Case


The syntax of switch statement is a bit peculiar. It’s objective is to check several possible
constant values for an expression. The syntax for the switch case structure.

Syntax

Switch (Expression){
Case const1:
Group of statement1;
Break;
Case const 2;
Group of statement 2;
Break;
------------------
------------------
Default:
Statement(s)

Example 1
Write a c-program to prompt the user to input a number in numerals and print the number
in words e.g 1-ONE
sln

29 Compiled by Mr.Rutoh Mike


#include<stdio.h>
Int main(){
Int number;
Printf(“input the numbers from 1-10/n”);
Scanf(“%d”,&number);
Switch(number){
Case 1:
Printf(“one/n”);
Break;
Case 2:
Printf(“two/n”);
Break;
Case 3:
Printf(“three/n”);
Break;
Case 4:
Printf(“four/n”);
Break;
Case 5:
Printf(“five/n”);
Break;
Case 6:
Printf(“six/n”);
Break;
Case 7:
Printf(“seven/n”);
Break;
Case 8:
Printf(“eight/n”);
Break;
Case 9:
Printf(“nine/n”);
Break;
Case 10:
Printf(“ten/n”);
Break;
Default:
Printf(“no such a number/n”);
}
Return 0;
}

ITERATION CONTROL STRUCTURES


I. DO…WHILE LOOP
II. WHILE…LOOP
III. FOR….LOOP

30 Compiled by Mr.Rutoh Mike


Iteration is a process of repeating the execution of statement until a given condition is
achieved.

i. While…loop
It’s functionality is simply to repeat statement while the condition sets in expression is True.
Syntax
While (condition){
Statements
}

Flowchart

start
true

Test
cond
false

Statements

Statement after
While..loop

Example 1
Write a program to print integers from 1-10
Sln
# include<stdio.h>
Int main (){
Int x;
X=1;
While(x<=10){
Printf(“x is %d”,x);
++x or x=x+1;
}

31 Compiled by Mr.Rutoh Mike


Return 0;
}

Example 2
Write a c program to display the number sequence 3,7,11,15,19,23,27,31
Sln
# include<stdio.h>
Int main(){
Int x;
X=3;
While(x<=31){
Printf(“x is %d”,x);
X=x+4;
}
Return 0;
}

Example 3
Write a c program to print all numbers from 1 to 21 that are divisible by 3
Sln
# include<stdio.h>
Int main(){
Int x;
X=3;
While(x<=21){
Printf(“x is %d”,x);
X=x+3;
}
Return 0;
}

ii. DO… WHILE LOOP


It is exactly the same as while..loop, except that the condition in the do..while loop is
evaluated after execution of statements, instead of before granting atleast one execution of
the statements even if the condition is never fulfilled.
Syntax
Do{
-------------
statements
……………..
} while(condition)

32 Compiled by Mr.Rutoh Mike


Flowchart

start

Body of the loop

Test

cond False

True

Statement after DO..While

Example 1
Write a c program to print integers 1-100
Sln
#include<stdio.h>
Int main(){
Int x;
X=1;
Do {
Printf(“x is %d”,x);
X=x+1;
}
While(x<=100);
Return 0;
}
Example 2

33 Compiled by Mr.Rutoh Mike


Write a c program to display odd numbers between 0 and 100
Sln
# include<stdio.h>
Int main(){
Int y,Rem;
Y=0;
DO{
y=y+1;
Rem=y%2;
If(Rem==1){
Printf(“y is %d”,y);
}
}
While(y<=100);
Return 0;
}

iii. FOR…LOOP
It’s main function is to repeat a statement while condition remains true.
Operation in for..loop
i. Initialization of the counter
ii. Testing the condition
iii. Changing the value of the counter(counter change)
iv. The loops body(statements)

Flowchart

start

Init

Test
cond false

True
Loop body

Reinit

34 Compiled by Mr.Rutoh Mike


Statement after loop

Syntax
For(initialization; condition; counter change){
………………………………………………………………
……………………………………………………………… statements
………………………………………………………………
}

Example1
Write a c program to display numbers 1 to 10
Sln
#include<stdio.h>
Int main(){
For (int y=1; y<=10; y++){
Printf(“y is %d”,y);
}
Return 0;
}

Example 2
Rewrite the above program to display numbers 10 decrement 1 i.e 10, 9,8,7,6,5,4,3,2,1
Sln
# include<stdio.h>
Int main(){
For(int y=10; y>0; y--){
Printf(“y is %d”,y);
}
Return 0;
}

Example 3
Write a c program to print even numbers from 2 to 20
Sln
#include<stdio.h>
For(int c=2; c<=20; c++){

35 Compiled by Mr.Rutoh Mike


If(c%==0){
Printf(“c is %d”,c);
}
}
Return 0;
}

Example 4
Write a c program to output the following pattern
S
S s
S s s
S s s s
S s s s s

Sln
#include<stdio.h>
Int main(){
For(int i=1; i<=5; i++){
For(int j=1; j<=I; j++){
Printf(“s\t is %d”,s);
}
Printf(“\n”);
}
Return 0;
}

Example 4
Write a c program to output the following pattern
@ @ @ @ @
@ @ @ @ @
@ @ @ @ @
@ @ @ @ @
@ @ @ @ @

Sln
#include<stdio.h>
Int main(){

36 Compiled by Mr.Rutoh Mike


For (int i= 1; i<=5; i++){
For (int j=5; j>0; j-- ){
Print f(“s\t”);
}
Printf(“s\n”);
}
Return 0;
}

Example 5
Write a c program to output the following pattern
S S S S S
S S S S
S S S
S S
S

Sln
#include<stdio.h>
Int main(){
Int i,j;
For(i=5; i<=i; i--){
For(j=1; j<=i; j++){
Printf(“s\n”);
}
}
Return 0;
}

Example 6
Write a c program using for loop to add and display the sum of all odd numbers between 0
and 100
Sln
#include<stdio.h>
Int main(){
Int sum,Rem;

37 Compiled by Mr.Rutoh Mike


Sum= 0;
For(int i=0; i<=100; i++){
Rem=i%2;
If(Rem==1){
Sum=sum+i;
}
}
Printf(“sum is %d”,sum);
Return 0;
}

Example 7
Write a c program to input 5 integers, compute the total, average and print the output using
for..loop
Sln
#include<stdio.h>
Int main(){
Int total;
Float Average;
Total=0;
For( int x=0; x<=5; x++){
Total=total + x;
Total=total/5;
}
Printf(“Total is %d”,total);
Printf(“Average is %f”,Average);
Return 0;
}

FUNCTIONS
Using functions we can structure a program in a more modular way. function also is a group
of statement that is excuted when it is called from source joint of the program.
Syntax
Type Name(parameter 1,parameter 2……….){
Statements
}
i. Type- is a datatype that specify for the data return by the function.
ii. Name-it is the identifier by which it will be possible to each function
iii. Parameter- Each parameter consists of datatype specifier followed by an identifier
like any regular variable declaraction.The parameter acts within the function as a
regular local variable.parameters allow to pass arguments to the function which it is
called.

38 Compiled by Mr.Rutoh Mike


iv. Statements-is the function body.it is a block of statement surrounded by braces.

Example 1
Write a c program to prompt the user for two values,add and display the results
using function
Sln
#include<stdio.h>
Int addition(int a,int b){
Int R;
R=a+b;
Return(R);
}
Int main(){
Int x, y, sum;
Printf(“input the value of y and x\n”);
Scanf(“%d%d”,&x,&y);
Sum=addition(x,y);
Printf(“sum is %d”,sum);
Return 0;
}

Function with no type, the use of void


Syntax
Type name(parameter 1,parameter…2){
Statement(s);
}

From the above declaraction,you will find it begins with a type i.e the type of data
that will be returned by the function with the return statement.
But what if we want to return no value? e.g Assume we want to make a function just
to show a message on the screen.In such situation we do not need to return any
value.In this case we should use void type specifier that indicates absences of type.

Example 1
Write a c program to display a message using function
Sln
#include<stdio.h>
Void printmessage(){
Printf(“A function without a return type\n”);
}
Int main(){

39 Compiled by Mr.Rutoh Mike


Print message();
}

Example 2
Write a c program containing a function called circleArea() to compute Area of the
circle given that Radius =7cm
sln
#include<stdio.h>
Float circleArea(float r){
Const float pi=3.142;
Float A;
A=pie*r*r;
Return(A);
}
Int main(){
Float radius,Area;
Printf(“input the radius\n”);
Scanf(“%F”,&Radius);
Radius=7;
Area=circleArea(Radius);
Printf(“Area is %F ”,Area);
Return 0;
}

Example 3
Write a c program using function that would accept the radius and height of a
closed cylinder and calculate its volume and the value of the volume to be
displayed in the body of the program
Sln
#include<stdio.h>
Double volume1(int r,int h){
Double v;
V=3.142*r*r*h;
Return(v);
}
Int main(){

40 Compiled by Mr.Rutoh Mike


Int x,y;
Double volume;
Printf(“input the value of radius\n”);
Scanf(“%d”,&x);
Printf(“input the value of height\n”);
Scanf(“%d”,&y);
Volume=volume1(x,y);
Printf(“volume is % f”,volume);
Return 0;
}

Example 3
Write the c program to accept a number enter through function ,the function then
determines whether number passed is odd or even
sln
#include<stdio.h>
Int number(int num){
Int Rem;
Rem=num%2;
If(Rem==0){
Printf(“even is %d”,even);
}
Else if{
Printf(“odd is %d”,odd);
}
Return(Rem);
}
Int main(){
Int a;
Printf(“input the value of a\n”);
Scanf(“%d”,&a);
Number(a);
Return 0;
}

Example 4
Write a c program to accept two numbers. determine which number is greatest using
function .Write the said program such that on the termination the sum value passed to a
notation function to be displayed
Sln
#include<stdio.h>
Int greatest(int a,int b){
Int max;
If(a>b){
Max=a;

41 Compiled by Mr.Rutoh Mike


}
Else {
Max=b;
}
Return(max);
}
Void display greatest(int max){
Printf(“greatest is %d”,greatest);
}
Int max(){
Int x,y,maximum;
Printf(“input the value of x,y\n”);
Scanf(“%d%d”,&x,&y);
Maximum=greatest(x,y);
Display greatest(maximum);
Return 0;
}

Function of void-Void is function which only brings a message and have no value to return.

Scope of variables
The scope of variables declared within the function or any other inner block is only their
own function or their own block and cannot be called outside there[Local variables] e.g in
the previous example it could have been impossible to use the variables a,b or r dmoctly in
the function main since they were variables local the function addition.

Therefore the scope of block of variables is limited to the same block levels in which they
are declared .N/B we have 2 types of scope of variables
[1]Global variables
[2]Local variables
We also have possibility to declare global variables. These variables are visible from any
point of the code inside and outside all functions.
In order to declare global variables you need to declare outside any functions or block.This
means directly on the body of the program as shown below.

Example 1
#include<stdio.h>
Int integer;
Char character; Global
Char string [20] variables
Unsigned int number of sons;
Int Addition(int a,int b){
Local
Int r;
variables
}

42 Compiled by Mr.Rutoh Mike


Int main(){
unsigned short age;
Float A number, Another one ;
}
N/B Anything declare within a functions is called local and anything declare outside the functions is
called global variables.
Global variables is a variables which is accessible in multiple scopes. They are only accessible after
they have been declared

Types of functions
[1] In build function
[2] user defined function

[1]In build function These are functions which have been written and the one that exist in the
library of codes.
If you want to use this functions you include them in the header file.

Example 1
Inbuilt functions
#Include< stdio.h>
#Include<CMath> Header file
This means that you are including math .h which is a header file in you program.
This c math contains different functions e.g sqrt(), sin(), cos(), tan(), pow(). Inbuilt mathematical
functions.
Syntax arguments
X=SQRT(40)
Keyword
Identifier

Example 1
A program to compute the power of number and value to false and must be entered by user.
Sln
#include<stdio.h>
#include<cmath>
Int main(){
Int m,n,power;

43 Compiled by Mr.Rutoh Mike


Printf(“enter a number\n”);
Scanf(“%d”,&m);
Printf(“enter value raise to\n”);
Scanf(“%d”,&m);
Power=pow(m,n);
Printf(“power is %d”,power);
Return 0;
}

Example 2
Write a c program to solve formula and display the possible roots of the quadratic
equation
ax2+bx+c=0;
sln
#include<stdio.h>
#include<cmath>
Int main(){
Float x,x1,x2;
Printf(“enter the value a,b,c\n”);
Scanf(“%d”,&a,&b,&c);
X=SQRT(b*b-4*a*c);
If(x>0){
X1=-b-(x)/2*a;
X2=-b+(x)/2*a;
Printf(“x1 is ”,x1);
Printf(“x2 is”,x2);
If(x==0){
X3=-b/2*a;
Printf(“x3 is%d”,x3);
}
Return 0;
}

DATA STRUCTURES
Is a specialised format of organizing data storing. Data structure is a way of organising data
in a computer so that it can be used effectively.
Data structure are methods and techniques for efficient use.
Example of data structures
i. Arrays

44 Compiled by Mr.Rutoh Mike


ii. Records/structs
iii. Pointers
iv. Types
v. Queues
vi. Stacks

1. ARRAYS
An array is data structure consisting of elements of the same type,each of which directly
access using the same name i.e Array name.
Array is a series of elements of the same type placed contiguous/consequently in a
memory and can be individually referenced by adding an index to unique name
Application of Arrays
1.used for storing marks of students
Types of arrays
i. one/single dimensional array
ii. multi-dimensional array

1. one/single Dimensional Array


A row or column of values INDEX
0 1 2 3 4
ARRAY
NAME X 20 50 90 -10 0
VALUES

Declaration of single Dimensional Arrays


Type ArrayName[minimum size]; of the same type

Example 1
Int X[5];

0 1 2 3 4
ARRAY
NAME X 20 50 90 -10 0

EXAMPLE 2

Char X[6];
Index
0 1 2 3 4 5

45 Compiled by Mr.Rutoh Mike


ARRAY
NAME X ‘a’ ‘e’ ‘9’ ‘0’ ‘u’ ‘7’

Value

Writing values to an Array(Assigning values to an Array):


Syntax
ArrayName[index]=Value;
Example 1
X[2]=90;
Char[3]=’10’;
Number[3]=’-10’;
N\B it will assign the value(-10) to the third location/index in the array number.
Accessing values stored in Array
To access values stored in a particular location in the array, we used this format
Name[index];
For example to display the value stored in the third location in the array number use
the statement.
Printf(“number is %d”,number[3]);
Example 1
Write a c program that initialised an array x to 5 given values and then display
values. Hint x(20,50,90,-10,0)
Sln
#include<stdio.h>
Int main(){
Int X[ ]={20,50,90,-10,0};
Int i;
For(i=0; i<=4; i++){
Printf(“numbers are %d”,X[i]);
Return 0;
}

Example 2
A program to prompt the user for an array of five elements to be stored in a
variable num.the program then display the elements in the array

46 Compiled by Mr.Rutoh Mike


Sln
#include<stdio.h>
Int main(){
Int num[5];
For(int i=0; i<=4; i++){
Printf(“enter the Array elements\n”);
Scanf(“%d”,&num[i]);
}
Printf(“elements entered are\n”);
For(int j=0; j<4; j++){
Printf(“numbers are %d”,num[i]);
}
Return 0;
}

Example 3
Write a c program to display an array of three elements entered by the user in
reverse order
Sln
#include<stdio.h>
Int main(){
Int num[3];
For(int i=0; i<2; i++){
Printf(“enter the elements\n”);
Scanf(“%d”,&num[i]);
}
Printf(“the elements in reverse are\n”);
For(int j=2; j>0; j--){
Printf(“numbers are\n”,num[j]);
}
Return 0;
}

Example 4
#include<stdio.h>
Int main(){
Int scores[10];
Int sum,average;
Sum=0;
For(int i=0; i<=9; i++){
Printf(“enter the scores\n”);

47 Compiled by Mr.Rutoh Mike


Scanf(“%d”,&scores[i]);
Sum=sum+scores[i];
Average=sum/10;
Printf(“average is %d”,average);
}
Return 0;
}

ii.Two dimensional Array


A two dimensional array can be describe as Arrays of Arrays.two dimensional array is
With N number of rows and N number of columns
It can be imagine as bi-dimensional table made of elements all of them of the same
datatype.Example below represent a two dimensional array of 3 by 5 elements of type int
(integer).

Syntax/format Student
scores
Type
ArrayName (max Rowsize) with (max columnsize)
0 1 2 3 4
0
Student
1
scores 2

[1] [3]
Row column

The way to declare this Array in C-programming would be: int student scores (3) (5)
.The way to reference the second elements vertically and fourth horizontally (the
second student fouth score) in the expression would be:
Student scores [1][3];
To insert a value of fourth it score for the second student, you would use the
statement:
Student score [1][3]=60;OR
Printf( student score[1][3]);
Arrayname [Rowindex] [columuindex]=value;

48 Compiled by Mr.Rutoh Mike


Example 1
Write a c program to assign 45 to all elements of 2X2 Array and display the contents

0 1
45 45
45 45

Sln
#include<stdio.h>
Int main(){
Int num[2][2];
Int row,cols;
For(row=0; row<1; row++){
For(cols=0; cols<=1; cols++){
Num[row][cols]=45;
}
}
For(row=0; row<=1; row++){
For(cols=0; cols<=1; cols++){
Printf(“num[row][cols]/t”);
Printf(“\n”);
}
Return 0;
}

Assignment
1.Write a c program to prompt the user for an array of 2 scores for 2 students add
and display their sum as per the table below
scores

0 1 2
maths english total

students

Sln
#include<stdio.h>
Int main(){
Int studscore[2][2];

49 Compiled by Mr.Rutoh Mike


Int stud,score;
Int sum[2];
For(stud=0; stud<=1; stud++){
Sum[2];
For(score=0; score<=1; score++){
Printf(“enter the score\n”);
Scanf(“%d”,studentscore[stud][score]);
Sum[stud]=sum[stud]+studentscore[stud][score];
}
}
Printf(“maths\t”,”English\t”,total\n”);
For(stud=0; stud<=1; stud++){
For(score=0; score<=1; score++){
Printf(“studentscore is%d\t”,studentscore[stud][score]);
}
Printf(“sum is %d/n”,sum[stud]);
}
Return 0;
}

50 Compiled by Mr.Rutoh Mike


RECORDS /STRUCTS
It is a collection of related fields.it enables us to manipulate data of different type.structs
(structures) is a data structure used to store element of different types using the same
name.
It store operations to be perfomed on that data therefore structs combine data and
operations to be peformed on that data, therefore structs combine data and operations that
concern objects of its type.
Structs contain:
i. Data members(stores attributes)
ii. Member function(functions within structures)

Structs/structures

Data member functions(functions)


Members
(variables)

N/B Structs are done outside main functions

Student: structure
Roll no- int datatype
Age-int datatype Member of
Religion- string datatype structure
Fees-float datatype

Declaration/syntax
Struct structName
Members declarations
};

EXAMPLE 1

Struct Num{

Int x;

Int y;

51 Compiled by Mr.Rutoh Mike


};

EXAMPLE 2

Declared an instance of struct (VARIABLE OF STRUCTS)/OBJECTS.

Struct name variable

EXAMPLE 2

Struct Num p,q;

Main () Global scope

Inside a fuction() Local scope

Store values;

P . x =values;

Variable struct Data member

Access struct values

1) Print f(“p.x”);
2) If (p.x>10)
Statement;
3) Y=(P.X =3)/2
4) Y =P.X
Example 3
#include<stdio.h.>
Struct x {
Char a;
Int b;
}
Int main (){
Struct xq structure variable
//Store values to struct
Printf(“Enter the value of member a character\n”);
Scanf(“%c”,&q.x);
Printf(“Enter the value of member b integer\n”);
Scanf(“%d”,&q.b);

52 Compiled by Mr.Rutoh Mike


// Output data member,member values
Printf(“a=”,q.a);
Printf(“b=”,q.b);
Return o;
}
ASSIGNMENT
Write a program to define a structure named employee.The structure should have the
following elements in it.
1. Employee no (int type)
2. Name (character array of 50 elements)
3. Age (int type)
4. Expression (int type)
5. Salary (float type)
This program should create a variable alok of this data.Accept members values from
the keyboard and print

SOLUTION

#include<stdio.h>

Struct Employee{

Int empno;

Char name [50];

Int age;

Int experience

Float salary;

} Aloak;

Int main (){

Printf(“Give employee number\n”);

Scanf(“%d,& Alok.empno);

Printf(“Give Name”)

Scanf(“%c”,Alok.Name);

Printf(“Give experience”);

Scanf(“%f” alok.salary);

Printf (“%d EmployeeNo\n” Alok.Empno);

SCOPE OF STRUCTS VARIABLE

53 Compiled by Mr.Rutoh Mike


I. Global
II. Local
a) Global scope –it declared outside of any function
Syntax
Struct {


} x,z,y Structure variable of global scope
b) Local scope –it is declared within a function
Syntax
Struct .structname variable
e.g struct xx=(value};
eg xx ={‘#’,2000}
Example 1

Intmain(){
Struct student stud1={“jane “,90,25,30};
Struct student stud 2={“Ken”,80,50,70”};
Member function of a structure
 These are just function declared within function; they define operation
within a structure.
 It define what are the function within the structure
Example
#include<stdio.h>
Struct x{

Data member Char a;

Int b;
Void ReadData(){
Printf(“enter the value of a\n”);
Scanf(“%c”,&a);
Printf(“enter the value of b\n”);
Scanf(“%b”,& b);

Member function }

Void Display (){


Printf(“a\n”);
Printf(“b\n”);
}};
Int main() {
Struct xx;
x.readData();
x.Display();
Return 0;

54 Compiled by Mr.Rutoh Mike


}

Array of structs

 We can define many struct using an array e.g to store 10


structure/struct we need an array of structs.
Structs
Struct structname X[max size];
Accesing structs array
X[Index].Datamember =value
Index 0
X [1].Name =”Hellen”;
X [1].Math =25;
X [1]. Eng =85;
X [2]. Name =”Peter”;
# include <stidio.h>
Struct student {
Int Math;
String Name;
Int Eng;
Int Kis;
}Stud;
Int main (){
Int I;
Struct Student Stud[10];
For(i=0;i<=9; i++){
Printf(“Name is”);
Scanf (“%s &stud [i].Name);
Printf(“math is”);
Scanf (“%d” & stud [i].Math);
Printf(“English is”);
Scanf(“%d”,stud[i].Eng);
Printf(“Kiswahili is”);
Scanf(“%d”,&stud[i].kisw);
}
For(i=0; I<=9;i++){
Printf (“%s Name is \n”, Stud[i].Name);
Printf(“%d Math is\n”, Stud[i].Math);
Printf(“%d English is\n”, Stud[i].Eng);
Printf(“%d Kiswahili is\n”, Stud[i].Kisw);
}
Return 0;
}
Assignment

55 Compiled by Mr.Rutoh Mike


Say a/c department has to keep track of saving s done by 30 employees of the
organization.For this it maintain the following records:

i. Employee
ii. Name
iii. Earnings
iv. Expenditure
Write a program that accepts the data of all employees and print saving amount
for them.
SOLUTION
#include <stdio.h>
Void Readdata(int);
Void calculate(int);
Struct Employee {
Int empno;
Char Name[30];
int earning;
int spend;
}emp[25];
Int main(){
Int n;
Printf(“\n How many employees are there”);
Scanf(“%d”, &n);
Readdata(n);
Calculate(n);
}
Void.Readdata(int n){
int i ;
For (i=0; i<n; i++){
Printf(“Give employee.Number”);
Scanf(“% I”,& emp[i].empno);
Printf(“Give employee Name”);
Scanf (“%[^\n]”, emp[i].Name);
Printf(“Give earning amount”);
Scanf(“%i”&emp[i].earning);
Printf(“Give expenditure amount”);
Scanf(“% I”, & emp[i].Spend);

}
Return;
}
Void calculate (int n){
int i,diff;
For(i=0; i<n; i++){
Diff =emp[i].earning –emp[i].spend;

56 Compiled by Mr.Rutoh Mike


Printf(“\n Employee Number% I”, emp [i] .empno);
Printf(“\n Name %s”, emp[i].Name);
Printf(“\n Earning % i”,emp[i].earning);
Printf(“\n Expenditure % i”, emp[i].spend);
Printf(“\n saving % i”,diff);
}
Return;
}
POINTERS
 It is a variable that hold the memory address of another object. It is
a variable that holds the location in another variable in memory.
WHY DO WE NEED POINTERS?
i. It simplify programming effort, because a programmer
needs only to declare one pointer and have it pointed to
different objects when needed.
ii. It is useful in dynamic memory management
iii. They are more efficient in holding complex data structures
such as Arrays,Structs,Link lists,Queues,Stacks.
iv. It increases program execution speed.
N/B Pointer Is a variable whose value is the address of
another variable i.e direct address of the memory location.
Declaration of pointers
Type *pointer Name
TYPE Primitive data type supported by c
 Void
 Int
 Char
 Float &double
Pointer Name is any valid identifier
Example 1
Int *ptr Declaring of pointer of type integer
Pointer operators
1) * Deference operator –It return a value of a variable at the
address indicated.Using a pointer we can directly access the value
stored in the variable which pointers to.To do this we simply have to
proceed the pointers identifier .Asterik(*) which acts as Deference
operator and that be literally translated to value pointed by

Example of deference
Int * p;
P=&a; Since p is pointing to a variable a then print (“*p”)
A=50
ii) Referencing operator -Returns the memory address of a variable
.The address that locate the variable within memory is what we
called Reference to that variable.The reference to a variable with

57 Compiled by Mr.Rutoh Mike


ampersand(&) sign, known as reference operator and which can
literally translated to address of
Example of reference(&)

Int * p;
Int a;
P=&a;

The statement p is equal to reference a, would assign to p the address of variable a, since when
proceding the name of avariable a with the reference operator(&) we are talking about the content
of the variable itself but about its record ie (its address memory)

N/B To differentiate pointers with normal variable they are prefixed with Asterik(*) sign.

N/B Data type ^pointer Name

Int* P speed
Char*pstatus
Float *point
EXAMPLE 1
#include<stdio.h>
Int main(){
Int speed=250;
Int*p speed.
Printf(“%d the value of speed variable\n” speed);
Printf(“% d the address of speed variable\n” pspeed);
Printf (“%d value attained trough operator\n” p speed);
Return 0;
}
OUTPUT
The value of speed variable is 250
Example 2
A program to add two numbers using pointers
#include<stdio.h>
Int main()}
Int a,b,s.
Int *p1,*p2,*sum;
P1=&a:
P2=&b;
Sum=&s;
Printf(“enter the value of a\n”);
Scanf(“%”,&*p1);
Printf(“enter the value of b\n”);

58 Compiled by Mr.Rutoh Mike


Scanf(“%d”’,&*p2);
Ss=*p1+*p2;
Printf(%d is “sum);
Return o0;
}
Example 3
Write a program to divide two numbers entered by the user and
display quotient
s\n
#include<stdio.h>
Int main()}
Int a,b,q;
int *p1,*p2,*q;
p1=&a;
p2=&b;
quotient=&q
prinf(“input the value of a\n”);
scanf(“%d,”&*p1);
q=b/2;
printf(“quotient is %d,” quotient)
Return 0;
}

Pointer and arrays


The concept of array is very much bound to the one of the pointer In fact the identifier of
the Array is equivalent to the address of its first element just as pointer is equivalent to the
address of the first element that it points to, so in fact they are the same concepts.

Example

Suppose you have the following declaration

Int Number[20];int *p;then the following assignment operators will be equivalent and
would have the same properties.They only difference is that it could change the value of
pointer P by another one wheares numbers would always point to the first twenty element
of type int with which it was defined.

Example 1

Due to xtrics of the variable all the expression that include pointers in the following example
on perfectly valid

s\n

59 Compiled by Mr.Rutoh Mike


#include<stdio.h>

Int main(){

Int numbers[5];

Int *p,

P=numbers;

*p=10;

p++;

*p=20;

P=&numbers[2];*p=30;

P=numbers;*(p+4)=50;

For (int n=0; n<5; n++){

Printf(“number are %d”, number (n));

Return 0;

Output

10, 20,30,40,50

Example 2

A program to a numbers using a function and a pointer

s\\n

#include <stidio.h>

Int sum(int n[]){

Int total;

Total=0;

For(int=0;j<5;j++){

Total=total+*(n+j);

60 Compiled by Mr.Rutoh Mike


Return (tot);

Int main()

Int number[5];

Int s;

For (int i=0; i>5; j++) {

Printf (“enter the element\n”);

Scanf (“%d”, & number[i];

Scanf (“%d”, & number[i]);

S=sum(numbers);

Printf(“sum is %d”,& 5);

Return 0;

Example 4

Write a c program using a function and a pointer to accept the array of number 1 to 10 and
display in reverse order.

s\n

#include<stdio.h>

Void reverse(int n[]){

For(int j=10;j.=0;j--){

Printf(“number are *(n +j)’);

Int main ()

For ( int i=1;i<10;i++){

61 Compiled by Mr.Rutoh Mike


Printf (“enter the elements\n”):

Scanf (“%d”,& number[1]);

Reverse (number);

Return 0;

Pointers to pointers

C programming allows the use of pointers that point to pointers i.e. that this will return
pointers to data or even to other pointers

- In order to do that we only need to add an asterisk for each of level reference in
their declaration
Example
Char a,
Char *b;
Char **c;
a=’z’;
b=&a;
c=&b;

- Supposing the randomly chosen memory location for variable a,b,c are
7230,8032,10502 respectively then the above declaration will be represented as;

‘z’ 7230 8032

8032 10502
7230

The value of each variable is written inside each cell,under the cells,there are respective
address in memory.

From the above example,the variable can be used in three different levels of directions each
one of them will correspond to different values eg c has value 8032

62 Compiled by Mr.Rutoh Mike


*c has value 7230

**c has the value’z’

SORTING TECHNIQUES

1. BUBBLE SORT

It is a simple sorting algorithm .The bubble sort work by iterating down an array to be sorted
from the first element to the last comparing each pair of element of switching their position
if necessary .This process is reapeted as many times as necessary until the aerray is sorted.

ILLUSTRATION;

-Bubble sort would pproduce the following list of ascending order

Elements to be sorted 5,4,3,1,2

Loc [0] [1] [2] [3] [4]

5 4 3 1 2

4 5 3 1 2

4 3 5 1 2 1st pass

4 3 1 5 2

4 3 1 2 5

Loc [0] [1] [2] [3] [4]

4 3 1 2 5

3 4 1 2 5

3 1 4 2 5 2nd pass

3 1 2 4 5

3 1 2 4 5

63 Compiled by Mr.Rutoh Mike


Loc [0] [1] [2] [3] [4]

3 1 2 4 5

1 3 2 4 5

1 2 3 4 5 3rd pass

1 2 3 4 5

But the element are already sorted

Example 1

A program to sort a list of 5 element entered by the user in ascending order using bubble sort
technique

Sln

#include <stdio.h>

#define n 5

Int main(){

Int num(n);

Int I,pass,compar;

For (i=0; i<n; i++){

Printf(“enter elements to sort\n”);

Scanf (“ number is %d ,”&num[i])

For(pass=0;compare,n-1;compar++]{

For(compare=0;compar<n-1;compar++){

If(num[compare]>num[compar+1){

Int temp=num[compare];

Num[compar] =num [compare +1];

Num [compare+1] = temp;

}//if

}// inner for

64 Compiled by Mr.Rutoh Mike


}//outer for

Printf(“ the sorted elements are \n”);

For (i=0;i<n; i++){

Printf(‘numbers are %d”, num[i]);

Return 0;

N/B Maximum pass is equal to number of elements minus 1

Ii SELECTION SORT

 Selection sort works by selecting the smallest(or largest).If you want to sort from big to small
)It works by selecting small and placing it at the head.Then the process is reapeted for the
remainder of the array.The next largest element is selected and put array .The next largest
element is selected and put into the next slot and so on down the line .
 Because a selection sorts looks at pproccessing smaller part of an array each time (it knows
to ignore to infront of the varray because it is already inorde)
 Then the selection sort is likely faster than bubble sort.

Illustration to sort the elements

5,4,3,1,2, In asc order using selections technique

Loc
0 5 4 3 1 1
1 4 5 5 5 5
2 3 3 4 4 4 1st pass
3 1 1 1 3 3
4 2 2 2 2 2

Loc 0 1 1 1 1
1 5 4 3 2
2 4 5 5 5 2nd pass
3 3 3 4 4
4 2 2 2 3

Loc 0 1 1 1

65 Compiled by Mr.Rutoh Mike


1 2 2 2 3rd pass
2 5 4 3
3 4 5 5
4 3 3 4

Loc
1 1 1
2 2 2
3 3 3 4th pass
4 5 4
5 4 5 the element are already sorted

Example 1
A program to sort a list of 5 elements entered by user in ascending order using
selection sort technique
s/n
#include<stdio.h>
#define n5
Int main() {
Int num[n];
Int pass, compare, temp;
For(i=0,I<n,i++}
Printf(‘’key element to sort/n”);
Scantf(“%d,” &num[i];
}
For(pass=0;pass<n-1;pass++){
For(compare=pass+1;compare<n;compare++){
If(num[pass]>num[compare]){
Temp=num[pass];
Num[pass]=num[compare];
Num[compare]=temp;
}//endif
}//end inner for
}//end outer for
Printf(‘’sorted list is %d,”sorted list/n’’);
For(i=0;i<n;i++){
Printf(“numbers are &d,’’num[i]/n’’);
}
Return 0;
}

SEARCHING TECHNIQUES
(1) LINEAR SEARCH
-This is a very straight forward searching techniques that compares every
element in the array with key element being search. As soon as the equal

66 Compiled by Mr.Rutoh Mike


values is found. The program displays the message that the element has
been founds.
-if the search finishes without finding a match . it means the search failed
&the program displays the message that element was found.
Example 1
A program to implement linear search
Sln
#include<stdo.h>
#define n5
Int main(){
Int X[n];
Int key,I;
Printf(‘’enter the element to search from list/n);
Scanf(“%d”,&key);
For (int j=0; j<=5; j++){
Printf(“enter the elements to search from\n”);
Scanf(“%d”, &x[i]);
}
I=0;
While(x[i] !=key)&&(i!=n){
I=i+i!
}
If( x[i]==key){
Printf(“ the element was found\n”);
}
Else {
Printf(“element not found\n”);
}
Return 0;
}

II BINARY SEARCH;
DIVIDE IN HALF;
- It is first way to search a sorted array. The idea is to look at element in the
middle. If the key is equal to that then the search is finished because the
element has been found.If the key ie less than the middle element.Do a
binary search on the first half of the array.If the key is greater.Do a binary
search on the second half of the array.
Example:
Search for 36 using a binary search
1,16,19,24,36,4,7,9,13
1,4,7,9, 13 16,19,24,36
Lower half upper half
middle

67 Compiled by Mr.Rutoh Mike


16,19 lower half 24,36 upper half search element is 36
Algorithm for binary search
1. Compare the subscript of the middle element with the target
elements
2. Set success to true if the target element is in middle
3. Set success to true if the target element is in middle
4. Otherwise lsearch the left handside if the target element is less than
the middle value.
5. Else search the right handside
6. Repeat step number 3 on the left sub-array and the right sub-array
until the element is found.

Example 1
A program to implement binary search
#include<stdio.h>
Int main () {
Int array [n];
Int first last key;
Prinf(“enter the element to search from the list\n”);
Scanf(“%d”, & key);
For (int i=0; i<n; i++) {
Printf(“enter the element to search from\n”);
Scanf(“%d”,& array [i]);
}
First =0
Last=n-1
While (first<=last){
Int mid=(first+last)/2;// compare mid points
If(key=array[mid]{
Prinf(“elements found\n”);
}
If(key>array[mid]{
First=mid+1;// repeat search in top half
}
If(key<array[mid]{
Last=mid-1;//repeat search in bottom half
}
}//end while
Print (“element not found\n”);
Return o;
}

68 Compiled by Mr.Rutoh Mike


FILE HANDLING
INPUT/OUTPUT WITH FILES:
- C Programming provides the following classes to perform output and
input of characters to and from files
i. Of stream –it is a stream class to write on files
ii. if stream –is a stream class to read from a file
iii. f stream-stream class both read and write from/to files
- These classes are directly derived or indirectly derived from the classes
istream and ostream
- We have already used objects whose types for its classes called Scanf is
an object of class istream
Printf is an object of class ostream
Textfiles
Are files designed to store text.
Example
The code below creates a file called example text that insert the
sentences into just as the same way we are used to printf but using the
file stream myfile instead
Example
Writing on a text file
#include<stdio.h>
#include<fstream>
Int main(){
Ofstream myfile;
Myfile.open(“c=/example.txt”);
Myfile(“this is a life \n”)
Myfile(“ this is another life \n”);
Myfile.close ()
Return 0;
}

Description of commands
i. Open a file
Inoder to open a file with stream object we used its members functions
toi open ()
Eg myfile .open (“c:\example.text”);
Internal name of part and external file name of file
A file and a command to write the same file
Ii closing a file
- When we are finished with our input and output of our files we
shall,closed it so that its resources became available again .This is done by
use of stream member function close()
Syntax
Myfile.close () take an argument
Example

69 Compiled by Mr.Rutoh Mike


#include<stdio.h>
#include<fstream>
#include<string>
Int main (){
String line;
Ifsream myfile;
Myfile.open (“F:\example txt”);
While (!myfile.eof()){
get line (myfile,file);
Printf (“line \n”);
}
Myfile.close()
Return 0;
}
Getline

-Ensure that the whole line of sentence consisting of string characters,spaces and special symbols is
read and stored in a particular variable in our case line.

E.O.F:

This last example read atxtfiles and brings out its content on the screen.We have used a new
member function called eof that returns true in the case that the end of the line has been Reached.

We have also created a while () loop that finishes when indeed myfile.eof() has become true i.e the
end of the file has been reached i.e e.of has been reached.

PROGRAM DOCUMENTATION

The program documentation is a kind of documentation that give a comprehensive procedural


description of a program.

I t shows as how s/w is written

Program documentation even has the capability to sustain any later maintenance or development of
the program.

IMPORTANCE OF SOFTWARE DOCUMENTATION

I .Clariffy your business goals,requirements and activities

With proper documentation you can share the business goals and requirements with your managers
and team –mates so that they have clear vision and goals and the activity they perform will be more
towards the success.

Ii Design and specify your product

This comes in architectural design documents and it gives you complete overview of how your
product taste like

70 Compiled by Mr.Rutoh Mike


Iii Everything is clearly explained

When you make end user documentation of the product of s\w you have to explain each and
everything about its working,It describers features of the program and assist the user in realizing
these features.

Iv Anybody can work on others codes;

If you are a developer, it is not sufficient toi write good codes only but also need to take care about
the documentation part, which can be helpful to other developers while working in a team.

V Helpful in proper communication

A good s\w documentation is helpful in proper communication the written procedure helps you to
make interaction with several departments.

Types of program documentation

S\w documentation is also reffered to as source code documentation and is a text that describes a
computer s\w.It explains how a s\w works but it can also explains how to use the s\w
properly.Several types of s\w documentation exist and can classified into:

I. User documentation

-Also known as s\w manuals user documentation intended for end-user and aims to help them use
s\w properly.It is usually arranged in a book style and typically also featured table of contenmts,
index and of course, the body which can be arranged different ways, depending on whom the s\w is
intended for.S\w manuals which is intended for immediate users on the other hand, are typically
arranged matricatically,while manuals for advanced users follow reference style.

ii. Technical documentation

Technical documentation is a very important part of s\w documentation of many programmers use
both terms interchangeably despite the fact technical documentation is only one of the several types
of s\w documentation.It describes codes but it is also addresses Algorithm,interfaces and other
technical aspects of s\w development and application .Technical documentation is usually created
by the programmers with the Aid of Auto-generating tools.

iii.Requirement document

Requirement documentation,also reffered to simply .As requirements explain what s\w does and
shall be able to do several types of requirements exists which may or may not be included in
documentation depending on purpose of complexity of the sytem.Eg application that don’t have any
safety implication and are not intended to be used for a longer period of time may be accompanied
at all.Those that affect human safety/or that are created to be used over a long period of time on
the other hand come with an exhausting documentation.

iv. Architectural documentation

71 Compiled by Mr.Rutoh Mike


-Also reffered as s/w archictured description, Archittecture documentation either analyses s\w
archictures or communicates the results of the later (work product).

It mainly deals with technical issues including online marketing and services but vital also covers
non-technical issues inorder to provide guidance to sytem developers,maintance,technicals and
others involved in the development or used of architecture including end users.

-Architecture documentation is usually arranged into architectural models which inturn may be
arranged into different views,each of which deals with specific issues.

72 Compiled by Mr.Rutoh Mike


73 Compiled by Mr.Rutoh Mike
74 Compiled by Mr.Rutoh Mike

You might also like