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

Structured Programming C

Uploaded by

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

Structured Programming C

Uploaded by

bwibo Michael
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 177

(NAIROBI CAMPUS)

COMPUTER SCIENCES DEPARTMENT

COURSE: DIPLOMA IN INFORMATION


COMMUNICATION TECHNOLOGY (ICT).
(MODULE I- KNEC)

UNIT NAME: STRUCTURED PROGRAMMING.

Michael Bwibo 0725327856 Page 1 of 142


TABLE OF CONTENTS:
SYLLABUS ................................................................................................................3
TOPIC 1 : INTRODUCTION TO STRUCTURED PROGRAMMING. ....................................4
Structured programming ........................................................................................4
Types of Structured Programming Language. ..........................................................6
History of Programming Languages ........................................................................7
PROGRAMMING PARADIGMS. ............................................................................... 10
Hardware and Software Considerations for Structured Programming. ...................... 11
TOPIC 2 : PROGRAM DEVELOPMENT AND DESIGN. .................................................. 14
Program Development and design ........................................................................ 14
Program Development Life Cycle .......................................................................... 14
Structured Programming Concepts ........................................................................ 20
Program Design Tools .......................................................................................... 22
TOPIC 3 : PROGRAM STRUCTURE. ........................................................................... 28
Program Structure ............................................................................................... 28
Format of A Structured Programming Language .................................................... 28
Operators ............................................................................................................ 28
Data Types.......................................................................................................... 36
TOPIC 4 : PROGRAM WRITING. ............................................................................... 39
Writing a program in a structured Language.......................................................... 39
Handling Errors. .................................................................................................. 40
TOPIC 5 : CONTROL STRUCTURES .......................................................................... 57
Control structures ................................................................................................ 57
Importance of Control Structures .......................................................................... 57
Types of Control Structures .................................................................................. 57
TOPIC 6: DATA STRUCTURES .................................................................................. 81
Data structure ..................................................................................................... 81
Types of Data structures ...................................................................................... 82
SORTING TECHNIQUES. .................................................................................... 107
SEARCHING TECHNIQUES .................................................................................. 123
TOPIC 7: SUBPROGRAMS ...................................................................................... 134
SUBPROGRAMS ................................................................................................. 134
Types of Sub programs ...................................................................................... 134
Scope of variables ............................................................................................. 134
Parameters........................................................................................................ 135
TOPIC 8 : FILE HANDLING .................................................................................... 147
Importance of file handling. ............................................................................... 147
Types of files. ......................................................... Error! Bookmark not defined.
File organisation techniques. .............................................................................. 153
File Design ........................................................................................................ 156
File handling operations ..................................................................................... 156
TOPIC 9 : PROGRAM DOCUMENTATION. ................................................................ 164
Program documentation ..................................................................................... 164
Types of Program Documentation ............................ Error! Bookmark not defined.

Michael Bwibo 0725327856 Page 2 of 142


Writing Program Documentation ......................................................................... 170
TOPIC TEN (10) EMERGING TRENDS IN PROGRAMMING ........................................ 173
Emerging trends in programming........................................................................ 173
Challenges Of Emerging Trends In Structured Programming. .. Error! Bookmark not
defined.

SYLLABUS
Code Sub-Module Content Total
Theory Practice Total
Unit
1.0 Introduction to -Structured 8 8
structured programming
programming -Types of structured
programming
languages
-History of
programming
languages
-Programming
paradigms
-Hardware and
Software
considerations for
structured
programming.
2.0 Program -Program development 24 24
development and design
-Program development
cycle
-Structured
programming concepts
-Program design tools
3.0 Program -Program Structure 8 8
structure -Format of Structured
programming concepts
-Operators
-Data types.
4.0 Program -Writing a program in 4 28 32
writing C and Pascal
-Error handling
5.0 Control -Control structure 8 24 32
Structure -Importance of Control
Structure
-Types of Control

Michael Bwibo 0725327856 Page 3 of 142


Structure
- Pattern in C and
Pascal.

6.0 Data structure -Data structures 8 32 40


-Types of data
structures
-Sort technigues
-Search techniques
7.0 Sub programs -Sub programs 8 24 32
-Types of sub
programs
-Scope of variables
Parameters
8.0 File Handling -Importance of file 4 8 12
handling
-Types of file
-File organization
techniques
-File design
-File handling
operations
9.0 Program -Program 4 4 8
documentation documentation
-Importance of
program
documentation
-Types of program
documentation
-Write programs
documentation
10.0 Emerging -Emerging trends in 4 4
trends in programming
Programming -Challenges of
emerging trends in
programming.

TOPIC 1 : INTRODUCTION TO STRUCTURED PROGRAMMING.

Structured programming – a technique for organizing and coding computer programs in which a
hierarchy of modules are used, each having a single entry and a single exit point, and in which
control is passed downward through the structure without unconditional branches to higher levels
of the structure.

Michael Bwibo 0725327856 Page 4 of 142


Computer hardware - refers to the physical parts of a computer and related devices. Internal
hardware devices include motherboards, hard drives, and RAM. External hardware devices include
monitors, keyboards, mice, printers, and scanners.
The internal hardware parts of a computer are often referred to as components, while external
hardware devices are usually called peripherals. Together, they all fall under the category of
computer hardware. Software, on the other hand, consists of the programs and applications that run
on computers. Because software runs on computer hardware, software programs often have system
requirements that list the minimum hardware required for the software to run.

Software - refers to the set of electronic program instructions or data a computer processor reads in
order to perform a task or operation. In contrast, the term 'hardware' refers to the physical
components that you can see and touch, such as the computer hard drive, mouse, and keyboard.
Software can be categorized according to what it is designed to accomplish. There are two main
types of software: systems software and application software.

Systems Software
Systems software includes the programs that are dedicated to managing the computer itself, such as
the operating system, file management utilities, and disk operating system (or DOS). The operating
system manages the computer hardware resources in addition to applications and data. Without
systems software installed in our computers we would have to type the instructions for everything
we wanted the computer to do.

Applications Software
Application software, or simply applications, are often called productivity programs or end-user
programs because they enable the user to complete tasks, such as creating documents, spreadsheets,
databases and publications, doing online research, sending email, designing graphics, running
businesses, and even playing games! Application software is specific to the task it is designed for and
can be as simple as a calculator application or as complex as a word processing application. When
you begin creating a document, the word processing software has already set the margins, font style
and size, and the line spacing for you. But you can change these settings, and you have many more
formatting options available. For example, the word processor application makes it easy to add
color, headings, and pictures or delete, copy, move, and change the document's appearance to suit
your needs.

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.
Programs are usually written to solve user problems on a computer.

Programming Language

Michael Bwibo 0725327856 Page 5 of 142


This is a set of symbols and the rules that govern their rules that are employed in the construction of
a computer program.

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.

Programmer
This is a person who is trained and/or specializes in the technique of creating, maintaining and
modifying computer programs.

Programming Languages

A programming language is a tool for developing executable models for a class of problem domains.
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.

Types of Structured Programming Language.

Pascal - A high-level programming language developed by Niklaus Wirth in the late 1960s. The
language is named after Blaise Pascal, a seventeenth-century French mathematician who constructed
one of the first mechanical adding machines. Pascal is best known for its affinity to structured
programming techniques. The nature of the language forces programmers to design programs
methodically and carefully. For this reason, it is a popular teaching language.
Despite its success in academia, Pascal has had only modest success in the business world. Part of
the resistance to Pascal by professional programmers stems from its inflexibility and lack of tools for
developing large applications. To address some of these criticisms, Wirth designed a new language
called Modula-2. Modula-2 is similar to Pascal in many respects, but it contains additional features.

C - C is a high-level and general-purpose programming language that is ideal for developing


firmware or portable applications. Originally intended for writing system software, C was developed
at Bell Labs by Dennis Ritchie for the Unix Operating System (OS) in the early 1970s.
Ranked among the most widely used languages, C has a compiler for most computer systems and
has influenced many popular languages – notably C++
C is a structured, procedural programming language that has been widely used both for operating
systems and applications and that has had a wide following in the academic community. Many
versions of UNIX-based operating systems are written in C. C has been standardized as part of the
Portable Operating System Interface (POSIX).

Fortran - Fortran is a programming language mainly used by the scientific community. Its name is a
contraction of FORmula TRANslation, and its aim is to provide a way to tell computers to calculate
complicated mathematical expressions, with more ease than assembly language. FORTRAN is one
of the earliest programming languages. The original versions used punched cards to write programs
with. FORTRAN's age is both a strength and a weakness. On one hand, FORTRAN has a huge

Michael Bwibo 0725327856 Page 6 of 142


number of libraries of code available. However, Fortran also has many archaic features, especially in
the earlier versions.
FORTRAN was designed for scientists and engineers, and has dominated this field. For the past 30
years FORTRAN has been used for such projects as the design of bridges and aeroplane structures,
it is used for factory automation control, for storm drainage design, analysis of scientific data and so
on. Throughout the life of this language, groups of users have written libraries of useful standard
FORTRAN programs.
COBOL - It is imperative, procedural and, since 2002, object-oriented. COBOL is primarily used in
business, finance, and administrative systems for companies and governments. COBOL is still
widely used in legacy applications deployed on mainframe computers, such as large-scale batch and
transaction processing jobs. But due to its declining popularity and the retirement of experienced
COBOL programmers, programs are being migrated to new platforms, rewritten in modern
languages or replaced with software packages. Most programming in COBOL is now purely to
maintain existing applications
LOGO - The Logo Programming Language, a dialect of Lisp, was designed as a tool for learning. Its
features - interactivity, modularity, extensibility, flexibility of data types - follow from this goal.
Although there are some versions of Logo that compile, it is generally implemented as an interpreted
language. The interactivity of this approach provides the user with immediate feedback on individual
instructions, thus aiding in the debugging and learning process. Error messages are descriptive. For
example
LISP - Lisp was originally created as a practical mathematical notation for computer programs,
influenced by the notation of Alonzo Church's lambda calculus. It quickly became the favored
programming language for artificial intelligence (AI) research. As one of the earliest programming
languages, Lisp pioneered many ideas in computer science, including tree data structures, automatic
storage management, dynamic typing, conditionals, higher-order functions, recursion, the self-
hosting compiler, closures, and the read–eval–print loop

History of Programming Languages

A program can be written in a 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

LOW LEVEL LANGUAGES

Machine Language (First Generation Language)


Digital computers represent and process data and instructions as binary numbers. This
representation of instructions and data is called machine language. Program instructions were
written as a series of binary digits (0’s and 1’s). When the program was entered into the computer
execution was direct since machine language needs no translation. The binary combination allowed
the program to have full access to and control the computers internal circuitry and memory
addresses.

Advantages
Program translation was fast because no conversion was required.

Michael Bwibo 0725327856 Page 7 of 142


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.
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.

Assembly Language (Second Generation)

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.

HIGH LEVEL LANGUAGES

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.

Michael Bwibo 0725327856 Page 8 of 142


High level languages can further be classified into :
Procedural languages (Third Generation)
Non-Procedural Languages (Fourth Generation Languages or 4GLs)

Procedural languages (Third Generation).

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 (Fourth Generation Languages or 4GLs).

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.

4GL consists of:


Report Generators: also called report writers. This is a program for end users that is used to
produce reports.
Query Language: This is an easy to use language for retrieving data from a database management
system.
Application Generators: This is a program’s tool that allows a person to give a detailed explanation
of what data to be processed. The software then generates codes needed to create a program to
perform the tasks.

Object Oriented Programming Languages

OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented


Programming (OOP) uses a different set of programming languages than old procedural
programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects".
Hence, you gain re-usability by means of four main object-oriented programming concepts.

An object can be considered a "thing" that can perform a set of related activities. The set of
activities that the object performs defines the object's behavior. For example, the hand can grip
something or a Student (object) can give the name or address.

Fifth-generation programming language

A fifth generation (programming) language (5GL) is a grouping of programming languages build on


the premise that a problem can be solved, and an application built to solve it, by providing

Michael Bwibo 0725327856 Page 9 of 142


constraints to the program (constraint-based programming), rather than specifying algorithmically
how the problem is to be solved (imperative programming).

In essence, the programming language is used to denote the properties, or logic, of a solution, rather
than how it is reached. Most constraint-based and logic programming languages are 5GLs. A
common misconception about 5GLs pertains to the practice of some 4GL vendors to denote their
products as 5GLs, when in essence the products are evolved and enhanced 4GL tools.

PROGRAMMING PARADIGMS.

Programming paradigms are a way to classify programming languages according to the style of
computer programming. Features of various programming languages determine which programming
paradigms they belong to; as a result, some languages fall into only one paradigm, while others fall
into multiple paradigms. Some paradigms are concerned mainly with implications for the execution
model of the language, such as allowing side effects, or whether the sequence of operations is
defined by the execution model. Other paradigms are concerned mainly with the way that code is
organized, such as grouping code into units along with the state that is modified by the code. Yet
others are concerned mainly with the style of syntax and grammar. A programming paradigm is an
approach to solving programming problems.

1) Un structured programming.

An unstructured program is a procedural program – the statements are executed in sequence as


written. But this type of programming uses the goto statement. A goto statement allows control to
be passed to any other place in the program. When a goto statement is executed, the sequence
continues from the target of the goto. Thus to understand how a program works, you have to
pretend to execute it. This means that it is often difficult to understand the logic of such a program.
Some program compilers cross-index where a goto connects to, making it practical to rapidly
navigate the source code. However, it was a common practice in some programming languages to
use a variable in association with where the goto goes, making automated indexing impractical.
There are similar problems in some structured programming languages, such as how foreign
language views are implemented, to permit many people to view the same computer data, in their
human language.

2) Structured programming
Structured programming (sometimes known as modular programming) is a subset of procedural
programming that enforces a logical structure on the program being written to make it more
efficient and easier to understand and modify. Certain languages such as Ada, Pascal, and dBASE are
designed with features that encourage or enforce a logical program structure.
A technique for organizing and coding computer programs in which a hierarchy of modules is used,
each having a single entry and a single exit point, and in which control is passed downward through
the structure without unconditional branches to higher levels of the structure. Three types of control
flow are used: sequential, test, and iteration.

3) Object Oriented Programming

Michael Bwibo 0725327856 Page 10 of 142


Object Oriented Programming (OOP) is a paradigm in which real-world objects are each viewed as
seperate entities having their own state which is modified only by built in procedures, called
methods. Because objects operate independently, they are encapsulated into modules which contain
both local environments and methods. Communication with an object is done by message passing.
Object-oriented programming (OOP) is a programming language model organized around objects
rather than "actions" and data rather than logic. Historically, a program has been viewed as a logical
procedure that takes input data, processes it, and produces output data.

4) Visual Programming.
In computing, a visual programming language (VPL) is any programming language that lets users
create programs by manipulating program elements graphically rather than by specifying them
textually. A VPL allows programming with visual expressions, spatial arrangements of text and
graphic symbols, used either as elements of syntax or secondary notation. For example, many VPLs
(known as dataflow or diagrammatic programming) are based on the idea of "boxes and arrows",
where boxes or other screen objects are treated as entities, connected by arrows, lines or arcs which
represent relations.

5) Internet Based programming.

Web programming refers to the writing, markup and coding involved in Web development, which
includes Web content, Web client and server scripting and network security. The most common
languages used for Web programming are XML, HTML, JavaScript, Perl 5 and PHP. Web
programming is different from just programming, which requires interdisciplinary knowledge on the
application area, client and server scripting, and database technology.
Web programming can be briefly categorized into client and server coding. The client side needs
programming related to accessing data from users and providing information. It also needs to ensure
there are enough plug ins to enrich user experience in a graphic user interface, including security
measures.
To improve user experience and related functionalities on the client side, JavaScript is usually used.
It is an excellent client-side platform for designing and implementing Web applications.
HTML5 and CSS3 supports most of the client-side functionality provided by other application
frameworks.

Hardware and Software Considerations for Structured Programming.

- Structured programs written for one system can be run with little or no modification on other
systems.
- There are several Pascal compilers and interpreters available for general use. Among these are:
Turbo Pascal: provides an IDE and compiler for running Pascal programs on CP/M, CP/M-86,
DOS, Windows and Macintosh.
Delphi: provides compilers for running Object Pascal and generates native code for 32- and 64-
bit Windows operating systems, as well as 32-bit Mac OS X and iOS. Embarcadero is planning to
build support for the Linux and Android operating system.
Free Pascal: it is a free compiler for running Pascal and Object Pascal programs. Free Pascal
compiler is a 32- and 64-bit Turbo Pascal and Delphi compatible Pascal compiler for Linux,
Windows, OS/2, FreeBSD, Mac OS X, DOS and several other platforms.

Michael Bwibo 0725327856 Page 11 of 142


Turbo51: it is a free Pascal compiler for the 8051 family of microcontrollers, with Turbo Pascal 7
syntax.
Oxygene: it is an Object Pascal compiler for the .NET and Mono platforms.
GNU Pascal (GPC): it is a Pascal compiler composed of a front end to GNU Compiler
Collection.

- The source code written in source file is the human readable source for your program. It needs to
be "compiled", to turn into machine language so that your CPU can actually execute the program as
per instructions given.
This C programming language compiler will be used to compile your source code into final
executable program. Most frequently used and free available compiler is GNU C/C++ compiler.

Hardware requirements.
Architecture
All computer operating systems are designed for a particular computer architecture. Most software
applications are limited to particular operating systems running on particular architectures. Although
architecture-independent operating systems and applications exist, most need to be recompiled to
run on a new architecture.

Processing power
The power of the central processing unit (CPU) is a fundamental system requirement for any
software. Most software running on x86 architecture define processing power as the model and the
clock speed of the CPU. Many other features of a CPU that influence its speed and power, like bus
speed, cache, and MIPS are often ignored. This definition of power is often erroneous, as AMD
Athlon and Intel Pentium CPUs at similar clock speed often have different throughput speeds. Intel
Pentium CPUs have enjoyed a considerable degree of popularity, and are often mentioned in this
category.

Memory
All software, when run, resides in the random access memory (RAM) of a computer. Memory
requirements are defined after considering demands of the application, operating system, supporting
software and files, and other running processes. Optimal performance of other unrelated software
running on a multi-tasking computer system is also considered when defining this requirement.
Secondary storage
Hard-disk requirements vary, depending on the size of software installation, temporary files created
and maintained while installing or running the software, and possible use of swap space (if RAM is
insufficient).
Display adapter
Software requiring a better than average computer graphics display, like graphics editors and high-
end games, often define high-end display adapters in the system requirements.
Peripherals
Some software applications need to make extensive and/or special use of some peripherals,
demanding the higher performance or functionality of such peripherals. Such peripherals include
CD-ROM drives, keyboards, pointing devices, network devices, etc.

Software requirements

Michael Bwibo 0725327856 Page 12 of 142


Software requirements deal with defining software resource requirements and prerequisites that need
to be installed on a computer to provide optimal functioning of an application. These requirements
or prerequisites are generally not included in the software installation package and need to be
installed separately before the software is installed.
Platform
A computing platform describes some sort of framework, either in hardware or software, which
allows software to run. Typical platforms include a computer's architecture, operating system, or
programming languages and their runtime libraries.
Operating system is one of the requirements mentioned when defining system requirements
(software). Software may not be compatible with different versions of same line of operating
systems, although some measure of backward compatibility is often maintained. For example, most
software designed for Microsoft Windows XP does not run on Microsoft Windows 98, although the
converse is not always true. Similarly, software designed using newer features of Linux Kernel v2.6
generally does not run or compile properly (or at all) on Linux distributions using Kernel v2.2 or
v2.4.
APIs and drivers
Software making extensive use of special hardware devices, like high-end display adapters, needs
special API or newer device drivers. A good example is DirectX, which is a collection of APIs for
handling tasks related to multimedia, especially game programming, on Microsoft platforms.

Michael Bwibo 0725327856 Page 13 of 142


TOPIC 2 : PROGRAM DEVELOPMENT AND DESIGN.

Program Development and design

Software development is the process of computer programming, documenting, testing, and bug
fixing involved in creating and maintaining applications and frameworks resulting in a software
product. Software development is a process of writing and maintaining the source code, but in a
broader sense, it includes all that is involved between the conception of the desired software
through to the final manifestation of the software, sometimes in a planned and structured process.
Therefore, software development may include research, new development, prototyping,
modification, reuse, re-engineering, maintenance, or any other activities that result in software
products.

Program Design
Software design is the process by which an agent creates a specification of a software artifact,
intended to accomplish goals, using a set of primitive components and subject to constraints.
Software design may refer to either all the activity involved in conceptualizing, framing,
implementing, commissioning, and ultimately modifying complex systems or the activity following
requirements specification and before programming, as a stylized software engineering process.
Software design usually involves problem solving and planning a software solution. This includes
both a low-level component and algorithm design and a high-level, architecture design.

Cohesion
• Cohesion is the indication of the relationship within module.
• Cohesion shows the module’s relative functional strength.
• Cohesion is a degree (quality) to which a component / module focuses on the single thing.
• While designing you should strive for high cohesion i.e. a cohesive component/ module
focus on a single task (i.e., single-mindedness) with little interaction with other modules of the
system.
• Cohesion is the kind of natural extension of data hiding for example, class having all
members visible with a package having default visibility. Cohesion is Intra – Module Concept.
Coupling
• Coupling is the indication of the relationships between modules.
• Coupling shows the relative dependence/interdependence among the modules.
• Coupling is a degree to which a component / module is connected to the other modules.
• While designing you should strive for low coupling i.e. dependency between modules should
be less
• Making private fields, private methods and non public classes provides loose coupling.
• Coupling is Inter -Module Concept.

Michael Bwibo 0725327856 Page 14 of 142


Program Development Life Cycle

1. Design program objectives


It involves forming a clear idea in terms of the information you want to include in the program,
computations needed and the output. At this stage, the programmer should think in general terms,
not in terms of some specific computer language.

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.

3. Write the Code


It is the design Implementation by writing the (C) code i.e. translating your program design into C
language instructions. You will use C’s text editor or any other editor such as notepad. Using
another editor such as notepad requires you to save your program with the extension .c.

4. Compile the code


A compiler converts the source code into object code. Object codes are instructions in machine
language. Computers have different machine languages. C compilers also incorporate code for C
libraries into the final program. The libraries contain standard routines. The end result is an
executable file that the computer can understand.
The compiler also checks errors in your program and reports the error to you for correction. The
object code can never be produced if the source code contains syntax errors.

5. Run the program


This is the actual execution of the final code, usually preceded by linking#. Once the executable
code is complete and working, it can be invoked in future by typing its name in a ‘run’ command.

6. Test the program


This involves checking whether the system does what it is supposed to do. Programs may have bugs
(errors). Debugging involves the finding and fixing of program mistakes.

7. Maintain and modify the program


Occasionally, changes become necessary to make to a given program. You may think of a better way
to do something in a program, a clever feature or you may want to adapt the program to run in a
different machine. These tasks are simplified greatly if you document the program clearly and
follow good program design practices.

Types of Software Testing


Introduction:-

Michael Bwibo 0725327856 Page 15 of 142


Testing is a process of executing a program with the aim of finding error. To make our software
perform well it should be error free.If testing is done successfully it will remove all the errors from
the software.
Principles of Testing:-

(i) All the test should meet the customer requirements


(ii) To make our software testing should be performed by third party
(iii) Exhaustive testing is not possible.As we need the optimal amount of testing based on the risk
assessment of the application.
(iv) All the test to be conducted should be planned before implementing it
(v) It follows pareto rule(80/20 rule) which states that 80% of errors comes from 20% of program
components.
(vi) Start testing with small parts and extend it to large parts.

Types of Testing:-
1. Unit Testing
It focuses on smallest unit of software design. In this we test an individual unit or group of inter
related units. It is often done by programmer by using sample input and observing its corresponding
outputs.
Example:
a) In a program we are checking if loop, method or
function is working fine
b) Misunderstood or incorrect, arithmetic precedence.
c) Incorrect initialization

2. Integration Testing
The objective is to take unit tested components and build a program structure that has been dictated
by design. Integration testing is testing in which a group of components are combined to produce
output.
Integration testing are of two types: (i) Top down (ii) Bottom up
Example
(a) Black Box testing:- It is used for validation.
In this we ignores internal working mechanism and
focuses on what is the output?.

(b) White Box testing:- It is used for verification.


In this we focus on internal mechanism i.e.
how the output is achieved?

3. Regression Testing
Every time new module is added leads to changes in program. This type of testing make sure that
whole component works properly even after adding components to the complete program.
Example
In school record suppose we have module staff, students and finance combining these modules and
checking if on integration these module works fine is regression testing.

4. Smoke Testing

Michael Bwibo 0725327856 Page 16 of 142


This test is done to make sure that software under testing is ready or stable for further testing
It is called smoke test as testing initial pass is done to check if it did not catch the fire or smoked in
the initial switch on.
Example:

5. Alpha Testing
This is a type of validation testing.It is a type of acceptance testing which is done before the product
is released to customers. It is typically done by QA people.
Example:
When software testing is performed internally within the organization

6. Beta Testing
The beta test is conducted at one or more customer sites by the end-user of the software. This
version is released for the limited number of users for testing in real time environment
Example:
When software testing is performed for the limited number of people

7. System Testing
In this software is tested such that it works fine for different operating system. It is covered under
the black box testing technique. In this we just focus on required input and output without focusing
on internal working.
In this we have security testing, recovery testing , stress testing and performance testing
Example:
This include functional as well as non functional testing

8. Stress Testing
In this we gives unfavorable conditions to the system and check how they perform in those
condition. Stress testing refers to the testing of software or hardware to determine whether its
performance is satisfactory under any extreme and unfavorable conditions, which may occur as a
result of heavy network traffic, process loading, underclocking, overclocking and maximum requests
for resource utilization.
Example:
(a) Test cases that require maximum memory or other resources are executed
(b) Test cases that may cause thrashing in a virtual operating system
(c) Test cases that may cause excessive disk requirement

9. Performance Testing
It is designed to test the run-time performance of software within the context of an integrated
system. It is used to test speed and effectiveness of program.
Example:
Checking number of processor cycles.

Differences Between Black Box Testing and White Box Testing


The Differences Between Black Box Testing and White Box Testing are listed below.
Criteria Black Box Testing White Box Testing
Definition Black Box Testing is a software testing White Box Testing is a software

Michael Bwibo 0725327856 Page 17 of 142


method in which the internal structure/ testing method in which the internal
design/ implementation of the item structure/ design/ implementation of
being tested is NOT known to the tester the item being tested is known to the
tester.
Mainly applicable to higher levels of Mainly applicable to lower levels of
Levels Applicable
testing:Acceptance Testing testing:Unit Testing
To
System Testing Integration Testing
Responsibility Generally, independent Software Testers Generally, Software Developers
Programming
Not Required Required
Knowledge
Implementation
Not Required Required
Knowledge
Basis for Test
Requirement Specifications Detail Design
Cases

Verification
Verification is the process to make sure the product satisfies the conditions imposed at the start of
the development phase. In other words, to make sure the product behaves the way we want it to.
Validation
Validation is the process to make sure the product satisfies the specified requirements at the end of
the development phase. In other words, to make sure the product is built as per customer
requirements.
Blackbox Testing
Black box testing is a testing technique that ignores the internal mechanism of the system and
focuses on the output generated against any input and execution of the system. It is also called
functional testing.
Whitebox Testing
White box testing is a testing technique that takes into account the internal mechanism of a system.
It is also called structural testing and glass box testing.
Black box testing is often used for validation and white box testing is often used for verification.

Unit Testing
Unit testing is the testing of an individual unit or group of related units. It falls under the class of
white box testing. It is often done by the programmer to test that the unit he/she has implemented
is producing expected output against given input.

Integration Testing
Integration testing is testing in which a group of components are combined to produce output. Also,
the interaction between software and hardware is tested in integration testing if software and
hardware components have any relation. It may fall under both white box testing and black box
testing.

Functional Testing
Functional testing is the testing to ensure that the specified functionality required in the system
requirements works. It falls under the class of black box testing.

Michael Bwibo 0725327856 Page 18 of 142


System Testing
System testing is the testing to ensure that by putting the software in different environments (e.g.,
Operating Systems) it still works. System testing is done with full system implementation and
environment. It falls under the class of black box testing.

Stress Testing
Stress testing is the testing to evaluate how system behaves under unfavorable conditions. Testing is
conducted at beyond limits of the specifications. It falls under the class of black box testing.

Performance Testing
Performance testing is the testing to assess the speed and effectiveness of the system and to make
sure it is generating results within a specified time as in performance requirements. It falls under the
class of black box testing.

Usability Testing
Usability testing is performed to the perspective of the client, to evaluate how the GUI is user-
friendly? How easily can the client learn? After learning how to use, how proficiently can the client
perform? How pleasing is it to use its design? This falls under the class of black box testing.

Acceptance Testing
Acceptance testing is often done by the customer to ensure that the delivered product meets the
requirements and works as the customer expected. It falls under the class of black box testing.

Regression Testing
Regression testing is the testing after modification of a system, component, or a group of related
units to ensure that the modification is working correctly and is not damaging or imposing other
modules to produce unexpected results. It falls under the class of black box testing.

Beta Testing
Beta testing is the testing which is done by end users, a team outside development, or publicly
releasing full pre-version of the product which is known as beta version. The aim of beta testing is
to cover unexpected errors. It falls under the class of black box testing.

Alpha testing
A type of acceptance testing; performed to identify all possible issues/bugs before releasing the
product to everyday users or public. The focus of this testing is to simulate real users by using
blackbox and whitebox techniques. The aim is to carry out the tasks that a typical user might
perform. Alpha testing is carried out in a lab environment and usually the testers are internal
employees of the organization. To put it as simple as possible, this kind of testing is called alpha only
because it is done early on, near the end of the development of the software, and before beta testing.

Alpha Testing Beta Testing


Alpha testing performed by Testers who are Beta testing is performed by Clients or End Users
usually internal employees of the organization who are not employees of the organization
Alpha Testing performed at developer's site Beta testing is performed at client location or end

Michael Bwibo 0725327856 Page 19 of 142


user of the product
Reliability and Security Testing are not performed Reliability, Security, Robustness are checked
in-depth Alpha Testing during Beta Testing
Alpha testing involves both the white box and
Beta Testing typically uses Black Box Testing
black box techniques
Beta testing doesn't require any lab environment
Alpha testing requires lab environment or testing or testing environment. Software is made
environment available to the public and is said to be real time
environment
Long execution cycle may be required for Alpha Only few weeks of execution are required for
testing Beta testing
Most of the issues or feedback is collected from
Critical issues or fixes can be addressed by
Beta testing will be implemented in future
developers immediately in Alpha testing
versions of the product
Beta testing also concentrates on quality of the
Alpha testing is to ensure the quality of the product, but gathers users input on the product
product before moving to Beta testing and ensures that the product is ready for real time
users.

Structured Programming Concepts

Structuring a program breaks it down into understandable chunks. Structured programming is an


approach to writing programs that are easier to read, test, debug and modify. The approach assists in
the development of large programs through stepwise refinement and 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.

In short, structured programming serves to increase programmer productivity, program reliability


(readability and execution time), program testing, program debugging and serviceability.

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.

Michael Bwibo 0725327856 Page 20 of 142


Bottom-up Approach

In this design approach, the application is developed starting at the bottom of 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. It's a long-standing principle of programming style that the
functional elements of a program should not be too large. If some component of a program grows
beyond the stage where it's readily comprehensible, it becomes a mass of complexity which conceals
errors as easily as a big city conceals fugitives. Such software will be hard to read, hard to test, and
hard to debug.

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.

Advantages of modular programming

Modules can be reused thus saving development time.


Testing of individual modules in isolation makes tracing mistakes easier.
An amendment to a single module does not affect the rest of the program.
Ability to create libraries of often used routines which are reliable and can go into other programs.

Monolithic programming.

Michael Bwibo 0725327856 Page 21 of 142


In software engineering, a monolithic application describes a single-tiered software application in
which the user interface and data access code are combined into a single program from a
single platform. A monolithic application is self-contained, and independent from other computing
applications.

Indicates the program which contains a single function for the large program i.e. monolithic
programming will not divide the program and it is a single thread of execution. When the program
size increases it becomes difficult to maintain. This design approach is highly discouraged due to the
following reasons.
Difficult to check errors on large programs.
Code can be specific to a particular problem i.e. it cannot be re-used.

Control Flow Structure

Program Design Tools

Algorithms

A programming algorithm is a computer procedure that is a lot like a recipe (called a procedure) and
tells your computer precisely what steps to take to solve a problem or reach a goal. The ingredients
are called inputs, while the results are called the outputs.

The characteristics of a good algorithm are:


Precision – the steps are precisely stated(defined).
Uniqueness – results of each step are uniquely defined and only depend on the input and the result
of the precedingsteps.
Finiteness – the algorithm stops after a finite number of instructions are executed.
Input – the algorithm receives input.
Output – the algorithm produces output.
Generality – the algorithm applies to a set of inputs.

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

Michael Bwibo 0725327856 Page 22 of 142


Increment counter by one
Check the value of the counter
If counter < 6
Loop to step 3
End

Flowchart In Programming

Flowchart is a diagrammatic representation of an algorithm. Flowchart are very helpful in writing


program and explaining program to others.

Symbols Used In Flowchart

Different symbols are used for different states in flowchart, For example: Input/Output and
decision making has different symbols. The table below describes all the symbols that are used in
making flowchart

Symbol Purpose Description


Flow line Used to indicate the flow of logic by connecting symbols.

Terminal(Stop/Start) Used to represent start and end of flowchart.

Input/Output Used for input and output operation.

Processing Used for airthmetic operations and data-manipulations.

Used to represent the operation in which there are two


Desicion
alternatives, true and false.

On-page Connector Used to join different flowline

Off-page Connector Used to connect flowchart portion on different page.

Predefined Used to represent a group of statements performing one


Process/Function processing task.
Examples of flowcharts in programming

Draw a flowchart to add two numbers entered by user.

Michael Bwibo 0725327856 Page 23 of 142


Draw a flowchart to input two numbers from user and display the largest of two numbers

Advantages Of Using FLOWCHARTS:

• Communication: Flowcharts are better way of communicating the logic of a system to all
concerned or involved.
• Effective analysis: With the help of flowchart, problem can be analyzed in more effective way
therefore reducing cost and wastage of time.

Michael Bwibo 0725327856 Page 24 of 142


• Proper documentation: Program flowcharts serve as a good program documentation, which is
needed for various purposes, making things more efficient.
• Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
• Proper Debugging: The flowchart helps in debugging process.
• Efficient Program Maintenance: The maintenance of operating program becomes easy with the
help of flowchart. It helps the programmer to put efforts more efficiently on that part

Disadvantages Of Using FLOWCHARTS:

• Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes
complex and clumsy. This will become a pain for the user, resulting in a waste of time and money
trying to correct the problem
• Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely. This will usually waste valuable time.
• Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a
problem.

Advantages of the Pseudo code

• Since it is a language-independent it can be used by most programmers it allows the


developer to express the design in plain and natural language.
• It is easier to develop a program from a pseudo code as compared to the flow chart.
Programmers do not have to think about syntax, we simply have to concentrate on the
underline logic. The focus is on the steps to solve a problem rather than how to use the
computer language.
• Often it is easy to translate pseudocode into a programming language, a step which can be
accomplished by less experienced
• The uses of words and phrases in pseudo code, which are in the lines of basic computer
operations simplify the translation from the pseudo code algorithm to the specific
programming language.
• Unlike flow charts, pseudo code is at and does not tend to run over many pages. Its simple
structure and readability make it easier to modify.
• The pseudocode allows programmers to work in different computer languages to talk to
others they can be reviewed by groups easier than the real code.

Disadvantages/limitation of Pseudo Code:

• The main disadvantages are that it does not provide a visual representation of the
programming logic.
• There are no accepted standards for writing the pseudo code. Programmers use their own
styles of writing pseudo code.
• The pseudo code cannot be compiled nor executed and there is no real formative of a syntax
of rules. It is simply one step, an important one, in producing the final code.

Michael Bwibo 0725327856 Page 25 of 142


Decision Tables.
A decision table is an excellent tool to use in both testing and requirements management. Essentially
it is a structured exercise to formulate requirements when dealing with complex business rules.
Decision tables are used to model complicated logic. They can make it easy to see that all possible
combinations of conditions have been considered and when conditions are missed. Decision tables,
like flowcharts, if-then-else, and switch-case statements, associate conditions with actions to
perform, but in many cases do so in a more elegant way.

Decision Tables

Decision table is a brief visual representation for specifying which actions to perform depending
on given conditions. The information represented in decision tables can also be represented as
decision trees or in a programming language using if-then-else and switch-case statements.

A decision table is a good way to settle with different combination inputs with their corresponding
outputs and also called cause-effect table. Reason to call cause-effect table is a related logical
diagramming technique called cause-effect graphing that is basically used to obtain the decision
table.

Conditions =
(
Printer does not print |Y|Y|Y|Y|N|N|N|N|
A red light is flashing |Y|Y|N|N|Y|Y|N|N|
Printer is unrecognized |Y|N|Y|N|Y|N|Y|N|
)

Actions=
(
Check the power cable | | |x| | | | | |
Check the printer-computer cable |x| |x| | | | | |
Ensure printer software is installed |x| |x| |x| |x| |
Check/replace ink |x|x| | |x|x| | |
Check for paper jam | |x| |x| | | | |
)

Michael Bwibo 0725327856 Page 26 of 142


Michael Bwibo 0725327856 Page 27 of 142
TOPIC 3 : PROGRAM STRUCTURE.

Program Structure
The overall form of a program, with particular emphasis on the individual components of the
program and the interrelationships between these components. Programs are frequently referred to
as either well structured or poorly structured. With a well-structured program the division into
components follows some recognized principle such as information hiding, and the interfaces
between components are explicit and simple. By contrast, with a poorly structured program the
division into components is largely arbitrary (or even nonexistent), and interfaces are implicit and
complex.

Format of A Structured Programming Language

"Sequence"; ordered statements or subroutines executed in sequence.


"Selection"; one or a number of statements is executed depending on the state of the program. This
is usually expressed with keywords such as if..then..else..end if.
"Iteration"; a statement or block is executed until the program reaches a certain state, or operations
have been applied to every element of a collection. This is usually expressed with keywords such as
while, repeat, for or do..Until. Often it is recommended that each loop should only have one entry
point (and in the original structural programming, also only one exit point, and a few languages
enforce this).
"Recursion"; a statement is executed by repeatedly calling itself until termination conditions are met.
While similar in practice to iterative loops, recursive loops may be more computationally efficient,
and are implemented differently as a cascading stack.

Operators
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).

An operand can be a constant value, a variable name or a symbolic constant.

Note: An expression is a combination of operators and operands.

Examples
x + y ; x, y are operands, + is an addition operator.

Michael Bwibo 0725327856 Page 28 of 142


3 * 5; 3, 5 are constant operands, * is a multiplication operator.
x % 2.5; x, 5 are operands, % is a modulus (remainder) operator.
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:
There exists no exponential operators in C.
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).
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.
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.
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:
c1 and c2 are character constants
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

Michael Bwibo 0725327856 Page 29 of 142


a+b =8
a – b = 14
a * b = -33
a / b = -3
a % b = -2
c % b = -2
c/b=3

Examples of floating point arithmetic operators


r1 = -0.66, r2 = 4.50 (operands with different signs)
r1 + r2 = 3.84
r1 - r2 = -5.16
r1 * r2 = -2.97
r1 / r2 = -0.1466667

Note:
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).
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.
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).
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)

From the above, evaluate the following expressions given:


i =7, f = 5.5, c = ’w’. State the type of the result.

i+f
i+c
i + c-‘w’
( i + c) - ( 2 * f / 5)

(‘w” has ASCII decimal value of 119)

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:

(data type) expression.


The data type must be enclosed in parenthesis (). For example the expression (i + f) above evaluates
to 12.5. To convert this to an integer, it will be necessary to write
(int) (i + f).

Operator Precedence

Michael Bwibo 0725327856 Page 30 of 142


The order of executing the various operations makes a significant difference in the result. C assigns
each operator a precedence level. The rules are;

Multiplication and division have a higher precedence than addition and subtraction, so they are
performed first.

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.

Consider the statement;


butter = 25.0 + 60.0 * n / SCALE;
Where n = 6.0 and SCALE = 2.0.

The order of operations is as follows;


First: 60.0 * n = 360.0
(Since * and / are first before + but * and / share the operand n with * first)

Second: 360.0 / SCALE = 180


(Division follows)

Third: 25.0 + 180 = 205.0 (Result)


(+ comes last)

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.

What is the result of the above expression written as:


+ 60.0 * n) / SCALE.

Example: Use of operators and their precedence


/* Program to demonstrate use of operators and their precedence */
include<stdio.h >
main()
{
int score,top;
score = 30;
top = score - (2*5) + 6 * (4+3) + (2+3);
printf (“top = %d \ n” , top);
system(“pause”);
return 0;
}
Try changing the order of evaluation by shifting the parenthesis and note the change in the top
score.

Example: Converting seconds to minutes and seconds using the % operator


#include<stdio.h >

Michael Bwibo 0725327856 Page 31 of 142


#define SEC_PER_MIN 60
main()
{
int sec, min, sec_left;
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);
system(“pause”);
return 0;
}

The size of 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.

Example : Demonstrating ‘sizeof’ operator


#include <stdio.h>
main()
{
int n;
printf(“n has % d bytes; all ints have % d bytes \n”, sizeof n, sizeof(int)) ;
system(“pause”);
return 0;
}
The Assignment Operator
The Assignment operator ( = ) is a value assigning operator. There are several other assignment
operators in C. All of them assign the value of an expression to an identifier.

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;

Note

Michael Bwibo 0725327856 Page 32 of 142


You cannot assign a variable to a constant such as 3 = a ;
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.
Multiple assignments are possible e.g. a =b = 5 ; assigns the integer value 5 to both a and b.
Assignment can be combined with +, -, /, *, and %

The Conditional Operator


Conditional tests can be carried out with the conditional operator (?). A conditional expression takes
the form:

expression1 ? expression2 : expression3 and implies;

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.

Consider the statement (i < 0) ? 0 :100

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 single operand to produce a value. The operators may precede the
operand or are after an operand.

Examples
Unary minus e.g. - 700 or –x
Incrementation operator e.g. c++
Decrementation operator e.g. f - -
sizeof operator e.g. sizeof( float)

Relational Operators

There are four relational operators in C.

< Less than


<= Less than or equal to
> Greater than
>= Greater than or equal to

Closely associated with the above are two equality operators;


= = Equal to
!= Not equal to

Michael Bwibo 0725327856 Page 33 of 142


The above six operators form logical expressions.

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

&& Logical AND


|| Logical OR
! NOT

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;

(i > = = 6 ) && ( C = = ‘w’ ) is 1 (true)


( C’ > = 6 ) || (C = 119 ) is 1 (true)
(f < 11 ) && (i > 100) is 0 (false)
(C! = ‘ p’) || ((i + f) < = 10 ) is 1 (true)

Revision Exercises

Describe with examples, four relational operators.


What is ‘operator precedence’? Give the relative precedence of arithmetic operators.
Suppose a, b, c are integer variables that have been assigned the values a =8, b = 3 and c = - 5, x, y,
z are floating point variables with values x =8.8, y = 3.5, z = -5.2.

Further suppose that c1, c2, c3 are character-type variables assigned the values E, 5 and ?
respectively.

Determine the value of each of the following expressions:


a/b (v) x % y
2 * b + 3 * (a – c) (vi) 2 * x / (3 * y)

Michael Bwibo 0725327856 Page 34 of 142


(a * c) % b (vii) c1 / c3
(x / y) + z (viii) (c1 / c2) * c3
In C, precedence of arithmetic operators( *, %, /, +, -) is higher than relational operators(==, !=,
>, <, >=, <=) and precedence of relational operator is higher than logical operators(&&, || and !).

Operator Meaning of operator Associativity

() Functional call
[] Array element reference
-> Indirect member selection
. Direct member selection Left to right

! Logical negation
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
-- Decrement
& Dereference Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion) Right to left

* Multiply
/ Divide
% Remainder Left to right

+ Binary plus(Addition)
- Binary minus(subtraction) Left to right

<< Left shift


>> Right shift Left to right

< Less than


<= Less than or equal
> Greater than
>= Greater than or equal Left to right

== Equal to
!= Not equal to Left to right

& Bitwise AND Left to right

^ Bitwise exclusive OR Left to right

Michael Bwibo 0725327856 Page 35 of 142


Operator Meaning of operator Associativity

| Bitwise OR Left to right

&& Logical AND Left to right

|| Logical OR Left to right

?: Conditional Operator Right to left

Simple assignment
= Assign product
*= Assign quotient
/= Assign remainder
%= Assign sum
-= Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift Right to left

, Separator of expressions Left to right

Summary of C operators with precedence and associativity

Data Types
In computer programming, a data type or simply type is a classification of data which tells the
compiler or interpreter how the programmer intends to use the data. Most programming languages
support various types of data, for example: real, integer or Boolean. A Data type provides a set of
values from which an expression (i.e. variable, function ...) may take its values. The type defines the
operations that can be done on the data, the meaning of the data, and the way values of that type
can be stored.

Simple Data types - primitive data type is either of the following:


a basic type is a data type provided by a programming language as a basic building block. Most
languages allow more complicated composite types to be recursively constructed starting from basic
types.
a built-in type is a data type for which the programming language provides built-in support.
They include
Type Meaning Keyword
Character Character data Char
Integer Signed whole number Int

Michael Bwibo 0725327856 Page 36 of 142


Float floating-point numbers Float
Double double precision floating-point Double
numbers
Void Valueless Void

The ‘int’ specifier


It is a type specifier used to declare integer variables. For example, to declare count as an integer you
would write:
int count;

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.

The ‘char’ specifier


A variable of type char is 1 byte long and is mostly used to hold a single character. For example to
declare ch to be a character type, you would write:
char ch;

The ‘float’ specifier


It is a type specifier used to declare floating-point variables. These are numbers that have a whole
number part and a fractional or decimal part for example 234.936. To declare f to be of type float,
you would write:
float f;
Floating point variables typically occupy 4 bytes.
The ‘double’ specifier
It is a type specifier used to declare double-precision floating point variables. These are variables that
store float point numbers with a precision twice the size of a normal float value. To declare d to be
of type double you would write:
double d;
Double-type variables typically occupy 8 bytes.

Structured Data Type (SDT)

Largely known as Record, Struct or Structure in most programming languages, it is the GeneXus
object which allows defining complex data structures. An SDT represents data whose structure is
made up of several elements like a Customer struct. The SDT makes it easy to transfer parameters
(more specifically, they allow providing/using structured information when using web services), it
simplifies XML automatic reading and writing and makes it possible to manage variable-length lists
of elements.

A user-defined data type (UDT)

Is a data type that derived from an existing data type. You can use UDTs to extend the built-in types
already available and create your own customized data types.
A structured type is a user-defined data type that has a structure that is defined in the database. It
contains a sequence of named attributes, each of which has a data type. A structured type also
includes a set of method specifications.

Michael Bwibo 0725327856 Page 37 of 142


A structured type can be used as the type of a table, view, or column. When used as a type for a
table or view, that table or view is known as a typed table or typed view. For typed tables and typed
views, the names and data types of the attributes of the structured type become the names and data
types of the columns of this typed table or typed view. Rows of the typed table or typed view can be
thought of as a representation of instances of the structured type. When used as a data type for a
column, the column contains values of that structured type (or values of any of the subtypes for that
type, as defined later in this section). Methods are used to retrieve or manipulate attributes of a
structured column object.
A supertype is a structured type for which other structured types, called subtypes, are defined. A
subtype inherits all the attributes and methods of its supertype and can have additional attributes and
methods defined. The set of structured types that is related to a common supertype is called a type
hierarchy and the type that does not have any supertype is called the root type of the type hierarchy.

Identifiers, Expressions and I/O Instructions

An identifier- is a string of alphanumeric characters that begins with an alphabetic character or an


underscore character that are used to represent various programming elements such as variables,
functions, arrays, structures, unions and so on. Actually, an identifier is a user-defined word.

An expression - in a programming language is a combination of one or more explicit values,


constants, variables, operators, and functions that the programming language interprets (according
to its particular rules of precedence and of association) and computes to produce ("to return", in a
stateful environment) another value. This process, as for mathematical expressions, is called
evaluation.

I/O Instructions - A statement is a command given to the computer that instructs the computer to
take a specific action, such as display to the screen, or collect input. A computer program is made up
of a series of statements. All C programs are made up of a sequence of instructions. In C,
instructions are also called statements. In the English language, a statement is terminated by a
period, a question mark or an exclamation point. Note that in C language, a statement is terminated
by a semicolon. In the example program above, there is only one statement -- the printf() statement.

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 unsignedError! Bookmark not
defined.
register return short union continue
struct switch typedef const extern
volatile while char enum static
A typical C program is made of the following components:
Preprocessor directives
Functions

Michael Bwibo 0725327856 Page 38 of 142


Declaration statements
Comments
Expressions
Input and output statements.

TOPIC 4 : PROGRAM WRITING.

Writing a program in a structured Language


C is a high-level programming language and that you need a C compiler to translate your C
programs into binary code that your computer can understand and execute. In this lesson you'll
learn to write your first C program and the basics of a C program, such as
The #include directive
Header files
Comments
The main() function
The return statement
The exit() function
The newline character (\n)
The void data type
Translating a C program into an executable file
Debugging

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.

It was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell
Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978, Brian
Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as
the K&R standard. The UNIX operating system, the C compiler, and essentially all UNIX
applications programs have been written in C. The C has now become a widely used professional
language for various reasons.

Easy to learn
Structured language
It produces efficient programs.
It can handle low-level activities.
It can be compiled on a variety of computer platforms.

Facts about C
C was invented to write an operating system called UNIX.
C is a successor of B language, which was introduced around 1970.
The language was formalized in 1988 by the American National Standard Institute. (ANSI).
The UNIX OS was totally written in C by 1973.
Today, C is the most widely used and popular System Programming Language.

Michael Bwibo 0725327856 Page 39 of 142


Most of the state-of-the-art softwares have been implemented using C.
Today's most popular Linux OS and RBDMS MySQL have been written in C.

Why to use C?

C was initially used for system development work, in particular the programs that make up the
operating system. C was adopted as a system development language because it produces code that
runs nearly as fast as code written in assembly language. Some examples of the use of C might be:
Operating Systems Modern Programs
Databases Text Editors
Language Interpreters Language Compilers
Utilities

MERITS OF C LANGUAGE

C Supports structured programming design features.


It allows programmers to break down their programs into functions. Further it supports the use of
comments, making programs readable and easily maintainable.
Efficiency
C is a concise language that allows you to say what you mean in a few words.
The final code tends to be more compact and runs quickly.
Portability
C programs written for one system can be run with little or no modification on other systems.
Power and flexibility
C has been used to write operating systems such as Unix, Windows.
It has (and still is) been used to solve problems in areas such as physics and engineering.
Programmer orientation
C is oriented towards the programmer’s needs.
It gives access to the hardware. It lets you manipulate individual bits of memory.
It also has a rich selection of operators that allow you to expand programming capability.

Handling Errors.

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.

Run Time Error

This is an error that occurs during the execution of a program. In contrast, compile-time errors
occur while a program is being compiled. Runtime errors indicate bugs in the program or problems

Michael Bwibo 0725327856 Page 40 of 142


that the designers had anticipated but could do nothing about. For example, running out of memory
will often cause a runtime error.

Semantic Errors

They are caused by illegal expressions that the computer cannot make meaning of. Usually no results
will come out of them and the programmer will find it difficult to debug 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.

Syntax errors
These are errors in the code you write so that the compiler cannot understand your code and the
code will not compile. They include missing colon, semicolon and parenthesis.

Coding - Computer programming (often shortened to programming) is a process that leads from an
original formulation of a computing problem to executable computer programs. Programming
involves activities such as analysis, developing understanding, generating algorithms, verification of
requirements of algorithms including their correctness and resources consumption, and
implementation (commonly referred to as coding) of algorithms in a target programming language.
Source code is written in one or more programming languages. The purpose of programming is to
find a sequence of instructions that will automate performing a specific task or solving a given
problem. The process of programming thus often requires expertise in many different subjects,
including knowledge of the application domain, specialized algorithms, and formal logic.

Compiling - A compiler is a computer program (or a set of programs) that transforms source code
written in a programming language (the source language) into another computer language (the target
language), with the latter often having a binary form known as object code. The most common
reason for converting source code is to create an executable program. The name "compiler" is
primarily used for programs that translate source code from a high-level programming language to a
lower level language (e.g., assembly language or machine code). If the compiled program can run on
a computer whose CPU or operating system is different from the one on which the compiler runs,
the compiler is known as a cross-compiler. More generally, compilers are a specific type of
translator.

Debugging - Debugging is the routine process of locating and removing computer program bugs,
errors or abnormalities, which is methodically handled by software programmers via debugging
tools. Debugging checks, detects and corrects errors or bugs to allow proper program operation
according to set specifications. Developing software programs undergo heavy testing, updating,
troubleshooting and maintenance. Normally, software contains errors and bugs, which are routinely
removed. In the debugging process, complete software programs are regularly compiled and
executed to identify and rectify issues. Large software programs, which contain millions of source
code lines, are divided into small components.

Michael Bwibo 0725327856 Page 41 of 142


Testing - testing is finding out how well something works. In terms of human beings, testing tells
what level of knowledge or skill has been acquired. In computer hardware and software
development, testing is used at key checkpoints in the overall process to determine whether
objectives are being met. For example, in software development, product objectives are sometimes
tested by product user representatives. When the design is complete, coding follows and the finished
code is then tested at the unit or module level by each programmer; at the component level by the
group of programmers involved; and at the system level when all components are combined
together. At early or late stages, a product or service may also be tested for usability.

Execution and Program Development - Execution in computer and software engineering is the
process by which a computer or a virtual machine performs the instructions of a computer program.
The instructions in the program trigger sequences of simple actions on the executing machine.
Those actions produce effects according to the semantics of the instructions in the program.
Programs for a computer may execute in a batch process without human interaction, or a user may
type commands in an interactive session of an interpreter. In this case the "commands" are simply
programs, whose execution is chained together. Program development the coding of an individual
software program or to the creation on an entire information system and all related software

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
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.

Compilation can be divided into three stages including

Lexical Analysis which involves

Michael Bwibo 0725327856 Page 42 of 142


Checking for valid words like data names or operator symbols
Checking for reserved words (keywords). These are words that have a special meaning for the
compiler. These are then replaced with non-alphanumeric character codes known as tokens.

Syntax analysis which involves

Checking the program statements for correct grammatical form.


Breaking down the complex statements in the program into simpler equivalents and more
manageable forms.

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.

Code Generation involves


Translation of each statement into its equivalent machine code. This is done using tables.
Setting up linkages that allow the object program to communicate or work with various operating
systems and hardware.
Fetching of subroutines from the system library, to optimize the code and make it execute faster and
use less storage space.

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.

Example 1: A simple code that would print the words "Hello World":
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
system(“pause”);
return 0;
}

1. The first line of the program #include <stdio.h> is a preprocessor command, which tells a C
compiler to include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where program execution begins.

Michael Bwibo 0725327856 Page 43 of 142


3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.
Comments can be used for the various purpose like :

1. Planning and reviewing : In comments, we can write the pseudocode which we


planned before writing the source code. Pseudocode is a mixture of natural language
and high-level programming language. This helps in reviewing the source code more
easily because pseudocode is more understandable than the program.
2. Code description : Code description is used by the programmer to make others
understand his/her intent. It contains the summary of the code.
3. Algorithmic description : Comments are used for explanation of the methodology.
Such explanations may include diagrams and formal mathematical proofs. This may
constitute the explanation of the code, rather than a clarification of its intent.
4. Resource inclusion : Logos, diagrams, and flowcharts consisting of ASCII art
constructions can be inserted into source code formatted as a comment. Further,
copyright notices can be embedded within source code as comments.
5. Metadata : Comments also contain metadata of the program. This metadata helps in
software maintenance. The metadata includes the name of the creator of the original
version, current maintainer of the program, data when the first version was created,
the name of the people who have edited the program files so far etc.
6. Debugging : Brute force method is a common method of debugging. In this
approach, print statements are inserted throughout the program to print the
intermediate values with the hope that some of the printed values will help to
identify the errors.
7. Automatic documentation generation : Programming tools sometimes store
documentation and metadata in comments.
8. Stress relief : Commenting on development tools, competitors, employers, working
conditions, or the quality of the code itself are the ways to relieve stress.

4. The next line printf(...) is another function available in C which causes the message "Hello,
World!" to be displayed on the screen. \n creates a new line.
5.System (“pause”) causes the output window remain displayed until the user presses any key. You
can still use getch();
6. The next line return 0; terminates main()function and returns the value 0.

System ("pause") or getch() - Allows the program to stay open long enough for you to see/interact
with it. The program closes immediately upon executing it and thus some compilers need you to add
that statement before return 0 ;

Sample Program 2
This program will print out the message: This is a C program.
#include<stdio.h>
main()

Michael Bwibo 0725327856 Page 44 of 142


{
printf("This is a C program \n");
system (“pause”);
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.

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.
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.

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 “);

Michael Bwibo 0725327856 Page 45 of 142


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.

Note:
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.
While omitting the keyword int to imply the return type of the main( ) function does not disqualify
the fact that an integer is returned (since int is default), you should explicitly write it in other
functions, especially if another value other than zero is to be returned by the function.

Source Code files


When you write a program in C language, your instructions from the source code (or simply source
file). C filenames have an extension .c. The part of the name before the period is called the base
name and the part after the period is called the extension.

Object code, Executable code and Libraries


An executable file is a file containing ready to run machine code. C accomplishes this in two steps.
Compiling – The compiler converts the source code to produce the intermediate object code.
The linker combines the intermediate code with other code to produce the executable file. C does
this in a modular manner.
Every C file must be saved with a .c file extension.

Preprocessor directives and header files

A preprocessor directive performs various manipulations on your source file before it is actually
compiled. Preprocessor directives are not actually part of the C language, but rather instructions
from you to the compiler

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

Michael Bwibo 0725327856 Page 46 of 142


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.

Assignment and Expression statements

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.
For example, this program:

#include<stdio.h>
main()
{
printf(“This is line one \n”);
printf(“This is line two \n”);
printf(“This is line three”);
system(pause);
return 0;
}
displays the following output on the screen.

This is line one


This is line two
This is line three
Below are other escape sequences:
Escape sequence Meaning
\a alert/bell
\b backspace
\n new line
\v vertical tab
\t horizontal tab
\\ back slash
\’ Single quote (‘)
\” Double quote (“”)
\0 null

Michael Bwibo 0725327856 Page 47 of 142


Special character in C.
, Comma * Asterisk ' Apostrophe ( Left Parenthesis
& .Ampersand : Colon < Opening Angle(Less than sign) | Vertical Bar
.
. Period - .Minus Sign " Quotation Marks ) Right Parenthesis
; Semicolon ? Question > Closing Angle(Greater than / Slash
Mark sign)
^ Caret + .Plus Sign ! Exclamation Mark [ Left Bracket
\ Backslash ~ Tilde % Percentage Sign $ Dollar Sign

] Right { Left Brace } Right Bracket # Number Sign


Bracket
- Underscore

Variables in programming.

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];

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.

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.

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

Michael Bwibo 0725327856 Page 48 of 142


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

Using a Symbolic Constant


This involves the use of another C preprocessor, #define.

For example, #define SIZE 10


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.

Michael Bwibo 0725327856 Page 49 of 142


This process is generally referred to as macro substitution. The general form of the #define
statement is;

#define macro-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.

Michael Bwibo 0725327856 Page 50 of 142


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.

int high = 250; /* Maximum Temperature */


int low = -40; /* Minimum Temperature */
int results[20]; /* Series of temperature readings */

Scope of variables
Scope of variable refers to the visibility of a variable in a program. Meaning which parts of your
program can see or use it.
A scope is a region of the program and broadly speaking there are three places, where variables can
be declared −
Inside a function or a block which is called local variables,
In the definition of function parameters which is called formal parameters.
Outside of all functions which is called global variables.
1) Local Variables
Are variables declared inside a given procedure and can be accessed or used only in a procedure in
which they are declared. These types of variables are only meaningful inside the procedure. No
statements outside the procedure may reference local variables .A local variable is a variable that is
given local scope. Local variable references in the function or block in which it is declared override
the same variable name in the larger scope. In programming languages with only two levels of
visibility, local variables are contrasted with global variables.
2) Global Variables
Variables declared for the entire program. Global variables can be utilized anywhere within the
program block, whether inside of or external to the procedure. a global variable is a variable with
global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed.

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.

Rules for constant and variables


1) Variable or constant name shouldn’t be a keyword it should be a user defined
2) Every variable or constant name should start with either underscore or alphabet
3) A variable or constant name can be made up of either underscore or alphabet as well
as numerals and combination of both.
4) No special character are allowed within either constant or variable name except
underscore
5) In case a variable or a constant name is made up of more than one word, the words

Michael Bwibo 0725327856 Page 51 of 142


can either be fully joined or joined by use of underscore

Examples of legal variable names


x result outfile bestyet
x1 x2 out_file best_yet

Using printf() To Output Values

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);

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

Michael Bwibo 0725327856 Page 52 of 142


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;
num = 100;
printf(“ The value is %d “, num);
system(“pause”);
return 0;
}
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);
system(“pause”);
return 0;
}

Inputting Numbers From The Keyboard Using scanf( )

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);

Michael Bwibo 0725327856 Page 53 of 142


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);
system(“pause”);
return 0;
}

2. This program computes the area of a rectangle, given its dimensions. It first prompts the user for
the length and width of the rectangle and then displays the area.

Michael Bwibo 0725327856 Page 54 of 142


#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);
system(“pause”);
return 0;
}

Exercises

Enter, compile and run the example programs.


Write a program that inputs two floating-point numbers (use type float) and then displays their sum.
Write a program that computes the volume of a cube. Have the program prompt the user for each
dimension.

Example: Area of a circle

#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);
system(“pause”);
return 0;
}

Revision Exercises

Discuss four fundamental data types supported by C, stating how each type is stored in memory.
Distinguish between a variable and a constant.
Suggest, with examples two ways in which constant values can be used in C expression statements.
Give the meaning of the following declarations;
(i) char name[20];
(ii) int num_emp;
(iii) double tax, basicpay;
(iv) char response;

Michael Bwibo 0725327856 Page 55 of 142


What is the difference between a local and a global variable?
Write a program that will prompt you to enter the radius a cylinder. The code then calculates the
volume of the cylinder.

C PROGRAM EXAMPLES.
A C code that calculates the average of 3 integers.
#include<stdio.h>
main()
{
int x,y,z;
float average,sum=0.0;

printf("Enter x ");
scanf("%d", &x);
printf("Enter y ");
scanf("%d", &y);
printf("Enter z ");
scanf("%d", &z);
sum=x+y+z;
average = sum/3;
printf("\n The average is %f \n", average);
system("pause");
return 0;
}

C Program to Find Volume and Surface Area of Sphere

#include <stdio.h>
#include <math.h>
int main()
{
float radius;
float surface_area, volume;
printf("Enter radius of the sphere : \n");
scanf("%f", &radius);
surface_area = 4 * (22/7) * radius * radius;
volume = (4.0/3) * (22/7) * radius * radius * radius;
printf("Surface area of sphere is: %.3f", surface_area);
printf("\n Volume of sphere is : %.3f", volume);
system("pause");
return 0;

Michael Bwibo 0725327856 Page 56 of 142


TOPIC 5 : CONTROL STRUCTURES

Control structures represent the forms by which statements in a program are executed. A control
structure is a block of programming that analyzes variables and chooses a direction in which to go
based on given parameters.

Importance of Control Structures

The term flow control details the direction the program takes (which way program control "flows").
Hence it is the basic decision-making process in computing; flow control determines how a
computer will respond when given certain conditions and parameters.

Types of Control Structures

Three structures control program execution:


Sequence
Selection or decision structure
Iteration or looping structure

1) Sequence Control Structure

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 sequence control structure is the default or overriding structure.

The sequence structure indicates instructions are to be executed one statement at a time in the order
they occur from top down unless a different control structure dictates otherwise.

2) Selection Control Structure

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.

Types of Selection Structure

The if statement
The if statement provides a junction at which the program has to select which path to follow.

Michael Bwibo 0725327856 Page 57 of 142


Syntax
The syntax of an if statement in C programming language is:

if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}

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”);
Flow diagram.

Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
system(“pause”);
return 0;
}

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.

Michael Bwibo 0725327856 Page 58 of 142


Syntax
The syntax of an if...else statement in C programming language is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}

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.

Flow diagram

Example
#include <stdio.h>
main()
{
int i;
printf("Enter a value \n");
scanf("%d",&i);
if (i%2 == 0)
printf("%d - is Even \n", i);
else
printf("%d - is Odd \n", i);
system("pause");
return 0;
}

Multiple Choice: else if (Nested IF)

This is a control structure that is used when more than two choices have to be made. It involves
having IF structure inside another IF structure either in the true or false part.

The general form is:

Michael Bwibo 0725327856 Page 59 of 142


if (expression 1)
statement 1;
else if (expression 2)
statement 2;
else if (expression 3)
statement 3;
-------------
else
statement n;

(Braces still apply for block statements) In this structure expression 2 is only tested if condition one
is false. Explain how execution of the statements occurs.

Example 1:
/* Program to find roots of a quadratic equation when coefficients are entered by user. */
/* Library function sqrt() computes the square root. */

#include <stdio.h>
#include <math.h> /* This is needed to use sqrt() function.*/
int main()
{
float a, b, c, determinant, r1,r2, real, imag;
printf("Enter coefficients a, b and c:\n");
scanf("%f%f%f",&a,&b,&c);
determinant=b*b-4*a*c;
if (determinant>0)
{
r1= (-b+sqrt(determinant))/(2*a);
r2= (-b-sqrt(determinant))/(2*a);
printf("Roots are: %.2f and %.2f",r1 , r2);
}
else if (determinant==0)
{
r1 = r2 = -b/(2*a);
printf("Roots are: %.2f and %.2f", r1, r2);
}
else
{
real= -b/(2*a);
imag = sqrt(-determinant)/(2*a);
/* printf("Roots are: %.2f+%.2fi and %.2f-%.2fi", real, imag, real, imag);*/
printf("Roots are: %.2f and %.2f \n", real, imag, real, imag);
}
system("pause");
return 0;
}
Example 2:
#include<stdio.h >

Michael Bwibo 0725327856 Page 60 of 142


int main()
{
int marks;
printf (" Enter the students marks \n");
scanf( "%d",&marks );
if ( marks >=75 && marks <=100)
{
printf("The grade is A");
}
else if( marks >= 60 && marks < 75 )
{
printf("The grade is B");
}
else if(marks>=50 && marks<60)
{
printf("The grade is C");
}
else if(marks>=40 && marks<50)
{
printf("The grade is D");
}
else if (marks>=0 && marks<40)
{
printf ("The grade is E");
}
else
{
printf("The mark is impossible!" );
}
system ("pause");
return 0;
}
The ‘switch’ and ‘break’ statements

The switch - break statements can be used in place of the if - else statements when there are several
choices to be made. The switch structure is used to test if a variable equals some constant values
then executes the equivalent statement.

The structure of a switch is as follows:

switch (integer expression)


{
case constant 1:
statement; optional
case constant 2:
statement; optional
…………

Michael Bwibo 0725327856 Page 61 of 142


default: (optional)
statement; (optional)
}

Example: Demonstrating the ‘switch’ structure


/* Source code to create a simple calculator for addition, subtraction, multiplication and division
using switch...case statement in C programming. */

# include <stdio.h>
int main()
{
char o;
float num1,num2;
printf("Enter operator either + or - or * or divide : ");
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o) {
case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);

Michael Bwibo 0725327856 Page 62 of 142


break;
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
system("pause");
return 0;
}

Example: Demonstrating the ‘switch’ structure

/* 10L05.c Adding the break statement */


#include <stdio.h>
main()
{
int day;

printf("Please enter a single digit for a day\n");


printf("(within the range of 1 to 7):\n");
day = getchar();
switch (day)
{
case '1':
printf("Day 1 is Sunday.\n");
break;
case '2':
printf("Day 2 is Monday.\n");
break;
case '3':
printf("Day 3 is Tuesday.\n");
break;
case '4':
printf("Day 4 is Wednesday.\n");
break;
case '5':
printf("Day 5 is Thursday.\n");
break;

Michael Bwibo 0725327856 Page 63 of 142


case '6':
printf("Day 6 is Friday.\n");
break;
case '7':
printf("Day 7 is Saturday.\n");
break;
default:
printf("The digit is not within the range of 1 to 7.\n");
break;
}
system("pause");
return 0;
}

You can specify a range of consecutive values in a single case label, like this:
case low ... high:
It can be used for ranges of ASCII character codes like this:
case 'A' ... 'Z':
You need to Write spaces around the ellipses … . For example, write this:
// Correct - case 1 ... 5:
// Wrong - case 1...5:

Looping/Repetition Control Structure

In many programming problems a sequence of statements or in some cases the entire program may
need to be executed repeatedly a definite or indefinite number of times. The repetition or iteration
control structure is used to control this. In a finite loop the number of iterations is determined and
set by the programmer. In an infinite loop the number of repetitions is dictated by a user or other
factors.

C supports three loop versions:


while loop
do while loop
for loop.

The ‘while’ loop

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.

Michael Bwibo 0725327856 Page 64 of 142


Syntax
The syntax of a while loop in C programming language is:
while(condition)
{
statement(s);
}

Example: Calculating the average of n numbers using a ‘while’ loop

Algorithm:
Initialise an integer count variable to 1. It will be used as a loop counter.
Assign a value of 0 to the floating-point sum.
Read in the variable for n (number of values)
Carry out the following repeatedly (as long as the count is less or equal to n).
Read in a number, say x.
Add the value of x to current value of sum.
Increase the value of count by 1.
Calculate the average: Divide the value of sum by n.
Write out the calculated value of average.

Solution

/* To add numbers and compute the average */


#include<stdio.h>
main()
{
int n, count = 1;
float x, average, sum=0.0;
/* initialise and read in a value of n */
printf(“How many numbers? “);
scanf(“%d”, &n);

/*Read in the number */


while (count<=n)
{

Michael Bwibo 0725327856 Page 65 of 142


printf(“x = “);
scanf(“%f”, &x);
sum+=x;
count++;
}
/* Calculate the average and display the answer */
average = sum/n;
printf(“\n The average is %f \n”, average);
system(“pause”);
return 0;
}

Example 2:
/* counter.c */
/* Displays the digits 1 through 9 */
main()
{
int digit=0, sum=0; /* Initialisation */
while (digit<=9)
{
if (digit %2==0)
{
printf("%d \n", digit);
sum+=digit;
}
digit++;

}
printf("Th sum is %d \n", sum);
system("pause");
return 0;
}

The ‘do .. while’ loop (Post-Test)

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.

Syntax
The syntax of a do...while loop in C programming language is:
do
{
statement(s);
}while( condition );

Michael Bwibo 0725327856 Page 66 of 142


Example 1:
/* Displays the digits 1 through 9 */
main()
{
int digit=0; /* Initialisation */
do
{
printf(“%d \n”, digit);
digit++;
} while (digit<=9);
system(“pause”);
return 0;
}

Example 2:
#include <stdio.h>
main()
{
int value =0;

do
{ if (value %2 != 0)
{
printf("Value is %d\n", value);
}
value++;
}while(value<=30);
system("pause");
return 0;
}

The ‘for’ loop

This is the most commonly used looping statement in C.

Michael Bwibo 0725327856 Page 67 of 142


Syntax
The syntax of a for loop in C programming language is:
for ( init; condition; increment )
{
statement(s);
}

expression1 is used to initialize some parameter (called an index). The index controls the loop
action. It is usually an assignment operator.

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: Counting 0 to 9 using a ‘for’ loop

/* Displays the digits 1 through 9 */


#include<stdio.h>
main()
{
int digit;
for(digit=0;digit<=9; digit++)
printf(“%d \n” , digit);
return 0;
}

Example: Averaging a set of numbers using a ‘for’ loop


/* average.c */
/* To add numbers and compute the average */
#include<stdio.h>
main()

Michael Bwibo 0725327856 Page 68 of 142


{
int n, count;
float x, average, sum=0.0;.

/* initialise and read in a value of n */


printf(“How many numbers? “);
scanf(“%d”, &n);
/*Read in the number */
for(count=1;count<=n;count++)
{
printf(“x = “);
scanf(“%f”, &x);
sum+=x;
}
/* Calculate the average and display the answer */
average = sum/n;
printf(“\n The average is %f \n”, average);
return 0;
}

Nested ‘for’ statement


Suppose we want to calculate the average of several consecutive lists of numbers, if we know in
advance how many lists are to be averaged.
Example: Nested ‘for’ statements

/* Calculate the averages of several different lists of number */


#include<stdio.h>
main()
{
int n, count, loops, loopcount;
float x, average, sum;
/*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 */

Michael Bwibo 0725327856 Page 69 of 142


/* Calculate the average and display the answer */
average = sum/n;
printf(“\n The average is %f \n”, average);
} /*End of outer loop */
system(“pause”);
return 0;
}

Example: The following program uses a nested for loop to find the prime numbers from 2 to 100:

#include <stdio.h>
int main ()
{
/* local variable definition */
int i, j;
for(i=2; i<100; i++) {
for(j=2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}
system(“pause”);
return 0; }

CONTROL STATEMENTS:

Loop Control Statements:

Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Pascal supports the following control statements.

Control Statements Description


break statement -Terminates the loop or case
statement and transfers execution to
the statement immediately following
the loop or case statement.
continue statement -Causes the loop to skip the
remainder of its body and immediately
retest its condition prior to reiterating.
goto statement -Transfers control to the labeled
statement. Though it is not advised to
use goto statement in your program.

1) Break statement

The break statement in Pascal has the following two usages:

Michael Bwibo 0725327856 Page 70 of 142


1. When the break statement is encountered inside a loop, the loop is immediately terminated and
program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the case statement.

If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the
execution of the innermost loop and start executing the next line of code after the block.

Syntax: break;

Flow Diagram.

Example 1 Break.

/* 10L06.c: Breaking an infinite loop */

Michael Bwibo 0725327856 Page 71 of 142


#include <stdio.h>
main()
{
int c;

printf("Enter a character:\n(enter x to exit)\n");


while (1) {
c = getc(stdin);
if (c=='x')
break;
}
printf("Break the infinite while loop. Bye!\n");
system("pause");
return 0;
}

2) Continue statement.

The continue statement in C works somewhat like the break statement. Instead of forcing
termination, however, continue forces the next iteration of the loop to take place, skipping any code
in between. For the for-do loop, continue statement causes the conditional test and increment
portions of the loop to execute. For the while-do and repeat...until loops, continue statement causes
the program control to pass to the conditional tests.

Syntax:continue;

Flow Diagram.

Michael Bwibo 0725327856 Page 72 of 142


Example 1 Continue.
/* 10L07.c: Using the continue statement */
#include <stdio.h>

main()
{
int i, sum;

sum = 0;
for (i=1; i<8; i++){
if ((i==3) || (i==5))
continue;
sum += i;
}
printf("The sum of 1, 2, 4, 6, and 7 is: %d\n", sum);
system("pause");
return 0;
}

3) Goto statement.
A goto statement in C provides an unconditional jump from the goto to a labeled statement in the
same function.
NOTE: Use of goto statement is highly discouraged in any programming language because it makes
difficult to trace the control flow of a program, making the program hard to understand and hard to
modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.

Syntax
goto label;
...

Michael Bwibo 0725327856 Page 73 of 142


...
label: statement;

In C programming, goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program.

Syntax:
goto label;
.............
.............
.............
label:
statement;
In this syntax, label is an identifier.
When, the control of program reaches to goto statement, the control of the program will jump to
the label: and executes the code below it.

Flow Diagram.

Michael Bwibo 0725327856 Page 74 of 142


Example 1 GoTo Statement.

#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
Note:
Though goto statement is included in ANSI standard of C, use of goto statement should be reduced
as much as possible in a program.

Reasons to avoid goto statement

• Though, using goto statement give power to jump to any part of program, using goto
statement makes the logic of the program complex and tangled.
• In modern programming, goto statement is considered a harmful construct and a bad
programming practice.
• The goto statement can be replaced in most of C program with the use of break and
continue statements.
• In fact, any program in C programming can be perfectly written without the use of goto
statement.
• All programmer should try to avoid goto statement as possible as they can.

When we use break, continue and goto statements, we must follow the following...

• The break is a keyword so it must be used only in lower case letters.


• The break statement can not be used with if statement.
• The break statement can be used only in switch case and looping statements.
• The break statement can be used with if statement, only if that if statement is
written inside the switch case or looping statements.

Michael Bwibo 0725327856 Page 75 of 142


• The continue is a keyword so it must be used only in lower case letters.
• The continue statement is used only within looping statements.
• The continue statement can be used with if statement, only if that if
statement is written inside the looping statements.
• The goto is a keyword so it must be used only in lower case letters.
• The goto statement must require a label.
• The goto statement can be used with any statement like if, switch, while, do-
while, and for, etc.

Pattern programs in C
Pattern programs in C language, showing how to create various patterns of numbers
and stars. The programs require nested loops (a loop inside another loop). A design of
numerals, stars, or characters is a way of arranging these in some logical manner, or
they may form a sequence. Some of these are triangles that have particular importance
in mathematics. Some patterns are symmetrical, while others are not. See the complete
page for all of them.

Example 1: Half Pyramid of *


*
**
***
****
*****
C Program

#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;

Michael Bwibo 0725327856 Page 76 of 142


}

Example 2: Half Pyramid of Numbers


1
12
123
1234
12345
C Program

#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}

Example 3: Half Pyramid of Alphabets


A
BB
CCC
DDDD
EEEEE
C Program

#include <stdio.h>
int main() {
int i, j;
char input, alphabet = 'A';
printf("Enter an uppercase character you want to print in the last row: ");
scanf("%c", &input);
for (i = 1; i <= (input - 'A' + 1); ++i) {
for (j = 1; j <= i; ++j) {

Michael Bwibo 0725327856 Page 77 of 142


printf("%c ", alphabet);
}
++alphabet;
printf("\n");
}
return 0;
}

Example 4: Inverted half pyramid of *


*****
****
***
**
*
C Program

#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}

Example 5: Inverted half pyramid of numbers


12345
1234
123
12
1
C Program

#include <stdio.h>

Michael Bwibo 0725327856 Page 78 of 142


int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}

Example 6: Floyd's Triangle.


1
23
456
7 8 9 10
C Program

#include <stdio.h>
int main() {
int rows, i, j, number = 1;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; ++j) {
printf("%d ", number);
++number;
}
printf("\n");
}
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.

Michael Bwibo 0725327856 Page 79 of 142


Ksh. 3, 000 <= Purchase Amount < Ksh. 5,000 - Give 3% discount on the amount.
0 > Purchase Amount < Ksh. 3,000 - Pay full amount.

Write a program that asks for the customer’s purchase amount, then uses if statements to
recommend the appropriate payable amount. The program should cater for negative purchase
amounts and display the payable amount in each case.
In what circumstance is the continue statement used in a C program?
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.
Write a while loop that will calculate the sum of every fourth integer, beginning with the integer 3
(that is calculate the sum 3 + 7 +11 + 15 + ...) for all integers that are less than 30.

Michael Bwibo 0725327856 Page 80 of 142


TOPIC 6: DATA STRUCTURES

Data structure

A data structure is a particular way of organizing data in a computer so that it can be used efficiently.
Different kinds of data structures are suited to different kinds of applications, and some are highly
specialized to specific tasks. Data structures can implement one or more particular abstract data
types (ADT), which specify the operations that can be performed on a data structure and the
computational complexity of those operations. In comparison, a data structure is a concrete
implementation of the specification provided by an ADT.
Different kinds of data structures are suited to different kinds of applications, and some are highly
specialized to specific tasks. For example, relational databases commonly use B-tree indexes for data
retrieval, while compiler implementations usually use hash tables to look up identifiers

Data structure is a way to organize a data in computer so that it can be used efficiently.
In computer science, Data Structure is classified into two categories :
Linear Data Structure
Non Linear Data Structure

Classifications of Data Structure


Linear Data Structures: The data structure where data items are organized sequentially or linearly
where data elements attached one after another is called linear data structure. Data elements in a
liner data structure are traversed one after the other and only one element can be directly reached
while traversing. All the data items in linear data structure can be traversed in single run.
These kind of data structures are very easy to implement because memory of computer is also
organized in linear fashion.
Examples of linear data structures are Arrays, Stack, Queue and Linked List.
An arrays is a collection of data items having the same data types. A Stack is a LIFO (Last In First
Out) data structure where element that added last will be deleted first. All operations on stack are
performed from on end called TOP. A Queue is a FIFO (First In First Out) data structure where
element that added first will be deleted first. In queue, insertion is performed from one end called
REAR and deletion is performed from another end called FRONT. A Linked list is a collection of

Michael Bwibo 0725327856 Page 81 of 142


nodes, where each node is made up of a data element and a reference to the next node in the
sequence.

Non Linear Data Structures: The data structure where data items are not organized sequentially is
called non linear data structure. In other words, A data elements of the non linear data structure
could be connected to more than one elements to reflect a special relationship among them. All the
data elements in non linear data structure can not be traversed in single run.

Examples of non linear data structures are Trees and Graphs, Decision Trees
A tree is collection of nodes where these nodes are arranged hierarchically and form a parent child
relationships. A Graph is a collection of a finite number of vertices and an edges that connect these
vertices. Edges represent relationships among vertices that stores data elements.

Difference Between Linear and Non Linear Data Structure


Linear Data Structure Non-Linear Data Structure

Every item is related to its previous and next Every item is attached with many other
item. items.

Data is arranged in linear sequence. Data is not arranged in sequence.

Data items can be traversed in a single run. Data can not be traversed in a single run.

Examples: Array, Stack, Queue, Linked List. Examples: Tree, Graph.

Implementation is Easy. Implementation is Difficult.

Homogeneous data: Homogeneous data structures are those data structures that contain only similar
type of data e.g. like a data structure containing only integer or float values. The simplest example of
such type of data structures is an Array.
Heterogeneous Data: Heterogeneous Data Structures are those data structures that contains a variety
or dissimilar type of data, for e.g. a data structure that can contain various data of different data
types like integer, float and character. The examples of such data structures include structures,
union.

Types of Data structures

1)BINARY TREE
A tree is a non-linear data structure that consists of a root node and potentially many levels of
additional nodes that form a hierarchy. A tree can be empty with no nodes called the null or empty
tree or a tree is a structure consisting of one node called the root and one or more subtrees.
A binary tree is a tree data structure in which each node has at most two children (referred to as the
left child and the right child). In a binary tree, the degree of each node can be at most two.

Michael Bwibo 0725327856 Page 82 of 142


Tree Traversals (Inorder, Preorder and Postorder)
Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical
way to traverse them, trees can be traversed in different ways. Following are the generally used ways
for traversing trees.

Depth First Traversals:


(a) Inorder (Left, Root, Right) : 4 2 5 1 3
(b) Preorder (Root, Left, Right) : 1 2 4 5 3
(c) Postorder (Left, Right, Root) : 4 5 2 3 1
Breadth First or Level Order Traversal : 1 2 3 4 5
Inorder Traversal: In - Order Traversal ( leftChild - root - rightChild )

Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
Uses of Inorder
In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get
nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder itraversal s
reversed, can be used.
Example: Inorder traversal for the above given figure is 4 2 5 1 3.
Preorder Traversal: Pre - Order Traversal ( root - leftChild - rightChild )
Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)

Michael Bwibo 0725327856 Page 83 of 142


Uses of Preorder
Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get prefix
expression on of an expression tree.
Example: Preorder traversal for the above given figure is 1 2 4 5 3.
Postorder Traversal: Post - Order Traversal ( leftChild - rightChild - root )
Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.
Uses of Postorder
Postorder traversal is used to delete the tree. Postorder traversal is also useful to get the postfix
expression of an expression tree.
Example: Postorder traversal for the above given figure is 4 5 2 3 1.

Besides the parent-child relationship, we can think of tree nodes having ancestors and
descendants. An ancestor of a node is any other node on the path from the node to the root. •
A descendant is the inverse relationship of ancestor: A node p is a descendant of a node q if and
only if q is an ancestor of p.

Forest is a collection of disjoint trees. In other words, we can also say that forest is a collection of an
acyclic graph which is not connected. Here is a pictorial representation of a forest.

A set (usually ordered) of 0 or more disjoint trees, or equivalently: the nodes of a tree excluding the
root.

The number of sub trees of a node is called the degree of the node. In a binary tree, all nodes
have degree 0, 1, or 2. A node of degree zero is called a terminal node or leaf node. A non-leaf
node is often called a branch node.

A level is the number of parent nodes corresponding to a given a node of the tree. It is basically
the number of ancestors from that node until the root node. So, for the root node (topmost
node), it's level is 0, since it has no parents.

Michael Bwibo 0725327856 Page 84 of 142


The height of a binary tree is the height of the root node in the whole binary tree. In other
words, the height of a binary tree is equal to the largest number of the edges from the root to
the most distant leaf node.

2) RECORD
A record is a data structure that contains other values, typically in fixed number and sequence and
typically indexed by names. The elements of records are usually called fields or members.Records are
2 or more variables of different types in one.
program Types;
Type StudentRecord = Record Number: Integer;
Name: String;
end;
var Student: StudentRecord;
begin
Student.Number := 12345;
Student.Name := 'John Smith';
end.

3) LINKED LIST
A linked list is a linear data structure where each element is a separate object. Each element (we will
call it a node) of a list is comprising of two items - the data and a reference to the next node. The
last node has a reference to null. The entry point into a linked list is called the head of the list.

Michael Bwibo 0725327856 Page 85 of 142


A linked list is a sequence of data structures, which are connected together via links.
Linked List is a sequence of links which contains items. Each link contains a connection to another
link. Linked list is the second most-used data structure after array. Following are the important terms
to understand the concept of Linked List.
Link − Each link of a linked list can store a data called an element.
Next − Each link of a linked list contains a link to the next link called Next.
LinkedList − A Linked List contains the connection link to the first link called First.
Linked List Representation
Linked list can be visualized as a chain of nodes, where every node points to the next node.

As per the above illustration, following are the important points to be considered.
Linked List contains a link element called first.
Each link carries a data field(s) and a link field called next.
Each link is linked with its next link using its next link.
Last link carries a link as null to mark the end of the list.
Types of Linked List
Following are the various types of linked list.
Simple Linked List − Item navigation is forward only.
Doubly Linked List − Items can be navigated forward and backward.
Circular Linked List − Last item contains link of the first element as next and the first element has a
link to the last element as previous.
Basic Operations
Following are the basic operations supported by a list.
Insertion − Adds an element at the beginning of the list.
Deletion − Deletes an element at the beginning of the list.
Display − Displays the complete list.
Search − Searches an element using the given key.
Delete − Deletes an element using the given key.
Advantages
Linked lists are a dynamic data structure, which can grow and be pruned, allocating and deallocating
memory while the program is running.
Insertion and deletion node operations are easily implemented in a linked list.

Michael Bwibo 0725327856 Page 86 of 142


Dynamic data structures such as stacks and queues can be implemented using a linked list.
There is no need to define an initial size for a linked list.
Items can be added or removed from the middle of list.
Backtracking is possible in two way linked list.
Disadvantages
They use more memory than arrays because of the storage used by their pointers.
Nodes in a linked list must be read in order from the beginning as linked lists are inherently
sequential access.
Nodes are stored incontiguously, greatly increasing the time required to access individual elements
within the list, especially with a CPU cache.
Difficulties arise in linked lists when it comes to reverse traversing. For instance, singly linked lists
are cumbersome to navigate backwards and while doubly linked lists are somewhat easier to read,
memory is consumed in allocating space for a back-pointer.
There are three common types of Linked List.
Singly Linked List
Doubly Linked List
Circular Linked List
Singly Linked List
It is the most common. Each node has data and a pointer to the next node.

Doubly Linked List


We add a pointer to the previous node in a doubly linked list. Thus, we can go in either direction:
forward or backward.

Circular Linked List


A circular linked list is a variation of linked list in which the last element is linked to the first
element. This forms a circular loop.

A circular linked list can be either singly linked or doubly linked.

Michael Bwibo 0725327856 Page 87 of 142


for singly linked list, next pointer of last item points to the first item
In doubly linked list, prev pointer of first item points to last item as well.

4) QUEUE
Queue Data Structures
Queue is also an abstract data type or a linear data structure, in which the first element is inserted
from one end called REAR(also called tail), and the deletion of exisiting element takes place from
the other end called as FRONT(also called head). This makes queue as FIFO data structure, which
means that element inserted first will also be removed first.
The process to add an element into queue is called Enqueue and the process of removal of an
element from queue is called Dequeue.

Michael Bwibo 0725327856 Page 88 of 142


Basic features of Queue
Like Stack, Queue is also an ordered list of elements of similar data types.
Queue is a FIFO( First in First Out ) structure.
Once a new element is inserted into the Queue, all the elements inserted before the new element in
the queue must be removed, to remove the new element.
peek( ) function is oftenly used to return the value of first element without dequeuing it.

Applications of Queue
Queue, as the name suggests is used whenever we need to have any group of objects in an order in
which the first one coming in, also gets out first while the others wait for there turn, like in the
following scenarios :
Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
In real life, Call Center phone systems will use Queues, to hold people calling them in an order, until
a service representative is free.
Handling of interrupts in real-time systems. The interrupts are handled in the same order as they
arrive, First come first served.
Applications of Queue Data Structure
Queue is used when things don’t have to be processed immediatly, but have to be processed in First
In First Out order like Breadth First Search. This property of Queue makes it also useful in
following kind of scenarios.
1) When a resource is shared among multiple consumers. Examples include CPU scheduling, Disk
Scheduling.
2) When data is transferred asynchronously (data not necessarily received at same rate as sent)
between two processes. Examples include IO Buffers, pipes, file IO, etc.

A queue is a particular kind of abstract data type or collection in which the entities in the collection
are kept in order and the principal operations on the collection are the addition of entities to the rear
terminal position, known as enqueue, and removal of entities .

Michael Bwibo 0725327856 Page 89 of 142


5) STACK.
A stack is a container of objects that are inserted and removed according to the last-in first-out
(LIFO) principle. In the push-down stacks only two operations are allowed: push the item into the
stack, and pop the item out of the stack.
A stack is a limited access data structure - elements can be added and removed from the stack only
at the top.
push adds an item to the top of the stack, pop removes the item from the top.
A stack is a recursive data structure. Here is a structural definition of a Stack:
a stack is either empty or
it consists of a top and the rest which is a stack
2. Application :-
To reverse a word. You push a given word to stack - letter by letter - and then pop letters from the
stack.
Backtracking. This is a process when you need to access the most recent data element in a series of
elements.
An "undo" mechanism in text editors; this operation is accomplished by keeping all text changes in a
stack.
Undo/Redo stacks in Excel or Word.
Language processing :
space for parameters and local variables is created internally using a stack.
compiler's syntax check for matching braces is implemented by using stack.
A stack of plates/books in a cupboard.
A garage that is only one car wide. To remove the first car in we have to take out all the other cars in
after it.
Wearing/Removing Bangles.
Back/Forward stacks on browsers.
Support for recursion
Activation records of method calls.

A stack is a particular kind of abstract data type or collection in which the principal operations on
the collection are the addition of an entity to the collection, known as push and removal of an entity,
known as pop. The relation between the push and pop operations is such that the stack is a Last-In-
First-Out (LIFO) data structure. In a LIFO data structure, the last element added to the structure
must be the first one to be removed.

Michael Bwibo 0725327856 Page 90 of 142


The two operations that form the majority of the functionality of the stack are the operation of
adding to the stack, and the operation of removing items from the stack.

For historical reasons the operation of adding items to a stack is called push. For similar reasons the
operation of removing an item from a stack is usually referred to as pop.

There are a couple more operations that we must consider before we attempt to implement a stack.
The first of these is an operation called init. This initialises the stack, and ensures that state of the
software is in a known condition before we try to use it. Just about every structure that we will ever
use will require an initialisation routine - get into the habit of writing the outline of the init operation
first!

As this is a course in developing software, we must also consider the possibility of errors. The easiest
error to envisage for a stack is when a program tries to remove an item from an empty stack. This
condition is called overflow, and if undetected will probably cause a series of mysterious errors
before the program crashes. The method that we use to detect this problem is to use an operation
called isEmpty to tell us if the stack is empty. If we try and take data from an empty stack the error
condition is usually called underflow. Similarly there is a possibility that we might run out of space. To
counter this we can provide an operation called isFull.

Using this analysis we can conclude that we need to provide five operations to implement a stack.
These operations are:

1. init
2. isEmpty
3. isFull
4. push
5. pop

If we can satisfactorily implement these operations we have implemented a stack. Note that we do
not have to say at this stage exactly how these operations are implemented, or exactly how the data
is held. There is more than one way of implementing a stack. In this Unit we are going to consider
how to implement a stack using an array.

Stack Underflow & Overflow


Now that we have a basic picture in mind of what a stack conceptually looks like, we can define
what underflow and overflow are. Stack underflow happens when we try to pop (remove) an item
from the stack, when nothing is actually there to remove. This will raise an alarm of sorts in the
computer because we told it to do something that cannot be done.

Michael Bwibo 0725327856 Page 91 of 142


Stack overflow happens when we try to push one more item onto our stack than it can actually
hold. You see, the stack usually can hold only so much stuff. Typically, we allocate (set aside) where
the stack is going to be in memory and how big it can get. So, when we stick too much stuff there or
try to remove nothing, we will generate a stack overflow condition or stack underflow condition,
respectively.

Consider the operation shown below:


(2 + 3) × 11 + 1
To evaluate this using a reverse polish or postfix notation, you rewrite the operation as shown below
then execute as shown on the table that follows below:
2, 3, add, 11, multiply, 1, add
Input 2 3 add 11 Mul 1 add

Stack 3 11 1
2 2 5 5 55 55 56

6) FILE.
A file is a large organised data structure that contains related data such as recorwds . A file
information data structure (INFDS) can be defined for each file to make file exception/error and
file feedback information available to the program. The file information data structure, which must
be unique for each file, must be defined in the main source section. The same INFDS is used by all
procedures using the files.

7)GRAPH.
A graph is a pictorial representation of a set of objects where some pairs of objects are connected by
links. The interconnected objects are represented by points termed as vertices, and the links that
connect the vertices are called edges.

Michael Bwibo 0725327856 Page 92 of 142


Formally, a graph is a pair of sets (V, E), where V is the set of vertices and Eis the set of edges,
connecting the pairs of vertices. Take a look at the following graph −

In the above graph,


V = {a, b, c, d, e}
E = {ab, ac, bd, cd, de}
Graph Data Structure
Mathematical graphs can be represented in data structure. We can represent a graph using an array
of vertices and a two-dimensional array of edges. Before we proceed further, let's familiarize
ourselves with some important terms −
Vertex − Each node of the graph is represented as a vertex. In the following example, the labeled
circle represents vertices. Thus, A to G are vertices. We can represent them using an array as shown
in the following image. Here A can be identified by index 0. B can be identified using index 1 and so
on.
Edge − Edge represents a path between two vertices or a line between two vertices. In the following
example, the lines from A to B, B to C, and so on represents edges. We can use a two-dimensional
array to represent an array as shown in the following image. Here AB can be represented as 1 at row
0, column 1, BC as 1 at row 1, column 2 and so on, keeping other combinations as 0.
Adjacency − Two node or vertices are adjacent if they are connected to each other through an edge.
In the following example, B is adjacent to A, C is adjacent to B, and so on.
Path − Path represents a sequence of edges between the two vertices. In the following example,
ABCD represents a path from A to D.

Michael Bwibo 0725327856 Page 93 of 142


Basic Operations
Following are basic primary operations of a Graph −
Add Vertex − Adds a vertex to the graph.
Add Edge − Adds an edge between the two vertices of the graph.
Display Vertex − Displays a vertex of the graph.

A graph is an abstract data type that is meant to implement the graph and hypergraph concepts from
mathematics. A graph data structure consists of a finite set of ordered pairs, called edges or arcs, of
certain entities called nodes or vertices.

Michael Bwibo 0725327856 Page 94 of 142


8) DECISION TABLE.
A decision table (DT) - also termed an inference or logical tree - provides a schematic view of the
inference process of a decision-making process. Each decision rule of a DT is composed of a
premise (condition) and a conclusion (action). In its tree-like representation, the premises and
conclusions are shown as nodes, and the branches of the tree connect the premises and the
conclusions. The logical operators “AND” and “OR” are used to reflect the structure of the if-then
rules.

9)SET.
A set is an abstract data structure that can store certain values, without any particular order, and no
repeated values. It is a computer implementation of the mathematical concept of a finite set. ...
Intersection,Conjunction,AND.
Union,Disjoint,OR,v,

10. STRING
A string is traditionally a sequence of characters, either as a literal constant or as some kind of
variable. The latter may allow its elements to be mutated and the length changed, or it may be fixed
(after creation). A string is generally understood as a data type and is often implemented as an array
of bytes (or words) that stores a sequence of elements, typically characters, using some character

Michael Bwibo 0725327856 Page 95 of 142


encoding. A string may also denote more general arrays or other sequence (or list) data types and
structures.
Depending on programming language and precise data type used, a variable declared to be a string
may either cause storage in memory to be statically allocated for a predetermined maximum length
or employ dynamic allocation to allow it to hold variable number of elements.
When a string appears literally in source code, it is known as a string literal or an anonymous string.
In formal languages, which are used in mathematical logic and theoretical computer science, a string
is a finite sequence of symbols that are chosen from a set called an alphabet.

11. POINTERS.
A pointer is a programming language object, whose value refers to (or "points to") another value
stored elsewhere in the computer memory using its memory address. A pointer references a location
in memory, and obtaining the value stored at that location is known as dereferencing the pointer. As
an analogy, a page number in a book's index could be considered a pointer to the corresponding
page; dereferencing such a pointer would be done by flipping to the page with the given page
number.
Pointers to data significantly improve performance for repetitive operations such as traversing
strings, lookup tables, control tables and tree structures. In particular, it is often much cheaper in
time and space to copy and dereference pointers than it is to copy and access the data to which the
pointers point.
Pointers are also used to hold the addresses of entry points for called subroutines in procedural
programming and for run-time linking to dynamic link libraries (DLLs). In object-oriented
programming, pointers to functions are used for binding methods, often using what are called virtual
method tables.
What Is A Pointer?

A pointer is a secondary data type (also known as derived data type) in C. It is built from one
of the primary data types available in C language. Basically pointer contains memory address
of other variable or function as their value. As pointer deals with memory address, it can be
used to access and manipulate data stored in memory.

A pointer is a variable that holds the memory address of another variable. For example, if a variable
called p contains the address of another variable called q, then p is said to point to q.

Therefore if q were at location 100 in memory, then p would have the value 100.

Benefits of using Pointer in C Program

Pointer is one of the most exciting features of C language and it has added power and
flexibility to the language. Pointer is in C language because it offers following benefits to the
programmers:

1. Pointers can handle arrays and data table efficiently.


2. Pointers support dynamic memory management.
3. Pointer helps to return multiple values from a function through function argument.
4. Pointer increases program execution speed.
5. Pointer is an efficient tool for manipulating structures, linked lists, queues stacks etc.

Michael Bwibo 0725327856 Page 96 of 142


Pointer Declaration

To declare a pointer variable, use this general form:


type *var_name;

Here, type is the base type of the pointer. The base type specifies the type of the object that the
pointer can point to. Notice that an asterisk precedes the variable name. This tells the computer that
a pointer variable is being created. For example, the following statement creates a pointer to an
integer.

int *p;

Pointer Operators

C contains two special pointer operators: * and &. The operator returns the address of the variable
it precedes. The * operator returns the value stored at the address that it precedes. The * pointer
operator has no relationship to the multiplication operator, which uses the same symbol). For
example, examine this short program.

#include<stdio.h>
main()
{
int *p, q;
q = 100; /* assign q 100 */
p = &q; /* assign p the address of q*/
printf(“%d”, *p);/* display q’s value using pointer*/
return 0;
}

This program prints 100 on the screen. Lets see why.

First, the line int *p, q; defines two variables: p, which is declared as an integer pointer, and q, which
is an integer. Next, q is assigned the value 100.

In the next line, p is assigned the address of q. You can verbalize the & operator as “address of.“
Therefore, this line can be read as: assign p the address of q. Finally, the value is displayed using the
* operator applied to p. The * operator can be verbalized as “at address”.
Therefore the printf( ) statement can be read as “print the value at address q,” which is 100.
When a variable value is referenced through a pointer, the process is called indirection. It is possible
to use the * operator on the left side of an assignment statement in order to assign a variable a new
value using a pointer to it. For example, this program assigns a value q indirectly using the pointer p.

#include<stdio.h>
main()
{
int *p, q;
p = &q; /* get q’s address */

Michael Bwibo 0725327856 Page 97 of 142


*p = 199; /* assign q a value using a pointer */
printf(“q’s value is %d”, q);
return 0;
}

Note: The type of the variable and type of pointer must match.

Operations Performed Using Pointers

Assignment
One can assign an address to a pointer by:
Using an array name or
Using the address operator

From the previous example, p1 is assigned the address of the beginning of the array which is cell
234.

(b) Dereferencing (value – finding)


The * operator gives the value pointed to.
From the previous example, p1 = 100 which is the value stored in location 234.

(c) Take a pointer address


Pointer variables have an address and a value. The & operator tells us where the pointer itself is
stored.
From the previous example, p1 is stored in address 3606 whose value is 234.

Example: Demonstrating pointers

Program that uses a for loop that counts from 0 to 9. It puts in the numbers using a pointer.

#include<stdio.h>
main()
{
int i,*p;
p = &i;
for ( i =0; i <10; i++)
printf (“ %d ”, *p);
return 0;
}
Example : Further demonstration of pointers

#include<stdio.h>
main()
{
int u1, u2;
int v = 3;
int *pv;
u1 = 2 * ( v + 5 );

Michael Bwibo 0725327856 Page 98 of 142


pv = &v;
u2 = 2 * (*pv + 5 );
printf(“ \n u1 = %d u2 = %d ”, u1, u2);
return 0;
}

Output
u1 = 16, u2 = 16.

Note
Never use a pointer of one type to point to an object of a different type.
For example:
int q;
float *fp;
fp = &q; /* pointer fp assigned the address of an integer */
fp = 100.23; / address used for assignment */

Do not use a pointer before it has been assigned the address of a variable. May cause program to
crash.

For example:
main()
{
int *p;
*p =10; */Incorrect since p is not pointing to anything */

}

10) ARRAYS.

An array is an aggregate data structure that is designed to store a group of objects of the same types.
Arrays can hold primitives as well as references. The array is the most efficient data structure for
storing and accessing a sequence of objects.

ARRAYS EXPLANATION.

An array is a collection of data items of similar data type. It’s a composite object;it is composed of
several elements with independent values all of which have the same type. The independent values
are called the elements of an array and they are stored in separate cells. Each cell of an array is
assigned an index or a subscript. An array can be:

Michael Bwibo 0725327856 Page 99 of 142


1.Single Dimension Array or
2.Multidimensional Array.

What Is An Array?

An array is a data structure that consists of 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;

Items share a name


Items can be of any simple data type e.g. char, float, int, double.
Individual elements are accessed using an integer index whose value ranges from 0 to the value of
the array size.

Illustration examples:
age
An array of 10 student ages (stored as integers)
22 19 20 21 21 22 23 10 19 20
letters
An array of 5 characters in an employee’s name
O K O T H

Declaring Arrays
An array definition comprises;
Storage class (optional)
Data type
Array name
Arraysize expression (usually a positive integer or symbolic constant). This is enclosed in square
brackets.

Syntax:
Array_type array_name[maximum size];
Examples:

(i) int c [100];


int is the data type of the array (type of elements held), c is the array name
100 is the maximum number of elements (array size)
This declaration tells the compiler to create an array called c for storing 100 numbers of type integer.
The positions of values in an array are normally indicated using an index. The indices normally begin
from 0 onwards e.g c[0], c[1]………

Static char message[20]; A 20 character-type array called message.


The individual array values persist within function calls (static).

float debts [20];

Michael Bwibo 0725327856 Page 100 of 142


This statement declares debts as an array of 20 elements. The first element is called debts[0], the
second debts [1], - - - - , debts[19] .

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 */

Array Dimensions and types

An array’s dimension is the number of indices required to manipulate the elements of the array.
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).
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.

(iii) Two – dimensional array

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).

Examples of two-dimensional array declarations

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
Arrays, like simple variables can be automatic, external or static.

Automatic array
An automatic array is one defined inside a function including formal arguments. C allows us to
initialise automatic array variables as follows.

Michael Bwibo 0725327856 Page 101 of 142


main()
{

int marks[5] = [30, 40, 50, 90, 60];


---------
---------
}

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.

External array
An external array is one defined outside a function.
They
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.

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.

Have a look at the following example.

int SOWS [5] = {12, 100, 8, 9 ,6};


main()
{
----------
----------

int feed(int n)
{
---------
---------
}

Static array
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

int account(int n, int m)


{
static int k[2] = {343, 332};
---------
---------

Michael Bwibo 0725327856 Page 102 of 142


}

Initializing 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.

type array_name[size] = { value list };

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.

int i[5] = {1, 4, 9, 16, 25};

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’.

char a[3] = { ‘A’, ‘B’, ‘C’};

If the character array is going to hold a string, you can initialise the array using a quoted string, as
shown here.

char name[6] = “Peter”;

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.

EXAMPLES OF 1D ARRAY.
E.g 1
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j; /* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{ n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */

Michael Bwibo 0725327856 Page 103 of 142


for (j = 0; j < 10; j++ )
{ printf("Element[%d] = %d\n", j, n[j] );
}
system("Pause");
return 0;
}

E.g 2
#include<stdio.h>
main()
{
char str1[80],str2[80];
printf( " Enter your name: \n");
gets(str1);
printf( " Enter your home county: \n");
gets(str2);
printf("Your name is %s\n",str1);
printf("Your home county is %s\n",str1);
system ("Pause");
return 0;
}

E.g 3
#include<stdio.h>
#define MONTHS 12
int days [MONTHS] = {31,28,31,30,31,30,31,31,30,31,30,31};
main()
{
int index;
extern int days[];
for(index=0; index <MONTHS; index ++)
printf( "Month %d has %d days. \n ", index+1, days [index]);
getch();
/*system("Pause");*/
return 0;
}

Initializing multidimentional arrays


Multidimensional arrays are initialised the same way as one-dimensional ones.

For example, here the array sqr is initialised with the values 1 though 9, using row order.

int sqr [3][3] = {

Michael Bwibo 0725327856 Page 104 of 142


1, 2, 3,
4, 5, 6,
7, 8, 9
};

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. This helps avoid counting errors on long lists,
which is especially important when initialising strings.

Here an unsized array is used to hold a prompting message.

char prompt[ ] = “Enter your name: “;

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.

EXAMPLES OF 2D ARRAY.
E.g 1
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;

Michael Bwibo 0725327856 Page 105 of 142


/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("%d\t",a[i][j] );
}
printf("\n");
}
system("Pause");
return 0;
}

E.g 2
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2];
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{

printf("enter values = ");


scanf("%d",&a[i][j]);
/*printf("\n\t %d \n", a[i][j]);
printf("%d\n",a[i][j] );
/*printf("a[%d][%d] = %d\n", i,j, a[i][j] ); */
}
}
printf("\n\n Array elements \n ");
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{

printf("%d\t",a[i][j]);

}
printf("\n");
}
system("Pause");
return 0;
}

Michael Bwibo 0725327856 Page 106 of 142


SEARCHING AND SORTING.

Sorting is the process of arranging a collection of data in order. Sorting can alsobe defined as the
process of arranging data items in a specified order. Forexample, arranging names of students in a
class in an alphabetical order. The numerical data can be arranged in increasing or decreasing order
andcharacter data can be arranged alphabetically.

SORTING TECHNIQUES.

Sorting is the process of arranging data items in a specified order. For example, arranging names of
students in a class in an alphabetical order. The basic operation in Sorting techniques is to compare
the data items of the array with other data items of the array and swap the position of these data
itemsof the array in a specified order i.e. ascending or descending. Sorting techniques can be
implemented using any programming language, such as Pascal. The following sorting techniques can
used to arrange data items in a specifiedorder:

a)Bubble Sort
b)Insertion Sort
c)Selection Sort
d)Quick Sort
e)Shell Sort
f)Merge Sort etc.

BUBBLE SORT

This is the simplest sorting algorithm. The bubble sort is a sorting technique that keeps comparing
the two adjacent data items of an array and swaps them in a specified order repeatedly until the
whole array has been sorted.

How It Works
This technique starts with comparing the first two data items of the array andswaps them if they are
not in a specified order. After sorting the first two dataitems of the array, the next two data items are
compared and swapped, if they arenot in order. This process continues until all the data items of the

Michael Bwibo 0725327856 Page 107 of 142


array arecompared or the end of the array is reached. This process of comparingconsecutive data
items continues till the whole array is sorted in a specifiedorder.

Algorithm
We assume list is an array of n elements. We further assume that swapfunction swaps the values of
the given array elements.

begin BubbleSort(list)
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort

Pseudo code
We observe in algorithm that Bubble Sort compares each pair of array element unless the whole
array is completely sorted in an ascending order. This may cause a few complexity issues like what if
the array needs no more swapping as all the elements are already ascending.
To ease-out the issue, we use one flag variable swapped which will help us see if any swap has
happened or not. If no swap has occurred, i.e. the array requires no more processing to be sorted, it
will come out of the loop.
Pseudocode of BubbleSort algorithm can be written as follows −

procedure bubbleSort( list : array of items )


loop = list.count;
for i = 0 to loop-1 do:
swapped = false
for j = 0 to loop-1 do:
/* compare the adjacent elements */
if list[j] > list[j+1] then
/* swap them */

Michael Bwibo 0725327856 Page 108 of 142


swap( list[j], list[j+1] )
swapped = true
end if
end for
/*if no number was swapped that means
array is sorted now, break the loop.*/
if(not swapped) then
break
end if
end for
end procedure return list

Example 1

#include<stdio.h>
main()
{
int item[100];

Michael Bwibo 0725327856 Page 109 of 142


int a, b, t;
int count;
/* Read in the numbers */
printf(" How many numbers? ");
scanf(" %d ", &count);
for (a = 0; a < count; a ++)
scanf(" %d", &item[a]);
/* Now sort them using a bubble sort */
for(a = 1; a < count; ++ a)
for(b = count - 1; b >=a; -- b)

{
/* Compare adjacent items */
if (item[b -1] > item[b])
/* exchange the elements */
{
t = item[b - 1];
item[b - 1] = item[b];
item[b] = t;
}
}
/* Display sorted list */
for(t = 0; t < count; t++)
printf(" %d ", item[t]);
system ("Pause");
return 0;
}
INSERTION SORT
This is simple but inefficient sorting algorithm. The Insertion sort is a sorting technique that picks a
data item of an array and then inserts it in the correct position in another array.In insertion sort, an
array is divided into two sub-arrays. The first keeps only the sorted data items and the second sub-
array keeps remaining unsorted data items. The data item is moved from the second sub-array to the

Michael Bwibo 0725327856 Page 110 of 142


first sub-array until the second sub-array is empty and the first sub-array contain the sorted data
items.

How It Works
This technique starts with selecting the first data item of the array from theunsorted list and then
places it in the other (sorted) list. The data items aresequentially selected from the unsorted list and
placed at the appropriate positionin the other (sorted) list. This process continues until all the data
items of thearray are sorted in a specified order.

Algorithm
Now we have a bigger picture of how this sorting technique works, so we can derive simple steps
by which we can achieve insertion sort.

Insertion sort(a[],n)
for j->2 to n
do key <-a[j]
i<-j-1
while i>=0 and a[i]>key
do a[i+1]<-a[i]
i<-i+1
a[i+1]<-key
end

Step 1 − If it is the first element, it is already sorted. return 1;


Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted

Michael Bwibo 0725327856 Page 111 of 142


Pseudocode

procedure insertionSort( A : array of items )


int holePosition
int valueToInsert
for i = 1 to length(A) inclusive do:
/* select value to be inserted */
valueToInsert = A[i]
holePosition = i
/*locate hole position for the element to be inserted */
while holePosition > 0 and A[holePosition-1] > valueToInsert do:
A[holePosition] = A[holePosition-1]
holePosition = holePosition -1
end while
/* insert the number at hole position */
A[holePosition] = valueToInsert
end for
end procedure

Michael Bwibo 0725327856 Page 112 of 142


SELECTION SORT
Selection sort is a sorting technique that selects a data item and stores it in the appropriate position
of the array, until all the data items are arranged. In the selection sort technique, the smallest data
item in the array is selected and stored in the first position. The second smallest data item of the
array is selected and stored in the second position of the array. This process of selecting and
replacing continues until all the data items of the array are arranged in a sorted order.

1. selectionSort(array, size)
2. repeat (size - 1) times
3. set the first unsorted element as the minimum
4. for each of the unsorted elements
5. if element < currentMinimum
6. set element as new minimum
7. swap minimum with first unsorted position
8. end selectionSort

Algorithm

Step 1 − Set MIN to location 0


Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted

Pseudocode

procedure selection sort


list : array of items
n : size of list
for i = 1 to n - 1
/* set current element as minimum*/
min = i

/* check the element to be minimum */

Michael Bwibo 0725327856 Page 113 of 142


for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for
/* swap the minimum element with the current element*/
if indexMin != i then
swap list[min] and list[i]
end if
end for
end procedure

Quick Sort.
In this method, an element called pivot is identified and that element is fixed in its place by moving
all the elements less than that to its left and all the elements greater than that to its right.

Quick Sort Algorithm


Using pivot algorithm recursively, we end up with smaller possible partitions. Each partition is then
processed for quick sort. We define recursive algorithm for quicksort as follows −

Step 1 − Make the right-most index value pivot


Step 2 − partition the array using pivot value

Michael Bwibo 0725327856 Page 114 of 142


Step 3 − quicksort left partition recursively
Step 4 − quicksort right partition recursively

int partition ( int A[],int start ,int end) {


int i = start + 1;
int piv = A[start] ; //make the first element as pivot element.
for(int j =start + 1; j <= end ; j++ ) {
/*rearrange the array by putting elements which are less than pivot
on one side and which are greater that on other. */
if ( A[ j ] < piv) {
swap (A[ i ],A [ j ]);
i += 1;
}
}
swap ( A[ start ] ,A[ i-1 ] ) ; //put the pivot element in its proper place.
return i-1; //return the position of the pivot
}

Michael Bwibo 0725327856 Page 115 of 142


Quick Sort Pseudocode
To get more into it, let see the pseudocode for quick sort algorithm −

procedure quickSort(left, right)


if right-left <= 0
return
else
pivot = A[right]
partition = partitionFunc(left, right, pivot)
quickSort(left,partition-1)
quickSort(partition+1,right)
end if
end procedure

Shellsort.

Michael Bwibo 0725327856 Page 116 of 142


Shellsort, also known as Shell sort or Shell's method, is an in-place comparison sort. It can either be
seen as a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion
sort).The method starts by sorting elements far apart from each other and progressively reducing the
gap between them. Starting with far apart elements can move some out-of-place elements into
position faster than a simple nearest neighbor exchange

Algorithm
Following is the algorithm for shell sort.

Step 1 − Initialize the value of h


Step 2 − Divide the list into smaller sub-list of equal interval h
Step 3 − Sort these sub-lists using insertion sort
Step 3 − Repeat until complete list is sorted

Pseudocode
Following is the pseudocode for shell sort.

procedure shellSort()
A : array of items

/* calculate interval*/
while interval < A.length /3 do:
interval = interval * 3 + 1
end while

while interval > 0 do:

for outer = interval; outer < A.length; outer ++ do:

/* select value to be inserted */


valueToInsert = A[outer]
inner = outer;

/*shift element towards right*/

Michael Bwibo 0725327856 Page 117 of 142


while inner > interval -1 && A[inner - interval] >= valueToInsert do:
A[inner] = A[inner - interval]
inner = inner - interval
end while
/* insert the number at hole position */
A[inner] = valueToInsert
end for
/* calculate interval*/
interval = (interval -1) /3;
end while
end procedure

Michael Bwibo 0725327856 Page 118 of 142


Merge Sort.

Merge sort is a sorting algorithm that sorts data items into ascending or descending order, which
comes under the category of comparison-based sorting. Here we apply the divide-and-conquer
strategy to sort a given sequence of data items, which can be described as follows:

1. Recursively split the sequence into two halves (i.e. subsequences) until the subsequence contains
only a single data item (i.e. singleton subsequence).
2. Now, recursively merge these subsequences back together preserving their required order (i.e.
ascending or descending order).
-In computer science, merge sort (also commonly spelled merge sort) is an O(n log n) based sorting.
Most implementations produce a stable sort, which means that the implementation preserves the
input order of equal elements in the sorted output. Merge sort is a divide and conquer algorithm that
was invented by John von Neumann in 1945.

Michael Bwibo 0725327856 Page 119 of 142


Algorithm
Merge sort keeps on dividing the list into equal halves until it can no more be divided. By
definition, if it is only one element in the list, it is sorted. Then, merge sort combines the smaller
sorted lists keeping the new list sorted too.

Step 1 − if it is only one element in the list it is already sorted, return.


Step 2 − divide the list recursively into two halves until it can no more be divided.
Step 3 − merge the smaller lists into new list in sorted order.

Pseudocode
We shall now see the pseudocodes for merge sort functions. As our algorithms point out two main
functions − divide & merge.
Merge sort works with recursion and we shall see our implementation in the same way.

procedure mergesort( var a as array )


if ( n == 1 ) return a
var l1 as array = a[0] ... a[n/2]
var l2 as array = a[n/2+1] ... a[n]
l1 = mergesort( l1 )
l2 = mergesort( l2 )
return merge( l1, l2 )
end procedure
procedure merge( var a as array, var b as array )
var c as array
while ( a and b have elements )
if ( a[0] > b[0] )
add b[0] to the end of c
remove b[0] from b
else
add a[0] to the end of c
remove a[0] from a
end if
end while

Michael Bwibo 0725327856 Page 120 of 142


while ( a has elements )
add a[0] to the end of c
remove a[0] from a
end while
while ( b has elements )
add b[0] to the end of c
remove b[0] from b
end while
return c
end procedure

Heapsort
Is a comparison-based sorting algorithm. Heapsort is part of the selection sort family; it improves on
the basic selection sort by using a logarithmic-time priority queue rather than a linear-time search.
Although somewhat slower in practice on most machines than a well-implemented quicksort, it has
the advantage of a more favorable worst-case O(n log n) runtime.

Advantages and Disadvantages.

Insertion sort provides several advantages:


Simple implementation.
Efficient for (quite) small data sets.
Adaptive, i.e. efficient for data sets that are already substantially sorted: the time complexity is O(n +
d), where d is the number of inversions.
More efficient in practice than most other simple quadratic, i.e. O(n2) algorithms such as selection
sort or bubble sort; the best case (nearly sorted input) is O(n).
Stable, i.e. does not change the relative order of elements with equal keys
In-place, i.e. only requires a constant amount O(1) of additional memory space
Online, i.e. can sort a list as it receives it.

Michael Bwibo 0725327856 Page 121 of 142


Disadvantages of insertion sort:
It is less efficient on list containing more number of elements.
As the number of elements increases the performance of the program would be slow.
Insertion sort needs a large number of element shifts.

Bubble Sort
The bubble sort algorithm works by repeatedly swapping adjacent elements that are not in order
until the whole list of items is in sequence. In this way, items can be seen as bubbling up the list
according to their key values.
The primary advantage of the bubble sort is that it is popular and easy to implement. Furthermore,
in the bubble sort, elements are swapped in place without using additional temporary storage, so the
space requirement is at a minimum. The main disadvantage of the bubble sort is the fact that it does
not deal well with a list containing a huge number of items. This is because the bubble sort requires
n-squared processing steps for every n number of elements to be sorted. As such, the bubble sort is
mostly suitable for academic teaching but not for real-life applications.

Selection Sort
The selection sort works by repeatedly going through the list of items, each time selecting an item
according to its ordering and placing it in the correct position in the sequence.
The main advantage of the selection sort is that it performs well on a small list. Furthermore,
because it is an in-place sorting algorithm, no additional temporary storage is required beyond what
is needed to hold the original list. The primary disadvantage of the selection sort is its poor
efficiency when dealing with a huge list of items. Similar to the bubble sort, the selection sort
requires n-squared number of steps for sorting n elements. Additionally, its performance is easily
influenced by the initial ordering of the items before the sorting process. Because of this, the
selection sort is only suitable for a list of few elements that are in random order.

Insertion Sort
The insertion sorts repeatedly scans the list of items, each time inserting the item in the unordered
sequence into its correct position.
The main advantage of the insertion sort is its simplicity. It also exhibits a good performance when
dealing with a small list. The insertion sort is an in-place sorting algorithm so the space requirement

Michael Bwibo 0725327856 Page 122 of 142


is minimal. The disadvantage of the insertion sort is that it does not perform as well as other, better
sorting algorithms. With n-squared steps required for every n element to be sorted, the insertion sort
does not deal well with a huge list. Therefore, the insertion sort is particularly useful only when
sorting a list of few items.

Quick Sort
The quick sort works on the divide-and-conquer principle. First, it partitions the list of items into
two sublists based on a pivot element. All elements in the first sublist are arranged to be smaller than
the pivot, while all elements in the second sublist are arranged to be larger than the pivot. The same
partitioning and arranging process is performed repeatedly on the resulting sublists until the whole
list of items are sorted.
The quick sort is regarded as the best sorting algorithm. This is because of its significant advantage
in terms of efficiency because it is able to deal well with a huge list of items. Because it sorts in place,
no additional storage is required as well. The slight disadvantage of quick sort is that its worst-case
performance is similar to average performances of the bubble, insertion or selections sorts. In
general, the quick sort produces the most effective and widely used method of sorting a list of any
item size.

SEARCHING TECHNIQUES

Searching is the process of finding the location of some desired data in a collection of data items,
such as an array. If the data item that you want to search matches with any data item of the array, the
search returns the location of the data item that matches. Otherwise, the search fails.
There are three searching techniques namely:

1. Linear/Sequential Search
2. Binary Search
3. Merge Searching.

1)Linear/Sequential search.

Michael Bwibo 0725327856 Page 123 of 142


In linear search, the data item to be searched is compared with each element of the array, starting
from the beginning until the data item is found. In linear search, a data item is compared with each
data item of the array one by one until you find the location of the desired data item in the array or
the end of the array is reached. If the desired data item is found, this search returns the location of
the desired item otherwise the search has failed.

Algorithm

Linear Search ( Array A, Value x)

Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit

Pseudocode

procedure linear_search (list, value)

for each item in the list


if match item == value
return the item's location
end if
end for

end procedure

Michael Bwibo 0725327856 Page 124 of 142


2)Binary Search.

Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an
interval covering the whole array. If the value of the search key is less than the item in the middle of
the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly
check until the value is found or the interval is empty.

Implementing Binary Search Algorithm


Following are the steps of implementation that we will be following:
1. Start with the middle element:

Michael Bwibo 0725327856 Page 125 of 142


o If the target value is equal to the middle element of the array, then return the index
of the middle element.
o If not, then compare the middle element with the target value,
▪ If the target value is greater than the number in the middle index, then pick
the elements to the right of the middle index, and start with Step 1.
▪ If the target value is less than the number in the middle index, then pick the
elements to the left of the middle index, and start with Step 1.
2. When a match is found, return the index of the element matched.
3. If no match is found, then return -1

Procedure binary_search
A ← sorted array
n ← size of array
x ← value to be searched

Set lowerBound = 1
Set upperBound = n

while x not found

Michael Bwibo 0725327856 Page 126 of 142


if upperBound < lowerBound
EXIT: x does not exists.

set midPoint = lowerBound + ( upperBound - lowerBound ) / 2

if A[midPoint] < x
set lowerBound = midPoint + 1

if A[midPoint] > x
set upperBound = midPoint - 1

if A[midPoint] = x
EXIT: x found at location midPoint
end while

end procedure

Michael Bwibo 0725327856 Page 127 of 142


Michael Bwibo 0725327856 Page 128 of 142
Example:

The Binary search uses the “divide and conquer” strategy. It repeatedly divides the array into two
pieces and then searches the piece that could contain the target value. It can only work if the array is
already sorted either in ascending order or in descending order.

Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm
works on the principle of divide and conquer. For this algorithm to work properly, the data
collection should be in a sorted form.

#include <stdio.h>

#define MAX 20

// array of items on which linear search will be conducted.


int intArray[MAX] = {1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66};

void printline(int count) {


int i;

Michael Bwibo 0725327856 Page 129 of 142


for(i = 0;i <count-1;i++) {
printf("=");
}

printf("=\n");
}

int find(int data) {


int lowerBound = 0;
int upperBound = MAX -1;
int midPoint = -1;
int comparisons = 0;
int index = -1;

while(lowerBound <= upperBound) {


printf("Comparison %d\n" , (comparisons +1) );
printf("lowerBound : %d, intArray[%d] = %d\n",lowerBound,lowerBound,
intArray[lowerBound]);
printf("upperBound : %d, intArray[%d] = %d\n",upperBound,upperBound,
intArray[upperBound]);
comparisons++;

// compute the mid point


// midPoint = (lowerBound + upperBound) / 2;
midPoint = lowerBound + (upperBound - lowerBound) / 2;

// data found
if(intArray[midPoint] == data) {
index = midPoint;
break;
} else {

Michael Bwibo 0725327856 Page 130 of 142


// if data is larger
if(intArray[midPoint] < data) {
// data is in upper half
lowerBound = midPoint + 1;
}
// data is smaller
else {
// data is in lower half
upperBound = midPoint -1;
}
}
}
printf("Total comparisons made: %d" , comparisons);
return index;
}

void display() {
int i;
printf("[");

// navigate through all items


for(i = 0;i<MAX;i++) {
printf("%d ",intArray[i]);
}

printf("]\n");
}

main() {
printf("Input Array: ");
display();
printline(50);

//find location of 1
int location = find(55);

Michael Bwibo 0725327856 Page 131 of 142


// if element was found
if(location != -1)
printf("\nElement found at location: %d" ,(location+1));
else
printf("\nElement not found.");
}

3)Merge search.
A searching technique based on divide and conquer technique. With worst-case time complexity
being Ο(n log n), it is one of the most respected algorithms. Merge search first divides the array into
equal halves and then combines them in a sorted manner.
How Merge search Works?
we take an unsorted array as the following

Merge search first divides the whole array iteratively into equal halves unless the atomic values are
achieved. We see here that an array of 8 items is divided into two arrays of size 4.

This does not change the sequence of appearance of items in the original. Now we divide these two
arrays into halves.

We further divide these arrays and we achieve atomic value which can no more be divided.

Now, we combine them in exactly the same manner as they were broken down. Please note the
color codes given to these lists.
We first compare the element for each list and then combine them into another list in a sorted
manner. We see that 14 and 33 are in sorted positions. We compare 27 and 10 and in the target list
of 2 values we put 10 first, followed by 27. We change the order of 19 and 35 whereas 42 and 44 are
placed sequentially.

In the next iteration of the combining phase, we compare lists of two data values, and merge them
into a list of found data values placing all in a sorted order.

After the final merging, the list should look like this −

Michael Bwibo 0725327856 Page 132 of 142


Array involving Strings
In C, one or more characters enclosed between double quotes is called a string. C has no built-in
string data type. Instead, C supports strings using one dimensional character arrays. A string is
defined as a null terminated character array. In C, a null is 0. This fact means that you must define
the array is going to hold a string to be one byte larger then the largest string it is going to hold, to
make room for the null.

To read a string from the keyboard you must use another of C’s standard library functions, gets( ),
which requires the STDIO.H header file. To use gets( ), call it using the name of a character array
without any index. The gets( ) function reads characters until you press <ENTER>. The carriage
return is not stored, but it is replaced by a null, which terminates the string. For example, this
program reads and writes a string entered at the keyboard.

#include<stdio.h>
main()
{
char str[80];
int i;
printf( “ Enter a string (less than 80 characters): \n”);
gets(str);
for( i = 0 ; str[i]; i++)
printf(“ %c”, str[i]);
return 0;
}
The gets( ) function performs no bounds checking, so it is possible for the user to enter more
characters that gets( ) is called with can hold. Therefore be sure to call it with an array large enough
to hold the expected input.

In the previous program, the string that was entered by the user was output to the screen a character
at a time. There is however a much easier way to display a string, using printf( ). Here is the previous
program rewritten..

#include<stdio.h>
main()
{
char str[80];
printf( “ Enter a string (less than 80 characters): \n”);
gets(str);
printf(str);
system(“pause”);
return 0;
}

Michael Bwibo 0725327856 Page 133 of 142


If you wanted to output a new line, you could output str like this:

printf( “%s \n”, str);

This method uses the %s format specifier followed by the new line character and uses the array as a
second argument to be matched by the %s specifier.

TOPIC 7: SUBPROGRAMS

SUBPROGRAMS

A subprogram is a program unit/module that performs a particular task. These subprograms are
combined to form larger programs. This is basically called the 'Modular design.' A subprogram can
be invoked by a subprogram/program, which is called the calling program.

Types of Sub programs

There are two kinds of subprograms:

Functions: these subprograms return a single value.


Procedures: these subprograms do not return a value directly.

Basic Difference Between a function and a procedure.


Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n
values).
Functions can have only input parameters for it whereas Procedures can have input/output
parameters.

Scope of variables

Scope of variable refers to the visibility of a variable in a program. A scope is a region of the
program and broadly speaking there are three places, where variables can be declared − Inside a
function or a block which is called local variables, In the definition of function parameters which is
called formal parameters. Outside of all functions which is called global variables.

1) Local Variables
Are variables declared inside a given procedure and can be accessed or used only in a procedure in
which they are declared. These types of variables are only meaningful inside the procedure. No
statements outside the procedure may reference local variables. A local variable is a variable which is
either a variable declared within the function or is an argument passed to a function. As you may
have encountered in your programming, if we declare variables in a function then we can only use
them within that function.

2) Global Variables

Michael Bwibo 0725327856 Page 134 of 142


Are variables declared for the entire program. Global variables can be utilized anywhere within the
program block, whether inside of or external to the procedure. Global variable is a variable with
global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed.
The set of all global variables is known as the global environment or global state. In some languages,
all variables are global, or global by default, while in most modern languages variables have limited
scope, generally lexical scope, though global variables are often available by declaring a variable at
the top level of the program. In other languages, however, global variables do not exist; these are
generally modular programming languages that enforce a module structure, or class-based object-
oriented programming languages that enforce a class structure.
Parameters
- A parameter is like a placeholder. A parameter is a special kind of variable, used in a subroutine to
refer to one of the pieces of data provided as input to the subroutine. ... These pieces of data are
called arguments. a parameter or "argument" is a value that is passed into a function. Most modern
programming languages allow functions to have multiple parameters. While the syntax of a function
declaration varies between programming languages, a typical function with two parameters may look
something like this:
function graphXY(x, y)
{
...
}
Types of parameters.
Actual parameter - When a function is invoked, you pass a value to the parameter. This value is
referred to as actual parameter or argument. The list of variables or constants after the procedure
name is known as actual parameter.
Formal parameter - The argument(s) that establish the linkage between the calling program and the
function identifiers are called the formal parameters.

Parameter passing.
Parameters can either be passed by value or by reference.
a) Pass by Value (Value Parameters).
b) Pass by Reference (Reference/Variable Parameters)

Value parameters – These are ‘one-way’ parameter i.e they can be used to supply information to a
procedure but they cannot be used to get information out of a procedure.This method copies the
actual value of an argument into the formal parameter of the subprogram. In this case, changes
made to the parameter inside the subprogram have no effect on the argument ( Call by value)
Variable parameter – Are used in applications where information must be transferred in both
directions between the procedure and the procedure reference. This method copies the address of
an argument into the formal parameter. Inside the subprogram, the address is used to access the
actual argument used in the call. This means that changes made to the parameter affect the
argument. (Call by reference)

Passing Arguments to main()


main() is passed two arguments from the shell: an integer and a pointer to an array of strings.
Traditionally these are declared as follows:
int main(int argc,char *argv[])
Here argc (``argument count'') contains one plus the number of arguments passed to the program
from the command line and argv (``argument vector'') contains a series of char pointers to these

Michael Bwibo 0725327856 Page 135 of 142


arguments. The first element in argv is always the name of the program itself, so argc is always at
least 1. The library function getopt() can perform simple parsing of command-line arguments. Here's
a more simple example of passing two numbers and a string. Note the error trapping to force the
user to conform to the expected usage:
#include <stdio.h>
#include <stdlib.h> /* for atoi() */

int main(int argc,char *argv[]) {


int m,n;
if (argc != 4) {
printf("Usage: %s m n filename\n",argv[0]);
return 1;
}
m = atoi(argv[1]); /* convert strings to integers */
n = atoi(argv[2]);
printf("%s received m=%i n=%i filename=%s\n",argv[0],m,n,argv[3]);
return 0;
}

FUNCTIONS IN C

A function is a self-contained program segment that carries out some specific well - defined task.
Every A Function is a group of self-contained statements that can be used to perform a particular
activity or a specific task similar to a procedure. It is used to return avalue to the procedure or
program which calls it.

Characteristics of a FUNCTION

1.It begins with the keyword FUNCTION


2.It returns some value (simple data types) when called
3.It is used on the right side of an expression
4. Somewhere inside the code associated with the function, a value is assigned to the function name.

Advantages of Functions.
A function improves the readability and the logic of a program.
It helps to reduce the length of the source code which in turn reduce the complexity of the program.
Functions are easy to debug.
Functions can be used repeatedly within a given program.
The function can be used to keep away the tendency to re-write the same block of code in different
program locations.

Types of Functions
i. User defined
ii. In Built.

Michael Bwibo 0725327856 Page 136 of 142


Inbuilt Functions.

Are functions that have been written and exist as library codes. They can be directly interpreted by
the compiler. The inbuilt functions are normally embodied in certain header files e.g math.h
Examples include sqrt(x), sin(x), cos(x) and pow(x) these to write programs

ABS
– The ABSolute Function returns the absolute value either an integer or reale.g. ABS (-34) returns
34
COS
– The COSine Function returns the cosine value, in radians, of an argumente.g. COS (0) returns 1.0
SIN
– The Sine Function returns the sine value, in radians, of an argument e.g.SIN (60) returns 0.8660
SQRT
– This function returns the square root of a number e.g. SQRT (25) returns5

#include <stdio.h>
int main()
{
int num1,num2,SQUAREROOT;
printf("Enter any number to find the square root\n");
scanf("%d",&num1);
SQUAREROOT=sqrt(num1); //function call
printf("square root is =%d\n",SQUAREROOT);
system("pause");
return 0;
}
C supports a wide range of functions that manipulate null-terminated strings:

S.N. Function & Purpose


1 strcpy(s1, s2); Copies string s2 into
string s1.
2 strcat(s1, s2); Concatenates string
s2 onto the end of string s1.
3 strlen(s1); Returns the length of
string s1.
4 strcmp(s1, s2); Returns 0 if s1 and
s2 are the same; less than 0(-1) if
s1<s2; greater than 0(1) if s1>s2.
5 strchr(s1, ch); Returns a pointer to
the first occurrence of character
ch in string s1.
6 strstr(s1, s2); Returns a pointer to
the first occurrence of string s2 in
string s1.

Eg1

Michael Bwibo 0725327856 Page 137 of 142


#include<stdio.h>
#include<string.h>
main()
{
char a[10],dif;
printf("enter your name:");
scanf("%s",&a);
strrev(a);
printf("your name is correct %s\n",a);
system("pause");
return 0;
}

Eg2
#include<stdio.h>
#include<string.h>
main()
{
char str1[80],str2[80],str3[80];
int len;
printf( " Enter a string (less than 80 characters): \n");
gets(str1);
len=strlen(str1);
printf("The length of your name is %d\n",len);
system ("Pause");
return 0;
}

Eg3
#include<stdio.h>
#include<string.h>
#define name "george"
main()
{
char str1[10],dif;
printf("enter your name:");
gets(str1);
//scanf("%s",&a);
/*printf("confirm your name:");
scanf("%s",&b);*/
dif = strcmp(str1,name);
if(dif == 0)
printf("your name is correct = %s\n",name);
system("pause");
return 0;
}
Eg4

Michael Bwibo 0725327856 Page 138 of 142


#include<stdio.h>
#include<string.h>
main()
{
char a[10];
printf("enter your name:");
scanf("%s",&a);
strupr(a);
printf("your name is correct %s\n",a);
system("pause");
return 0;
}

Eg5
#include<stdio.h>
#include<string.h>
main()

{
char a[10],dif;
printf("enter your name:");
scanf("%s",&a);
strlwr(a);
printf("your name is correct %s\n",a);
system("pause");
return 0;
}

User defined functions.

A user-defined function (UDF) is a function provided by the user of a program or environment, in a


context where the usual assumption is that functions are built into the program or environment. C
allows you to define functions according to your need. These functions are known as user-defined
functions. For example:
Suppose, you need to create a circle and color it depending upon the radius and color. You can
create two functions to solve this problem:
createCircle() function
color() function

Defining A Function

The general form of a function definition in C programming language is as follows:


return_type function_name( parameter list )
{

Michael Bwibo 0725327856 Page 139 of 142


body of the function
}
A function definition in C programming language consists of a function header and a function body.
Here are all the parts of a function:

Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The

parameter list refers to the type, order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.
Function Body: The function body contains a collection of statements that define what the
function does.

Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.

A function declaration has the following parts:


return_type function_name( parameter list );
For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so following is
also valid declaration:
int max(int, int);

Function declaration is required when you define a function in one source file and you call that
function in another file. In such case you should declare the function at the top of the file calling the
function.

Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function. A called
function performs defined task, and when its return statement is executed or when its function-
ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example:
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition */

Michael Bwibo 0725327856 Page 140 of 142


int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
system(“pause”);
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
I kept max() function along with main() function and compiled the source code. While running final
executable, it would produce the following result:

Example : Determining the maximum of two integers (Complete program)

The following program determines the largest of three integers quantities. The program makes use
of a function that determines the larger of two integer quantities. The overall strategy is to determine
the larger of the first two quantities and then compare the value with the third quantity. The largest
quantity is then displayed by the main part of the program.

/*Determine the largest of the three integer quantities*/


#include<stdio.h>
int maximum (int x, int y) /*Determine the larger of two quantities*/
{
int z;
z = (x > = y )? x : y;
return(z);
}
main()
{
int a , b , c ,d;
/*read the integer quantities*/
printf(“\n a = ”);
scanf(“%d”, &a);
printf(“\n b = ” );
scanf(“%d”, &b);

Michael Bwibo 0725327856 Page 141 of 142


printf(“\n c = ”);
scanf(“%d”, &c);
/* Calculate and display the maximum value */
d = maximum (a, b);
printf (“\n \n maximum = % d ”, maximum (c ,d));
system(“pause”);
return 0;
}

Function Prototypes

In the previous function examples, the programmer -defined function has always preceded main.
Thus when the programs are compiled, the programmer-defined function will have been defined
before the first function access. However many programmers prefer a top down approach in which
main appears ahead of the programmer-defined function definition. In such a situation, the function
access (within main) will precede the function definition. This can be confusing to the compiler
unless the compiler is first alerted to the fact that the function being accessed will be defined later in
the program. A function prototype is used for this purpose

Function prototypes are usually written at the beginning of a program ahead of any programmer-
defined function (including main) .
The general form of a function prototype is;

data_type function_name (type 1 argument 1, type 2 argument 2, ., type n argument n);

Where data_type represents the type of the item that is returned by the function, function_name
represents the name of the function, type 1, type 2, … …., type n represent the types of the
arguments 1 to n.

Note that a function prototype resembles the first line of a function definition (although a definition
prototype ends with a semicolon).
Function prototypes are not a must but are desirable however because they further facilitate error
checking between the calls to a function and the corresponding function definition.

The names of the argument within the function prototype need not be declared else where in the
program since these are “dummy” argument names that are recognised only within the prototype. In
fact, the argument names can be omitted (though it is not a good idea to do so). However the
arguments data types are essential.

Function prototypes are not mandatory in C. They are desirable however because they further
facilitate error checking between the calls to a function and the corresponding function definition.

E.g 1.

/*Program to demonstrate the working of user defined function*/


#include <stdio.h>
int add(int a, int b); //function prototype(declaration)

Michael Bwibo 0725327856 Page 142 of 142


int main()
{
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
printf("sum=%d",sum);
system("pause");
return 0;
}
int add(int a,int b) //function declarator
{
/* Start of function definition. */
int add;
add=a+b;
return add; //return statement of function
/* End of function definition. */
}

E.g 2
/*Program to demonstrate the working of user defined function*/
#include <stdio.h>
int cube(int a); //function prototype(declaration)
int main()
{
int num1,num2,sum;
printf("Enter any number to find the cube\n");
scanf("%d",&num1);
sum=cube(num1); //function call
printf("cube of %d = %d\n", num1, sum);
system("pause");
return 0;
}
int cube(int a) //function declarator
{
/* Start of function definition. */
int cube;
cube=a*a*a;
return cube; //return statement of function
/* End of function definition. */
}

Recursion is the process by which a function calls itself repeatedly until a special condition is
satisfied.To use recursion, two conditions must be satisfied:
(i) The problem must be written in a recursive form.
(ii) There must be a stopping case (terminating condition).

Michael Bwibo 0725327856 Page 143 of 142


/* Source code to find factorial of a number. */

#include <stdio.h>
int factorial( int i) //unsigned
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
int main()
{ int i;
printf("Enter an positive integer: ");
scanf("%d",&i);
printf("Factorial of %d is %d\n", i, factorial(i));
system("pause");
return 0;
}

Fibonacci Series
Following is another example, which generates Fibonacci series for a given number using a recursive
function:

#include <stdio.h>
int fibonaci(int i)
{
if(i == 0)

{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%d\t", fibonaci(i));
}
system("pause");

Michael Bwibo 0725327856 Page 144 of 142


return 0; }

The passing by value guarantees that the procedure will not change the value of the parameter.
Generally we use call by value mechanism if we don’t need the changes made in calling function to
reflect in called function. E.g.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int a, int b);

int main()
{
int m = 22, n = 44;
// calling swap function by value
printf(" values before swap m = %d \nand n = %d", m, n);
swap(m, n);
system("pause");
return 0;
}

void swap(int a, int b)


{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}

Each variable has some fixed address which remains constant throughout execution of program in
memory. Using this address of variable, it is also possible to access and modify the value of variable
by using pointer. But if we required the changes to reflect in called function we use call by reference
mechanism.

#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);

int main()
{

int m = 22, n = 44;


// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
system("pause");
return 0;

Michael Bwibo 0725327856 Page 145 of 142


void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
}

Passing Arrays as Function Arguments


If you want to pass a single-dimension array as an argument in a function, you would have to declare
function formal parameter in one of following three ways and all three declaration methods produce
similar results because each tells the compiler that an integer pointer is going to be received. Similar
way you can pass multi-dimensional array as formal parameters.
Example 1:
#include <stdio.h>
float average(float c[]);
int main()
{
int i;
float avg,sum, c[6]={23.4, 55, 22.6, 3, 40.5, 18};
avg=average(c); /* Only name of array is passed as argument. */
printf("Average=%.2f\n",avg);
system("pause");
return 0;
}
float average(float c[])
{
int i;
float avg, sum=0.0;
for(i=0;i<6;++i)
{
sum+=c[i];
}
avg =(sum/6);
return avg;
}

Example 2:
/* example program to demonstrate the passing of an array */
#include <stdio.h>
int maximum( int [] ); /* ANSI function prototype */

int maximum( int values[5] )


{
int max_value, i;

Michael Bwibo 0725327856 Page 146 of 142


max_value = values[0];
for( i = 0; i < 5; ++i )
if( values[i] > max_value )
max_value = values[i];
return max_value;
}

main()
{
int values[5], i, max;

printf("Enter 5 numbers\n");
for( i = 0; i < 5; ++i )
scanf("%d", &values[i] );
for( i = 0; i < 5; ++i )
printf("Element[%d] = %d\n", i, values[i] );
max = maximum( values );
printf("\nMaximum value is %d\n", max );
system("Pause");
return 0;
}

TOPIC 8 : FILE HANDLING.

What is a File?

A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming
language provides access on high level functions as well as low level (OS level) calls to handle file on
your storage devices. It is a collection of bytes stored on a secondary storage device, which is
generally a disk of some kind. The collection of bytes may be interpreted, for example, as characters,
words, lines, paragraphs and pages from a textual document; fields and records belonging to a
database; or pixels from a graphical image. The meaning attached to a particular file is determined
entirely by the data structures and operations used by a program to process the file. It is conceivable
(and it sometimes happens) that a graphics file will be read and displayed by a program designed to
process textual data. The result is that no meaningful output occurs (probably) and this is to be
expected. A file is simply a machine decipherable storage media where programs and data are stored
for machine usage.

Importance of file handling.

-It meets the data management needs and requirements of the user, which include
storage of data and the ability to perform the aforementioned operations.
-It guarantee, to the extent possible, that the data in the file are valid.
-Optimize performance, both from the system point of view in terms of overall

Michael Bwibo 0725327856 Page 147 of 142


throughput and from the user’s point of view in terms of response time.
-It provide I/O support for a variety of storage device types.
-It minimize or eliminate the potential for lost or destroyed data.
-It provide a standardized set of I/O interface routines to user processes.
-It provide I/O support for multiple users, in the case of multiple-user systems

Why files are needed?


• When a program is terminated, the entire data is lost. Storing in a file will preserve your data
even if the program terminates.
• If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the file using
few commands in C.
• You can easily move your data from one computer to another without any changes.

Types of Files

When dealing with files, there are two types of files you should know about:

1. Text files
2. Binary files
1. Text files

Text files are the normal .txt files that you can easily create using Notepad or any simple text editors.

When you open those files, you'll see all the contents within the file as plain text. You can easily edit
or delete the contents.

They take minimum effort to maintain, are easily readable, and provide least security and takes
bigger storage space.

2. Binary files

Binary files are mostly the .bin files in your computer.

Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold higher amount of data, are not readable easily and provides a better security than text
files.

Michael Bwibo 0725327856 Page 148 of 142


File Operations

In C, you can perform four major operations on the file, either text or binary:

1. Creating a new file


2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file

Working with files

When working with files, you need to declare a pointer of type file. This declaration is needed for
communication between the file and program.

FILE *fptr;

Opening a file - for creation and edit


Opening a file is performed using the library function in the "stdio.h" header file: fopen().

The syntax for opening a file in standard I/O is:

ptr = fopen("fileopen","mode")

File Opening Mode Chart :


fopen Returns if FILE-
Mode Meaning
Exists Not Exists
r Reading – NULL
Create New
w Writing Over write on Existing
File
Create New
a Append –
File
New data is written at the beginning overwriting Create New
r+ Reading + Writing
existing data File
w+ Reading + Writing Over write on Existing Create New

Michael Bwibo 0725327856 Page 149 of 142


File
Reading + Create New
a+ New data is appended at the end of file
Appending File
Explanation :

1. File can be opened in basic 3 modes : Reading Mode, Writing Mode, Appending Mode
2. If File is not present on the path specified then New File can be created using Write and
Append Mode.
3. Generally we used to open following types of file in C –

File Type Extension


C Source File .c
Text File .txt
Data File .dat

Opening Modes in Standard I/O


File
Meaning of Mode During Inexistence of file
Mode
r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
If the file exists, its contents are overwritten. If the
w Open for writing.
file does not exist, it will be created.
If the file exists, its contents are overwritten. If the
wb Open for writing in binary mode.
file does not exist, it will be created.
Open for append. i.e, Data is added to
a If the file does not exists, it will be created.
end of file.
Open for append in binary mode. i.e,
ab If the file does not exists, it will be created.
Data is added to end of file.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
Open for both reading and writing in
rb+ If the file does not exist, fopen() returns NULL.
binary mode.
If the file exists, its contents are overwritten. If the
w+ Open for both reading and writing.
file does not exist, it will be created.
Open for both reading and writing in If the file exists, its contents are overwritten. If the
wb+
binary mode. file does not exist, it will be created.
a+ Open for both reading and appending. If the file does not exists, it will be created.
Open for both reading and appending
ab+ If the file does not exists, it will be created.
in binary mode.

putw(), getw() functions in C

Michael Bwibo 0725327856 Page 150 of 142


putw(), getw() functions are file handling function in C programming language which is used to write
an integer value into a file (putw) and read integer value from a file (getw). Please find below the
description and syntax for above file handling functions.
File
Declaration & Description
operation
Declaration: int putw(int number, FILE *fp);
putw function is used to write an integer into a file. In a C program, we can write
integer value in a file as below.
putw(i, fp);
putw()
where
i – integer value
fp – file pointer
Declaration: int getw(FILE *fp);
getw function reads an integer value from a file pointed by fp. In a C program, we can
getw()
read integer value from a file as below.
getw(fp);
Example program for putw(), getw() function in C programming language:
This file handling C program illustrates how to write into a file using putw() function and how to
read the same file using getw() function.
1 #include <stdio.h>
2
3 int main ()
4 {
5 FILE *fp;
6 int i=1, j=2, k=3, num;
7 fp = fopen ("test.c","w");
8 putw(i,fp);
9 putw(j,fp);
10 putw(k,fp);
11 fclose(fp);
12 fp = fopen ("test.c","r");
13 while(getw(fp)!=EOF)
14 {
15 num= getw(fp);
16 printf(“Data in test.c file is %d \n”, num);
17 }
18 fclose(fp);
19 return 0;
20 }

Output:

Other Inbuilt file handling functions in C programming language:

Michael Bwibo 0725327856 Page 151 of 142


C programming language offers many other inbuilt functions for handling files. They are given
below. Please click on each function name below to know more details, example programs, output
for the respective file handling function.
File
Description
handling functions
fopen () fopen () function creates a new file or opens an existing file.
fclose () fclose () function closes an opened file.
getw () getw () function reads an integer from file.
putw () putw () functions writes an integer to file.
fgetc () fgetc () function reads a character from file.
fputc () fputc () functions write a character to file.
gets () gets () function reads line from keyboard.
puts () puts () function writes line to o/p screen.
fgets () fgets () function reads string from a file, one line at a time.
fputs () fputs () function writes string to a file.
feof () feof () function finds end of file.
fgetchar () fgetchar () function reads a character from keyboard.
fprintf () fprintf () function writes formatted data to a file.
fscanf () fscanf () function reads formatted data from a file.
fputchar () function writes a character onto the output screen from keyboard
fputchar ()
input.
fseek () fseek () function moves file pointer position to given location.
SEEK_SET SEEK_SET moves file pointer position to the beginning of the file.
SEEK_CUR SEEK_CUR moves file pointer position to given location.
SEEK_END SEEK_END moves file pointer position to the end of file.
ftell () ftell () function gives current position of file pointer.
rewind () rewind () function moves file pointer position to the beginning of the file.
getc () getc () function reads character from file.
getch () getch () function reads character from keyboard.
getche () getche () function reads character from keyboard and echoes to o/p screen.
getchar () getchar () function reads character from keyboard.
putc () putc () function writes a character to file.
putchar () putchar () function writes a character to screen.

Michael Bwibo 0725327856 Page 152 of 142


printf () printf () function writes formatted data to screen.
sprinf () sprinf () function writes formatted output to string.
scanf () scanf () function reads formatted data from keyboard.
sscanf () sscanf () function Reads formatted input from a string.
remove () remove () function deletes a file.
fflush () fflush () function flushes a file.

Single Character Output Function : putch()


putch displays any alphanumeric characters to the standard output device. It displays only one
character at a time.
Declaration:
putch(variable_name);
Example Declaration:
char ch = 'a';

putch(ch)
Remarks:
putch print only one character at a time screen.
Example Program:
void main()
{
char ch='a';
putch(ch)
}

File organisation techniques.

File Access Method


The way by which information/data can be retrieved. There are two methods of file access:
Direct Access
Sequential Access
Direct Access

This access method the information/data stored on a device can be accessed randomly and
immediately irrespective to the order it was stored. The data with this access method is quicker than
sequential access. This is also known as random access method. For example Hard disk, Flash
Memory.
Sequential Access

This access method the information/data stored on a device is accessed in the exact order in which
it was stored. Sequential access methods are seen in older storage devices such as magnetic tape.

File Organization Method

Michael Bwibo 0725327856 Page 153 of 142


The process that involves how data/information is stored so file access could be as easy and quickly
as possible. Three main ways of file organization:
Sequential
Index-Sequential
Random
Sequential file organization
All records are stored in some sort of order (ascending, descending, alphabetical). The order is based
on a field in the record. For example a file holding the records of employeeID, date of birth and
address. The employee ID is used and records stored is group accordingly (ascending/descending).
Can be used with both direct and sequential access.

Index-Sequential organization
The records is stores in some order but there is a second file called the index-file that indicates
where exactly certain key points. Can not be used with sequential access method.

Random file organization


The records are stored randomly but each record has its own specific position on the disk (address).
With this method no time could be wasted searching for a file. Instead it jumps to the exact position
and access the data/information. Can only be used with direct access access method.

File organization methods


File organization refers to the way data is stored in a file. File organization is very important because
it determines the methods of access, efficiency, flexibility and storage devices to use. There are four
methods of organizing files on a storage media. This include:
sequential,
random,
serial and
indexed-sequential

Sequential file organization


Records are stored and accessed in a particular order sorted using a key field.
Retrieval requires searching sequentially through the entire file record by record to the end.
Because the record in a file are sorted in a particular order, better file searching methods like the
binary search technique can be used to reduce the time used for searching a file .
Since the records are sorted, it is possible to know in which half of the file a particular record being
searched is located, Hence this method repeatedly divides the set of records in the file into two
halves and searches only the half on which the records is found.
For example, of the file has records with key fields 20, 30, 40, 50, 60 and the computer is searching
for a record with key field 50, it starts at 40 upwards in its search, ignoring the first half of the set.

Advantages of sequential file organization


The sorting makes it easy to access records.
The binary chop technique can be used to reduce record search time by as much as half the time
taken.

Disadvantages of sequential file organization

Michael Bwibo 0725327856 Page 154 of 142


The sorting does not remove the need to access other records as the search looks for particular
records.

Sequential records cannot support modern technologies that require fast access to stored records.
The requirement that all records be of the same size is sometimes difficult to enforce.

Random or direct file organization


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

Advantages of random file access


Quick retrieval of records.
The records can be of different sizes.

Serial file organization


Records in a file are stored and accessed one after another.
The records are not stored in any way on the storage medium this type of organization is mainly
used on magnetic tapes.
Advantages of serial file organization
It is simple
It is cheap

Disadvantages of serial file organization


It is cumbersome to access because you have to access all proceeding records before retrieving the
one being searched.

Wastage of space on medium in form of inter-record gap.


It cannot support modern high speed requirements for quick record access.
Indexed-sequential file organization method
Almost similar to sequential method only that, an index is used to enable the computer to locate
individual records on the storage media. For example, on a magnetic drum, records are stored
sequential on the tracks. However, each record is assigned an index that can be used to access it
directly.

The pile

Data are collected in the order in which they arrive. Each record consists of one burst of data. The
purpose of the pile is simply to accumulate the mass of data and save it. Records may have different
fields, or similar fields in different orders.Thus, each field should self-describing, including a field
name as well as a value.

In choosing a file organization, several criteria are important:

• Short access time


• Ease of update

Michael Bwibo 0725327856 Page 155 of 142


• Economy of storage
• Simple maintenance
• Reliability

File Design
Creating a file and output some data
In order to create files we have to learn about File I/O i.e. how to write data into a file and how to
read data from a file. We will start this section with an example of writing data to a file. We begin as
before with the include statement for stdio.h, and then define some variables for use in the example
including a rather strange looking new type.
/* Program to create a file and write some data the file */
#include <stdio.h>
main( )
{
FILE *fp;
char stuff[25];
int index;
fp = fopen("TENLINES.TXT","w"); /* open for writing */
strcpy(stuff,"This is an example line.");
for (index = 1; index <= 10; index++)
fprintf(fp,"%s Line number %d\n", stuff, index);
fclose(fp); /* close the file before ending program */
}

The type FILE is used for a file variable and is defined in the stdio.h file. It is used to define a file
pointer for use in file operations. Before we can write to a file, we must open it. What this really
means is that we must tell the system that we want to write to a file and what the file name is. We do
this with the fopen() function illustrated in the first line of the program. The file pointer, fp in our
case, points to the file and two arguments are required in the parentheses, the file name first,
followed by the file type.

The file name is any valid DOS file name, and can be expressed in upper or lower case letters, or
even mixed if you so desire. It is enclosed in double quotes. For this example we have chosen the
name TENLINES.TXT. This file should not exist on your disk at this time. If you have a file with
this name, you should change its name or move it because when we execute this program, its
contents will be erased. If you don’t have a file by this name, that is good because we will create
one and put some data into it. You are permitted to include a directory with the file name. The
directory must, of course, be a valid directory otherwise an error will occur. Also, because of the way
C handles literal strings, the directory separation character ‘\’ must be written twice. For
example, if the file is to be stored in the \PROJECTS sub directory then the file name should be
entered as “\\PROJECTS\\TENLINES.TXT”. The second parameter is the file attribute and can
be any of three letters, r, w, or a, and must be lower case.

File handling operations


1) Reading (r)

Michael Bwibo 0725327856 Page 156 of 142


When an r is used, the file is opened for reading; a w is used to indicate a file to be used for writing,
and indicates that you desire to append additional data to the data already in an existing file. Most C
compilers have other file attributes available; check your Reference Manual for details. Using the r
indicates that the file is assumed to be a text file. Opening a file for reading requires that the file
already exist. If it does not exist, the file pointer will be set to NULL and can be checked by the
program.
Here is a program that reads a file and displays its contents on screen.
/* Program to display the contents of a file on screen */
#include <stdio.h>
void main()
{
FILE *fopen(), *fp;
int c;
fp = fopen("prog.c","r");
c = getc(fp) ;
while (c!= EOF)
{
putchar(c);
c = getc(fp);
}
fclose(fp);
}
2) Writing (w).
When a file is opened for writing, it will be created if it does not already exist and it will be reset if it
does, resulting in the deletion of any data already there. Using the w indicates that the file is assumed
to be a text file.
Here is the program to create a file and write some data into the file.
#include <stdio.h>
int main()
{
FILE *fp;
file = fopen("file.txt","w");
/*Create a file and add text*/
fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/
fclose(fp); /*done!*/
return 0;
}
3) Appending (a).
When a file is opened for appending, it will be created if it does not already exist and it will be
initially empty. If it does exist, the data input point will be positioned at the end of the present data
so that any new data will be added to any data that already exists in the file. Using the a indicates that
the file is assumed to be a text file.
Here is a program that will add text to a file which already exists and there is some text in the file.
#include <stdio.h>
int main()
{
FILE *fp
file = fopen("file.txt","a");

Michael Bwibo 0725327856 Page 157 of 142


fprintf(fp,"%s","This is just an example :)"); /*append some text*/
fclose(fp);
return 0;
}
4) Outputting to the file
The job of actually outputting to the file is nearly identical to the outputting we have already done to
the standard output device. The only real differences are the new function names and the addition of
the file pointer as one of the function arguments. In the example program, fprintf replaces our
familiar printf function name, and the file pointer defined earlier is the first argument within the
parentheses. The remainder of the statement looks like, and in fact is identical to, the printf
statement.
5) Closing a file
To close a file you simply use the function fclose with the file pointer in the parentheses. Actually, in
this simple program, it is not necessary to close the file because the system will close all open files
before returning to DOS, but it is good programming practice for you to close all files in spite of the
fact that they will be closed automatically, because that would act as a reminder to you of what files
are open at the end of each program.

C File management

A File can be used to store a large volume of persistent data. Like many other languages 'C' provides
following file management functions,

1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file

Following are the most important file management functions available in 'C,'

function purpose
fopen () Creating a file or opening an existing file
fclose () Closing a file
fprintf () Writing a block of data to a file
fscanf () Reading a block data from a file
getc () Reads a single character from a file
putc () Writes a single character to a file
getw () Reads an integer from a file
putw () Writing an integer to a file
Sets the position of a file pointer to a specified
fseek ()
location
ftell () Returns the current position of a file pointer

Michael Bwibo 0725327856 Page 158 of 142


rewind () Sets the file pointer at the beginning of a file

Why files are needed?

• When a program is terminated, the entire data is lost. Storing in a file will preserve your data
even if the program terminates.
• If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the
file using few commands in C.
• You can easily move your data from one computer to another without any changes.

STRUCTURES

Introduction

Suppose you want to write a program that keeps tracks of students [Name, Marks] i.e. a variety of
information to be stored about each student. This requires;
An array of strings (for the Names).
Marks in an array of integers.

Keeping track of many related arrays can be problematic, for example in operations such as sorting
all of the arrays using a certain format.

A data form or type containing both the strings and integers and somehow keep the information
separate is required. Such a data type is called a structure.

What Is A Structure?

A structure is an aggregate data type that is composed of two or more related elements. If we are
using C structure then we are combining different related data types in one group so that we can use
and manage those variables easily.

Difference between Structures and Arrays

Unlike arrays, each element of a structure can have its own type, which may differ from the types of
any other elements.

Setting Up A Structure

A template is the master plan describing how a structure is put together.

In our example, we can have the following template;

struct student
{
char name[SIZE];

Michael Bwibo 0725327856 Page 159 of 142


int marks;
};

The above describes a structure made up of a character array name, and int variable marks.

Explanation
The keyword struct announces to the computer that what follows is a structure data type template.
The tag follows: which is a shorthand label that can be used later to refer to this structure. In the
above example, the tag name is student.
A list of structure members enclosed in a pair of braces. Each member is described by its own
declaration. For example; the name portion is a character array of SIZE elements.
Note: Members of a structure can be any data types including other structures.

Example: Bank Account


Account number (integer)
Account type (character)
Account holder name [30]
Account balance (float)

struct Bank_ account


{
int acc_number;
char acc_type;
char holder_name [30];
float balance;
};

Defining A Structure Variable

The structure template doesn’t tell the computer how to represent the data. Having set up the
template we can declare a structure variable as follows;

struct student mystudent;

The computer creates a variable mystudent following the structure template. It allocates space for a
character array of SIZE elements and for an integer variable.

One can declare as many variables of type student as possible. For example,
struct student mystudent, student1, x, y, z; etc.

Note: One can combine the process of defining the structure template and the process of defining a
structure variable as follows;
struct student
{
char name;
int marks;
}mystudent;

Michael Bwibo 0725327856 Page 160 of 142


A general form of a structure can be given as follows;
struct tagname{
type1 element1;
type2 element2;
.
.
typeN elementN;
}variable list;

Initializing A Structure

A structure can be initialized like any other variable - external, static or automatic. This will depend
on where the structure is defined.

Example
static struct student mystudent =
{
“Fred Otieno”,25;
};
Each member is given its own line of initialization and a comma separator, one member
initialization from the next.

Accessing Structure Members

Individual structure members are accessed using a period (.) - structure member operator.

For example mystudent.marks which means the marks portion of struct mystudent.

Note: You can use mystudent.marks exactly the way you use other integer variables.
For example, you can use gets(mystudent.name);

or

scanf(“%d”, &mystudent.marks);

Note: Although mystudent is a structure, mystudent.marks is an int type and is like any other integer
variable. Therefore;

The use of scanf(“%d”.........) requires the address of an integer and that is what &mystudent.marks
does.

If stud1 is another student structure declared as follows;

struct student stud1;, then it is possible to read the name and marks into the variable using the
statements;

gets(stud1.name)

Michael Bwibo 0725327856 Page 161 of 142


scanf(“%d”, &stud1.marks);

Example: A student structure program

#include<stdio.h>
#define SIZE 40
struct student
{
char name[SIZE];
int marks;
};

main()
{
struct student mystudent; /* declare mystudent as a student type */
printf(“Please enter the name of the student \n”);
scanf(“%s”, mystudent.name);
printf(“Enter the marks obtained \n”);
scanf(“%d”, &mystudent.marks);
printf(“%s: got %d “, mystudent.name, mystudent.marks);
system(“pause”);
return 0;
}

Use of Structures

The immediate application that comes to mind is database management. For example, to maintain
data about employees in an organization, books in a library, items in a store, financial transactions in
a company. Their use however, stretches beyond database management. They can be used for a
variety of applications like:
Checking the memory size of the computer.
Hiding a file from a directory
Displaying the directory of a disk.
Interacting with the mouse
Formatting a floppy
Drawing any graphics shape on the screen.

Michael Bwibo 0725327856 Page 162 of 142


Michael Bwibo 0725327856 Page 163 of 142
TOPIC 9 : PROGRAM DOCUMENTATION.

Program documentation

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


description of a program. It shows as to how software is written. Program documentation even has
the capability to sustain any later maintenance or development of the program. The program
documentation describes what exactly a program does by mentioning about the requirements of the
input data and the effect of performing a programming task.

Michael Bwibo 0725327856 Page 164 of 142


USES OF PROGRAM DOCUMENTATION

Server Environments
It is always beneficial to have detailed documentation about an application and its environments.
Having this information readily available is invaluable when setting up new environments for an
application and/or maintaining existing ones for development, testing and production. This
documentation should state all the information desired for each environment to include the
application name/version, server name, IP, actual server location if necessary, directory path for the
code, URL to access the application, operating system, user account information, and a point of
contact.

Troubleshooting
Having documentation also helps when troubleshooting production issues. An FAQ document can
speed resolution for data issues that come up over and over with previously identified solutions or
workarounds. Most technical issues have error codes that can help with troubleshooting but data
errors sometimes need additional clues as to why something may not be working properly. This is
another type of knowledge gained through time working on an application, but having these

Michael Bwibo 0725327856 Page 165 of 142


documented can speed up the troubleshooting process, especially for a new developer working on
an ongoing project.

Application Installation
Installation and configuration documents are useful for when developers need to set up new or
additional application environments. If possible, the steps should be detailed and easy to follow and
can include screenshots if necessary. Anyone should be able to follow the steps and successfully
install an application. Having the steps identified will help the installer prevent problems because of
missing parts of an application. Details such as necessary software, libraries, and application server
versions, can be included to ensure the environment will be compatible and set up as intended.

Code Deployment
Most companies have their own deployment processes when doing releases and code updates and it
is always helpful to have the deployment instructions documented. There should be information
regarding the code repository, where the file updates are found, and where they need to be moved.
In addition, there should be step-by-step instructions on how to create an application package or a
build to be deployed.

All these documents should be readily available to the developers and team members on the project.
These can be placed in a document sharing portal for easy access, access control, and version
control. In order for them to be useful, they should be updated as changes are made or new
enhancements and processes are added to the application. Having all the necessary documents
pertaining to your application will make your development and maintenance efforts more efficient.

Others include
They act as a communication medium between members of the development team in a case where
system re-engineering may be needed.
They are a system information repository to be used by maintenance engineers.
They provide information for management to help them plan, budget and schedule the software
development process.
Some of the documentation should tell users how to use and administer the system.
It describes how to get started and how end-users might make use of the common system facilities.

Types of Documentations

1) User Documentation

Michael Bwibo 0725327856 Page 166 of 142


The user documentation is intended to help the users of the system.

The users are usually non-technical people, who don't need to know how the system works. They
just need to know how to use it.

User documentation usually includes:

• List of minimum hardware and software required to use the system


• How to install the system
• How to start / stop the system
• How to use the features of the system
• Screenshots showing the system in typical use
• Example inputs and outputs
• Explanations of any error messages that might be shown
• A troubleshooting guide

User documentation refers to the documentation for a product or service provided to the end users.
The user documentation is designed to assist end users to use the product or service. This is often
referred to as user assistance. The user documentation is a part of the overall product delivered to
the customer.

Traditionally user documentation was provided as a user guide, instruction manual or online help.
However, user documentation is increasingly being delivered online today. This has enabled
technical writers to be more imaginative in how they assist users.

User documentation is important because it provides a avenue for users to learn:

1. how to use your software


2. features of your software
3. tips and tricks of your software
4. how to resolve common problems with your software

Without user documentation, a user may not know how to do the above things.

Users expect the user documentation to include:

• FAQs
• Video tutorials
• Embedded assistance (for example, tool tips and dynamic page content)
• Support Portals

User manual should address the following:

• Minimum hardware and software requirements

Michael Bwibo 0725327856 Page 167 of 142


• Installation guide
• How to start the system
• How to use different features of the system
• Screenshots explaining main features of the system
• Example inputs and outputs
• Explanations of error messages and troubleshooting guides
• Information to contact the developer of the system if an undocumented question arises

The quality of user documentation can affect the rate of implementation of the new system.
Examples should include methods such as: help files, online support and printed manuals.

Evaluating user documentation

Method Advantages Disadvantages


• you might not get level of detail you
• User friendly
want
• really fast
• the user might not know what to
help files • easy to use
search for
• can be accessed offline
• Might be hard to find

• larger amount of
information • can't be accessed offline
online • easier to update • if you have slow internet connection,
support • can access from any device it's bad.
• can be faster

• slower
• easy to find • if you lose it, you're going to have a
• you can browse through bad day
printed
them • harder to search
manuals
• work without a computer • cannot be updated
• prone to physical destruction

2) Technical Documentation

The technical documentation is intended to help the maintainers of the system (the people who
need to keep the system running smoothly, fix problems, etc.)

The maintainers are usually technical people, who need to know exactly how the system works.

Technical documentation usually includes:

• Details of the hardware and software required for the system

Michael Bwibo 0725327856 Page 168 of 142


• Details of data structures (data types, field names, etc.)
• Details of expected inputs
• Details of validation checks
• Details of how data is processed
• Diagrams showing how data moves through the system
• Flowcharts describing how the system works

Program Documentation
Any written text, illustrations or video that describe a software or program to its users is
called program or software document. User can be anyone from a programmer, system analyst and
administrator to end user. At various stages of development multiple documents may be created for
different users. In fact, software documentation is a critical process in the overall software
development process.

In modular programming documentation becomes even more important because different modules
of the software are developed by different teams. If anyone other than the development team wants
to or needs to understand a module, good and detailed documentation will make the task easier.

These are some guidelines for creating the documents −

• Documentation should be from the point of view of the reader


• Document should be unambiguous
• There should be no repetition
• Industry standards should be used
• Documents should always be updated
• Any outdated document should be phased out after due recording of the phase out

Advantages of Documentation
These are some of the advantages of providing program documentation −

• Keeps track of all parts of a software or program


• Maintenance is easier
• Programmers other than the developer can understand all aspects of software
• Improves overall quality of the software
• Assists in user training
• Ensures knowledge de-centralization, cutting costs and effort if people leave the system
abruptly

Example Documents
A software can have many types of documents associated with it. Some of the important ones
include −

• User manual − It describes instructions and procedures for end users to use the different
features of the software.

Michael Bwibo 0725327856 Page 169 of 142


• Operational manual − It lists and describes all the operations being carried out and their
inter-dependencies.
• Design Document − It gives an overview of the software and describes design elements in
detail. It documents details like data flow diagrams, entity relationship diagrams, etc.
• Requirements Document − It has a list of all the requirements of the system as well as an
analysis of viability of the requirements. It can have user cases, reallife scenarios, etc.
• Technical Documentation − It is a documentation of actual programming components like
algorithms, flowcharts, program codes, functional modules, etc.
• Testing Document − It records test plan, test cases, validation plan, verification plan, test
results, etc. Testing is one phase of software development that needs intensive
documentation.
• List of Known Bugs − Every software has bugs or errors that cannot be removed because
either they were discovered very late or are harmless or will take more effort and time than
necessary to rectify. These bugs are listed with program documentation so that they may be
removed at a later date. Also they help the users, implementers and maintenance people if
the bug is activated.

The four sections of a documentation (documentation checklist).

Identification – This should include the title of the program, short statement of its function, author,
date written, language used and version and the hardware requirements.
General specification – This should include a description of the main actions of the program under
normal circumstances, file specifications, restrictions and/or limitations of the programs and
references to any texts explaining any complex procedures / techniques used in the program.
User information – This should include the format of input required, e.g. source documents, how to
produce outputs and their layout and detailed instructions on how to run the program.
Program specification – This will contain the design of the program using structures charts or
flowcharts, annotated program listing and testing procedure including test data and expected output.

Documentation is produced for:


System developer i.e. who will depend on documentation from previous life cycle stages to guide
continued development and subsequence maintenance of software or system
Management i.e. who will use documentation from past projects to plan and understand current
project.
System users i.e. who will learn how to use software or system from its narrative description or
documentation.

Writing Program Documentation


Good software documentation, whether a specifications document for programmers and testers, a
technical document for internal users, or software manuals and help files for end users, helps the
person working with the software understand its features and functions. Good software
documentation is specific, concise, and relevant, providing all the information important to the
person using the software. Following are instructions on how to write software documentation for
technical users and end users.

Michael Bwibo 0725327856 Page 170 of 142


Writing documentation for your program is one of the best ways you can help your users: the basic
users don't want to have to spend lots of unnecessary time trying to figure out how to use your
program and the hardcore gamers consider a program without documentation to just be distasteful
(some don't even download a program unless it has documentation).
While there are literally an infinite number of things that you can include in program documentation,
you should always at least include the basic essentials about your program. (It is your decision
whether you decide to include any of the extras, but keep in mind that the more detailed your
documentation is the better it will be for the program user.)

Author information
Program description
Calculator requirements
Installation (if necessary)
Instructions
Date released or version number
Files included in zip
Program controls
Troubleshooting
Copyright

Writing Software Documentation for Technical Users


Determine what information needs to be included. Software specification documents serve as
reference manuals for designers of the user interface, programmers who write the code, and testers
who verify that the software works as intended. The exact information depends on the program in
question but may include any of the following:

Key files within the application. This may include files created by the development team, databases
accessed during the program's operation, and third-party utility programs.
Functions and subroutines. This includes an explanation of what each function or subroutine does,
including its range of input values and output values.

Decide how much of the documentation should be within the program code and how much should
be separate from it. The more technical documentation is developed within the program's source
code to begin with, the easier it will be to update and maintain along with the code, as well as to
document various versions of the original application. At a minimum, documentation within the
source code needs to explain the purpose of functions, subroutines, variables, and constants.
If the source code is particularly lengthy, it can be documented in the form of a help file, which can
be indexed or searched with keywords. This is a particular advantage for applications where the
program logic is fragmented over many pages and includes a number of supplemental files, as with
certain Web applications.

Choose the appropriate documentation tool. To some extent, this is determined by the language the
code is written in, be it C++, C#, Visual Basic, Java, or PHP, as specific tools exist for these and
other languages. In other cases, the tool to use is determined by the type of documentation required.
Word-processing programs for Microsoft Word are adequate for creating separate text files of
documentation, as long as the documentation is fairly short and simple. For long, complex text files,
many technical writers prefer a documentation tool such as Adobe FrameMaker.

Michael Bwibo 0725327856 Page 171 of 142


Help files for documenting source code can be produced with any help authoring tool, such as
RoboHelp, Help and Manual, Doc-To-Help, MadCap Flare, or HelpLogix.
Writing Software Documentation for End Users

In no case, however, should software documentation substitute for poor interface design. If an
application screen requires reams of documentation to explain it, better to change the screen design
to something more intuitive.

Understand the audience you're writing the documentation for. In most cases, software users have
little knowledge of computers outside of the tasks the applications they use enable them to do.
There are several ways to determine how to address their needs with your documentation.
Look at the job titles your prospective users hold. A system administrator is likely expert with a
number of software applications, while a data entry clerk is more likely to know only the application
he or she currently uses to enter data.

Look at the users themselves. Although job titles generally indicate what people do, there can be
considerable variation in how certain titles are used within a given organization. By interviewing
prospective users, you can get a feel for whether your impressions of what their job title indicates are
accurate or not.

Look at existing documentation. Documentation for previous versions of software, as well as


functional specifications, provide some indication as to what the user will need to know to use the
program. Keep in mind, however, that end users are not as interested in how the program works as
they are in what it can do for them.
Identify the tasks needed to do the job, and what tasks need to be done before those tasks can be
done.

A user guide format explains how to use the software to perform a particular task. User guides are
often formatted as printed guides or PDFs, although some help files include topics on how to
perform particular tasks. (These help topics are usually not context-sensitive, although they may be
hyperlinked to from topics that are.) User guides often take the form of tutorials, with a summary of
the tasks to be performed in the introduction and instructions given in numbered steps.
Decide what form(s) the documentation should take. Software documentation for end users can take
1 or several of many forms: printed manuals, PDF documents, help files, or online help. Each form
is designed to show the user how to use each of the program's functions, whether in the form of a
walkthrough or a tutorial; in the case of help files and online help, this may include demonstration
videos as well as text and still graphics.

Help files and online help should be indexed and keyword-searchable to allow users to quickly find
the information they're looking for. Although help file authoring tools can generate indexes
automatically, it is often better to create the index manually, using terms users are likely to search
for.

Choose the appropriate documentation tool. Printed or PDF user manuals can be written with a
word-processing program like Word or a sophisticated text editor like FrameMaker, depending on

Michael Bwibo 0725327856 Page 172 of 142


their length and complexity. Help files can be written with a help authoring tool like RoboHelp,
Help and Manual, Doc-To-Help, Flare, HelpLogix, or HelpServer.

TOPIC TEN (10) EMERGING TRENDS IN PROGRAMMING.

Emerging trends in programming.

Programming languages have always been heavily influenced by programming paradigms, which in
turn have been characterized by general computing trends.

• Programming languages have always been heavily influenced by programming paradigms,


which in turn have been characterized by general computing trends. The cumbersomeness of
low-level machine code yielded imperative programming languages. These languages take
advantage of compilers or interpreters in order to generate low-level machine code based on
easier to handle higher-level languages. As a result of increasing complexity and scale of
programs, there was a need for finer granularity and encapsulation of code, which led to new
modularization concepts. This has been later complemented and extended by the object-
oriented paradigm, which introduced new concepts like polymorphism and inheritance. The
object-oriented paradigm promotes the design and implementation of large, but manageable,
software systems and thus addresses the requirements of large-scale applications

• Apart from the object-oriented paradigm, there are several less common paradigms such as
declarative or functional programming that focus on high expressiveness. Programming
languages following these paradigms have been considered as esoteric and academic
languages by the industry for a long time. As functional languages favor immutability and
side-effect free programming, they are by design easier to execute concurrently. They also
adapt other techniques for handling mutable state and explicit concurrency.

• The gap between imperative, object-oriented languages and purely functional languages has
been bridged by another tendency: multi-paradigm programming languages. By
incorporating multiple paradigms, programming languages allow the developer to pick the
right concepts and techniques for their problems, without committing themselves to a single
paradigm. Multi-paradigm languages often provide support for objects, inheritance and
imperative code, but incorporate higher-order functions, closures and restricted mutability at
the same time. Although these languages are not pure in terms of original paradigms, they
propose a pragmatic toolkit for different problems with high expressiveness and manageable
complexity at the same time.

Michael Bwibo 0725327856 Page 173 of 142


• Domain-specific languages allow to specify and express domain objects and idioms as part
of a higher-level language for programming. By providing a higher level of abstraction,
domain-specific languages allow to focus on the application or business domain while
concealing details of the programming language or platform. Several frameworks for web
development can be considered as domain-specific languages for the domain of web
applications.

New Programming Languages Programming

• JavaScript has not just become the lingua franca of the web, but also the most widespread
programming language in general. Every browser, even mobile ones, act as an execution
environment for JavaScript applications, thus JavaScript is available on virtually all
computing devices. But JavaScript is also increasingly popular outside the web browser,
thanks to projects like node.js. Microsoft uses JavaScript as the main programming language
for Metro applications in the upcoming Windows 8 release. JavaScript is a multi-paradigm
language that incorporates prototypal object inheritance combined with many functional
aspects of Scheme.

• Others attempt to transcompile (i.e. executing source-to-source compilation) different


languages to JavaScript. Popular examples therefore are ClojureScript [McG11]
and CoffeeScript. ClojureScript translates Clojure code into JavaScript, though some of the
Clojure features are missing. For instance, JavaScript is single-threaded, so the usage of
concurrency concepts of Clojure is limited. CoffeeScript takes a different route. It is a
language that exclusively transcompiles to JavaScript and has been designed as a syntactic
replacement for JavaScript. CoffeeScript not just adds syntactic sugar, but also provides
some advanced features like array comprehension and pattern matching.

• When Google was dissatisfied with the progress on new JavaScript specifications and was
reasoning about the future of web programming, they identified the need for a general-
purpose web programming language for both clients and servers, independent of JavaScript.
This need was shortly after addressed by Google's new Dart [Tea12] programming language.
Dart is derived from JavaScript, but incorporates several concepts from Java and other
languages. It is class-based, like Java, and supports interfaces, abstract classes and generics.
Dart is dynamically typed, but annotations can be used to enforce static typing. A core
library provides common data structures and operations, and a DOM library supports
HTML5 DOM. For server applications, Dart includes an I/O library with an asynchronous,
non-blocking programming model and an event loop. Dart also ships with an HTTP library
as a foundation for web servers. Concerning concurrency in Dart, the specification disallows
shared-state concurrency.

• Dart and node.js demonstrate the possibility of natively using the same programming
language for client-side and server-side web application development. Some node.js web
framworks already support the usage of the same functions both for browsers and the
server. For example, the same template rendering functions can be used, both for complete
page generation on the server and for partial updates in the browser. Also RPC-like
frameworks have emerged that allow the client-side application to execute remote operations
on the server, entirely using JavaScript.

Michael Bwibo 0725327856 Page 174 of 142


• Other frameworks like the Google Web Toolkit or Vaadin address the desire for a single
programming language by implementing web applications in Java, then generating client-side
code automatically.

• Opa is a dedicated approach which takes this idea one step further. Opa combines a new
OCaml-inspired programming language, a web application framework and a runtime
platform consisting of a web server, a database and a distributed execution engine. All parts
of a web application can thus be implemented entirely in Opa, using a single language and a
single programming model. For deployment, the code is automatically sliced into different
compiled components: JavaScript code for the browser, native code for the platform and
generated database queries/scripts. The Opa language focuses on a strong and static type
system in order to provide security and to prevent traditional web security flaws such as SQL
injections or cross-site scripting. The platform claims to provide a scalable architecture based
on an event-driven, non-blocking concept and messaging mechanisms similar to Erlang.
Opa also supports distribution by using multiple machines.

Challenges Of Emerging Trends In Structured Programming.

• New Takes on Concurrency and Distributed Programming

Concurrent and distributed programming is about to become one of the biggest challenges of our
time to be faced for computing in general. As a result, there is still much ongoing research effort in
finding programming models that tackle concurrency and distribution more naturally. While some
specifically target multi-core concurrency, others address concurrency more generally as an intrinsic
property of distributed computing. We now take a look at some of these concepts and study their
original ideas.

• Consistency and Logical Monotonicity

The idea is to accept eventual consistency whenever possible, but identify locations where the lack
of strong consistency results in unacceptable consistency bugs. Therefore, they introduce the notion
of consistency as logical monotonicity. Based on the theory of relational databases and logic
programming, a program can be defined as monotonic or non-monotonic. A monotonic program
incrementally produces output elements, never revoking them at a later time due to further
procressing. For instance, a projection on a set is a monotonic operation. Instead, non-monotonic
operations require the entire processing to be completed in order to produce outputs. Hence, non-
monotonic operations are blocking operations. Aggregation or negation operations on sets are
examples for non-monotonic operations.

• Distributed computing Concurrency.

Applied to distributed computing, we can also differentiate monotonic and non-monotonic


distributed operations. Monotonic operations do not rely on message ordering and can tolerate
partial delays of messages. Instead, non-monotonic operations require coordination mechanisms
such as sequence numbers or consensus protocols. For instance, everything that involves distributed

Michael Bwibo 0725327856 Page 175 of 142


counting is a non-monotonic operation with the need for coordination and waiting. Hellerstein et al.
further show that monotonic operations guarantee eventual consistency, independent of the order of
messages, while non-monotonic operations require coordination principles in order to assure
consistency. Based on a declarative language, consistency behaviors can be analyzed and non-
monotonic locations can be identified automatically. These locations are so-called points of order,
that need to be made consistent by adding coordination logic.

Distributed Dataflow Programming


Declarative dataflow programming provides a concurrency model with inherent coordination,
entirely hidden from the developer. Massively parallel data-centric computing frameworks such as
MapReduce have shown the strong points of dataflow programming. However, programming
abstractions like MapReduce heavily constrain the expressiveness compared to pure, non-distributed
dataflow languages. Thus, only a small amount of existing algorithms can be applied for
MapReduce-based computations. Combining an expressive programming model including dataflow
concurrency with a scalable and fault-tolerant distributed execution engine represents a sweet spot
for programming in the large.

• Functional Relational Programming

It represents an extreme approach on how to isolate and handle state and it does not resemble any
of the popular programming models. It rejects the notion of coupling state and behavior that
characterizes object-oriented programming. Instead, functional relational programming takes an
entirely declarative route, mainly resting upon relational principles and to minor extend the usage of
side-effect free functional programming constructs. It is still uncertain, whether this model will soon
immerse into mainstream development models for application programming.

Others Challenges of emerging trends in programming.

Cost overruns.

Changing of requirements.

Misunderstanding of requirements.

Poor understanding of goals.

Over-ambitious goals.

Lack of clear specification.

Poor planning/research.

Lack of a reasonable & structured software/feature plan.

No commercial market for end product.

Michael Bwibo 0725327856 Page 176 of 142


Complexity of software.

REFERENCES

1) “The C Programming Language” by Brian W. Kernighan, Dennis M. Ritchie


2) “Programming in ANSI C” by E. Balgurusamy
3) “C Programming: A Modern Approach” by K. N. King
4) Gottfried, Schaums Outline Series, “ Programming With C ”, TMH Publications.

Michael Bwibo 0725327856 Page 177 of 142

You might also like