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

Computer Programming-2

The document provides a comprehensive overview of programming concepts, languages, and methodologies, including various programming paradigms such as imperative, declarative, object-oriented, and functional programming. It outlines the phases of program development, approaches like the Waterfall and Agile models, and details on program design and analysis tools. Additionally, it discusses the characteristics and differences between low-level and high-level programming languages, as well as criteria for selecting a programming language.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Computer Programming-2

The document provides a comprehensive overview of programming concepts, languages, and methodologies, including various programming paradigms such as imperative, declarative, object-oriented, and functional programming. It outlines the phases of program development, approaches like the Waterfall and Agile models, and details on program design and analysis tools. Additionally, it discusses the characteristics and differences between low-level and high-level programming languages, as well as criteria for selecting a programming language.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 109

KENYA COAST NATIONAL

POLYTECHNIC

DEPARTMENT OF COMPUTING AND


INFORMATICS

DEVELOP COMPUTER PROGRAM

P.O. BOX 81220, TEL 041-2226458,


MOMBASA

1
INTRODUCTION TO PROGRAMMING..........................................................5
PROGRAMMING LANGUAGES...................................................................5
Programming Paradigm.........................................................................................10
i. Declarative Programming Languages...............................................................10
ii. Imperative Programming Languages................................................................10
iii. Object-oriented programming (OOP) Languages..............................................11
iv.Functional Programming Languages.................................................................12
Approaches of Program Development....................................................13
Waterfall Model.....................................................................................................13
Agile Model............................................................................................................14
Spiral Model...........................................................................................................16
Criteria for choosing the appropriate methodology..............................................17
Identify Phases of Program development...............................................18
PROCESS OF CREATING PROGRAMS ARE IDENTIFIED............................................18
PHASES OF PROGRAM DEVELOPMENT ARE IDENTIFIED........................................18
Program Development Life Cycle..........................................................................18
PERFORM PROGRAM DESIGN AND ANALYSIS..........................................20
PROGRAM DESIGN TOOLS.....................................................................................21
1. Pseudocode..................................................................................................21
2. Algorithm.....................................................................................................21
3. Flowchart.....................................................................................................22
4. Data Flow Diagrams.....................................................................................24
5. Decision Tables............................................................................................26
6. Entity Relationship Diagrams.......................................................................28
7. HIPO Diagrams.............................................................................................29
8. Structure Charts (module chart, hierarchy chart)........................................30
Software Design Levels.........................................................................................31
Types of System Design........................................................................................32
Factors Affecting Program Design and Analysis....................................................32
3. PROGRAM STRUCTURE....................................................................34

2
Format of a Computer Program.............................................................................34
Source Code Files...............................................................................................34
Step by Step Creation and Execution of a C Program........................................34
Fundamentals of Structured Programming using C Language..............................35
C DATA TYPES.......................................................................................................39
VARIABLES.............................................................................................................42
CONSTANTS...........................................................................................................46
TYPE CASTING.......................................................................................................46
C PROGRAMMING OPERATORS..............................................................................47
ARITHMETIC OPERATORS...................................................................................47
INCREMENT AND DECREMENT OPERATORS – Unary Operators.........................48
ASSIGNMENT OPERATORS – Binary Operators...................................................48
RELATIONAL OPERATORS - Binary Operators.....................................................49
LOGICAL OPERATORS - Binary Operators...........................................................49
CONDITIONAL OPERATOR – Ternary Operators..................................................50
PRECEDENCE OF OPERATORS...............................................................................51
ASSOCIATIVITY OF OPERATORS.............................................................................51
CONTROL STRUCTURES.........................................................................54
IMPORTANCE OF CONTROL STRUCTURES.............................................................54
TYPES OF CONTROL STRUCTURES.........................................................................54
SELECTION STRUCTURES......................................................................................55
(a) THE IF SELECTION STRUCTURE....................................................................55
(b) THE IF/ELSE..................................................................................................56
(c) THE IF...ELSE IF...ELSE STATEMENT.............................................................57
(d) NESTED IF STATEMENTS..............................................................................58
(e) SWITCH STATEMENT....................................................................................59
(f) NESTED SWITCH STATEMENTS..........................................................................61
REPETITION/ITERATIVE/LOOP STRUCTURES..........................................................62
(a) WHILE LOOP IN C.........................................................................................63
(b) FOR LOOP IN C.............................................................................................64

3
(c) DO...WHILE LOOP IN C – Post Test Loop.......................................................66
(d) NESTED LOOPS IN C.....................................................................................68
LOOP CONTROL STATEMENTS...............................................................................70
(a) BREAK STATEMENT......................................................................................70
(b) CONTINUE STATEMENT................................................................................71
THE COMMA OPERATOR in C.................................................................................71
THE INFINITE LOOP................................................................................................72
SUBPROGRAMS IN C..............................................................................73
TYPES OF FUNCTIONS............................................................................................73
LIBRARY FUNCTIONS..........................................................................................73
USER DEFINED FUNCTIONS................................................................................74
DEFINING A FUNCTION..........................................................................................75
FUNCTION DECLARATIONS....................................................................................77
CALLING A FUNCTION............................................................................................77
FUNCTION ARGUMENTS.........................................................................................79
Inbuilt Functions.................................................................................................80
DATA STRUCTURES............................................................................... 83
ARRAYS.................................................................................................................84
CREATING/DECLARING ARRAYS..........................................................................84
INITIALIZING ARRAYS.........................................................................................85
ACCESSING ARRAY ELEMENTS...........................................................................85
Initializing Two-Dimensional Arrays.......................................................................87
Accessing Two-Dimensional Array Elements.........................................................87
SORT TECHNIQUES.............................................................................................88
SEARCHING ARRAYS...........................................................................................96
C STRINGS.............................................................................................................98
POINTERS............................................................................................................102

4
INTRODUCTION TO PROGRAMMING
Programming refers to the process of writing instructions to enable a computer
to perform a specific task.
A programming language is a vocabulary and set of grammatical rules
designed for instructing a computer to perform specific tasks.

PROGRAMMING LANGUAGES
HISTORY OF PROGRAMMING LANGUAGES
Low-Level Programming Languages
First-Generation Programming Languages – Machine Language
These languages were introduced in the 1940s and had the following
characteristics:
 Instructions were entered directly in binary format (1s and 0s) and
therefore they were tedious and error prone. Programmers had to design
their code by hand then transfer it to a computer using a punch card,
punch tape or flicking switches.
 Instructions were executed directly/natively by the CPU and therefore
the programs were very fast.
 Programs were very difficult to edit and debug.
 Used to code simple programs only.
 The programs were lengthy and tiresome to read
 The languages were machine dependent. This is because different
machines (hardware) have different microprocessors used to build them.
These microprocessors use different instruction sets to operate them. The
languages are therefore not portable.
Second-Generation Programming Languages (2GL) –Assembly
Languages
They were introduced to mitigate the error prone and excessively difficult nature
of binary programming.
 Introduced in the 1950s
 They improved on the 1GL by providing human readable source code.
They use English-like abbreviations known as mnemonic codes such
as LDA for load and STA for store for various machine code
instructions. This made programs easier to read, write and maintain.
This code must, however, be assembled into machine code also known
as binary instructions or object code before it can be executed by a CPU.
 They are also specific to System Architecture i.e. 2GL source code is
not portable across processors or processing environments.
To convert assembly code into object code requires an Assembler and each line
of assembly can be replaced by the equivalent line of object (machine) code:

5
Assembly Code Machine Code

LDA A 000100110100
ADD #5 001000000101
-> Assembler ->
STA A 001100110100
010000000011
JMP #3

6
Such languages are sometimes still used for kernels and device drivers, i.e.
the core of the operating system and for specific machine parts. More often, such
languages are used in areas of intense processing, like graphics processing,
where the code needs to be optimized for performance.
Almost every CPU architecture has a companion assembly language. Most
commonly used assembly languages today are Autocoder for IBM mainframe
systems, Linoreum, MACRO -11,etc.
High-Level Programming Languages
Third-Generation Languages (3GL)
Third generation languages are the primary languages today.
 Introduced in the 1950s
 Based on natural language i.e. English-like
 They were designed to be programmer friendly i.e. easy to learn, write,
read and maintain
 Often designed with structured programming in mind
 The increased code reuse
 The languages are architecture independent/portable e.g. C, Java etc.
 Mostly used in general purpose programming
Examples:
Most Modern General Purpose Languages such as C, C++, C#, Java, Basic,
COBOL, Lisp and ML.
Fourth Generation Languages
 These are high-level languages built around database systems i.e. to
create, insert, retrieve and delete data.
 They are generally used in commercial environments.
 They are characterized by higher abstraction and statement power, to
reduce errors and increase development speed by reducing programming
effort and as a result a reduction in the cost of software development.
 A 4GL is designed with a specific purpose in mind. For example
languages to query databases (SQL), languages to make reports (Oracle
Reports) etc.

Fifth Generation Languages


1. Improves on the previous generations by skipping algorithm writing and
instead use constraints/conditions as the basis for program development.
2. They are designed to automate software development. The programmer only
needs to specify what problems need to be solved and only inputs a set
of logical constraints, with no specified algorithm, and the Artificial
Intelligence (AI)-based compiler builds the program based on these
constraints

Examples: Prolog, OPS5, Mercury


Low-Level Languages VS High-Level Languages

7
Low-level languages High-level languages
1. Closer to the hardware - the Closer to human languages -
programmer has more control over easier to learn and understand
the execution of code, memory
management, and system
resources.
2. Generally non-portable Generally portable

3. Runs directly on the processor They need to be compiled or


interpreted
4. Difficult to understand and maintain They are easier to understand
due to similarity with human
language.
5. Programs run very quickly Generally slower

6. They have very small memory They require a lot of computer


footprint resources
7. Difficult to learn Easy to learn

8. Difficult to read, write, and maintain Easier to read, write, and


maintain.
9. Do not support code reuse They enhance code reuse

10. They have low statement power They have more statement
power
11. Generally procedural Designed with structured
programming in mind

8
Compiled Languages VS Interpreted Languages
Compiled Languages
A program written in a compiled language is first translated to machine language
by another program called a compiler and outputs equivalent machine code to
another file (the executable file). The compiler parses/interprets each statement
in the program and outputs an equivalent sequence of machine or assembly
instructions.
Interpreted Languages
A program written in an interpreted language is never translated to machine
language. Instead, the program is interpreted and executed by another program
called an interpreter. E.g. Java, JavaScript, Python etc
Like a compiler, an interpreter parses each statement in the source program, but
instead of translating it to machine language, it simply executes the statement
as soon as it determines its meaning.

Criteria for Selecting a Programming Language


The following criteria can be used for language selection:
 Ease of learning the language
 Programming experience and Language Familiarity
 Whether it is compiled or interpreted.
 The general execution speed of the language
 How secure the language is. Some languages are designed with security in
mind e.g. Java.
 Whether it is proprietary or open source – Cost consideration.
 Whether it is portable across different hardware and operating systems or
not.
 GUI requirements - If a GUI is required then it can take up a lot of time and
code. For example, creating a GUI in C++ will be more complex than
creating a GUI in Visual Basic.

9
 Time available for Project development - High level languages such as
Visual Basic make programming both easier and faster.
 Availability of programming tools e.g. IDEs
 Support community for the program for example Java has one of the
largest online community.

Programming Paradigms
i. Declarative Programming Languages
Declarative programming is a programming paradigm that focuses on describing
what should be done rather than how to do it. Instead of giving explicit step-by-
step instructions, declarative languages allow developers to specify the desired
outcome or behavior, leaving the details of implementation to the compiler or
interpreter.
For instance if you want a dream house of your own, the functional approach
would would say I want a big house, on the beach with a big kitchen and
comfortable.

Here are some well-known declarative programming languages:

a) CSS (Cascading Style Sheets):


CSS is used to define the presentation and styling of HTML elements on a
webpage. It's a declarative language that lets you specify how elements should
look, and the browser applies these styles accordingly.
Eg. body{ margin-top:2%; background-color:cyan; font-family : Garamond,
fantasy}
b) HTML (Hypertext Markup Language):
HTML is used to structure content on the web, specifying the elements, layout,
and hierarchy of a webpage. It's a declarative markup language, where you
describe the structure and content of the page, and the web browser renders it
accordingly.

ii. Imperative Programming Languages


Imperative programming is a programming paradigm that focuses on describing
how a task is to be performed by providing a sequence of steps or commands for
a computer to follow.
For instance if you want a dream house of your own, the functional approach
would would say let us go to Ndiani and buy a beach plot. We then build the
foundation structure of the house, raise all the walls, get the moulding done and
the the interiors. We the build a swimming pool and make the house beautiful etc
Here are some well-known imperative programming languages: C,PHP,Java

iii. Object-oriented programming (OOP) Languages


Object-oriented programming (OOP) is a programming paradigm that revolves
around the concept of "objects. Objects are entities used to represent
programming concepts. Attributes and functionality/behaviour govern the
description of the object.
OOP follows the imperative (how) programming model that uses statements to
actively change the state of the program.
10
OOP promotes the organization of code into modular and reusable structures,
making it easier to model complex systems and collaborate on software
development.

Here are some well-known object-oriented programming languages:C#, Java,


Python
Example of a class
class Employee {
// fields
String name = “John Mutune”;
double salary=150000;

// a method
void pay () {
System.out.println("Pay to the order of " +
name + " $" + salary);
}
}

class AnEmployee {
public static void main(String[] args) {
Employee myObj = new Employee ();
Employee.pay();
}
}

iv. Functional Programming Languages


Functional programming is an approach to software development that uses pure
functions to create maintainable software. In other words, building programs by
applying and composing functions.
Whereas OOP breaks down into objects, attributes and methods, in functional
programming, concepts are based on the usage of functions and varibales and
return of values.

Approaches of Program Development


11
Waterfall Model
Waterfall approach was the first SDLC Model to be used widely in Software
Engineering to ensure success of a project. In "The Waterfall" approach, the
whole process of software development is divided into separate phases. In this
model, the outcome of one phase acts as the input for the next phase
sequentially.
The following illustration is a representation of the different phases of the
Waterfall Model.

The sequential phases in Waterfall model are –


 Software Concept – The software project is concieved and involves the
process of understanding why a system should be and feasibility studies
conducted.
 Requirements Gathering and analysis − All possible requirements of
the system to be developed are captured in this phase and documented in
a requirement specification document.
 System Design − The requirement specifications from first phase are
studied in this phase and the system design is prepared. This system
design helps in specifying hardware and system requirements and helps in
defining the overall system architecture.
 Implementation − With inputs from the system design, the system is first
developed in small programs called units, which are integrated in the next
phase. Each unit is developed and tested for its functionality, which is
referred to as Unit Testing.
 Integration and Testing − All the units developed in the implementation
phase are integrated into a system after testing of each unit. Post
integration the entire system is tested for any faults and failures.

12
 Deployment of system − Once the functional and non-functional testing
is done; the product is deployed in the customer environment or released
into the market.
 Maintenance − There are some issues which come up in the client
environment. To fix those issues, patches are released. Also to enhance the
product some better versions are released. Maintenance is done to deliver
these changes in the customer environment.
All these phases are cascaded to each other in which progress is seen as flowing
steadily downwards (like a waterfall) through the phases. The next phase is
started only after the defined set of goals are achieved for previous phase and it
is signed off, so the name "Waterfall Model".
Those endpoints or goals can't be revisited after their completion.
Advantages
Some of the major advantages of the Waterfall Model are as follows −
 Simple and easy to understand and use
 Easy to manage due to the rigidity of the model. Each phase has specific
deliverables and a review process.
 Phases are processed and completed one at a time.
 Works well for smaller projects where requirements are very well
understood.
 Clearly defined stages.
 Well understood milestones.
 Easy to arrange tasks.
 Process and results are well documented.
Disadvantages
The major disadvantages of the Waterfall Model are as follows −
 It does not allow much reflection or revision. Once an application is in the
testing stage, it is very difficult to go back and change something.
 No working software is produced until late during the life cycle.
 High amounts of risk and uncertainty.
 Not a good model for complex and object-oriented projects.
 Poor model for long and ongoing projects.
 Not suitable for the projects where requirements are at a moderate to high
risk of changing. So, risk and uncertainty is high with this process model.
 It is difficult to measure progress within stages.
 Cannot accommodate changing requirements.
 Adjusting scope during the life cycle can end a project.
 Integration is done as a "big-bang. at the very end, which doesn't allow
identifying any technological or business bottleneck or challenges early.

Agile Model
Agile Method breaks the product into small incremental builds. These builds are
provided in iterations. Each iteration typically lasts from about one to three
weeks.
In Agile, the tasks are divided into time boxes (small time frames) to deliver
specific features for a release.

13
Iterative approach is taken and a working software build is delivered after each
iteration. Each build is incremental in terms of features; the final build holds all
the features required by the customer.
Here is a graphical illustration of the Agile Model

Advantages
i. Is a very realistic approach to software development.
ii. Promotes teamwork and cross training.
iii. Functionality can be developed rapidly and demonstrated.
iv. Resource requirements are minimum.
v. Suitable for fixed or changing requirements
vi. Delivers early partial working solutions.
vii. Good model for environments that change steadily.
viii. Minimal rules, documentation easily employed.
ix. Enables concurrent development and delivery within an overall planned
context.
x. Little or no planning required.
xi. Easy to manage.
xii. Gives flexibility to developers.
Disadvantages
i. Not suitable for handling complex dependencies.
ii. More risk of sustainability, maintainability and extensibility.
iii. An overall plan, an agile leader and agile PM practice is a must without
which it will not work.

14
iv. Strict delivery management dictates the scope, functionality to be
delivered, and adjustments to meet the deadlines.
v. Depends heavily on customer interaction, so if customer is not clear, team
can be driven in the wrong direction.
vi. There is a very high individual dependency, since there is minimum
documentation generated.
vii. Transfer of technology to new team members may be quite challenging
due to lack of documentation.

Spiral Model
This Spiral model is a combination of agile model and the waterfall model with a
very high emphasis on risk analysis. It allows incremental releases of the product
or incremental refinement through each iteration around the spiral.

The spiral model has four phases. A software project repeatedly passes through
these phases in iterations called Spirals.

Determine Objectives

 Define Objectives: Identify and articulate the goals for the current phase or
iteration of the project.
 Establish Constraints: Determine the constraints including budget, time,
and resource limitations.
 Identify Alternatives: Explore various approaches and methods to achieve
the objectives.
 Determine Requirements: Gather and define the requirements that the
system must satisfy in this iteration.

Identify and Resolve Risks

 Risk Identification: Identify potential risks that could impact the project,
including technical, financial, and operational risks.
 Risk Analysis: Assess the identified risks to understand their potential
impact and likelihood.
 Risk Mitigation Strategies: Develop strategies to mitigate or reduce the
impact of the risks.
 Prototype Development: Create prototypes or proofs of concept to validate
assumptions and reduce technical risks.
 Review and Feedback: Obtain feedback from stakeholders on the risks and
mitigation plans, and adjust accordingly.

Development and Tests

 Design and Development: Implement the designs and develop the software
components as per the defined requirements and objectives.
 Unit Testing: Perform unit testing to ensure individual components function
correctly.
 Integration Testing: Integrate the components and perform integration
testing to ensure they work together as expected.
 Validation and Verification: Validate and verify the developed system
against the requirements and objectives.

15
 User Testing: Conduct user acceptance testing to ensure the system meets
user needs and expectations.

Plan the Next Iteration

 Review Current Iteration: Evaluate the outcomes of the current iteration,


including successes and areas for improvement.
 Gather Feedback: Collect feedback from stakeholders and end-users to
inform the next iteration.
 Adjust Objectives: Refine and adjust the objectives based on the feedback
and findings from the current iteration.
 Plan Tasks and Resources: Define the tasks, allocate resources, and
establish timelines for the next iteration.
 Document Planning: Document the detailed plan for the next iteration,
including objectives, tasks, and risk management strategies.

The following illustration is a representation of the Spiral Model, listing the


activities in each phase.

Based on the customer evaluation, the software development process enters the
next iteration and subsequently follows the linear approach to implement the
feedback suggested by the customer. The process of iterations along the spiral
continues throughout the life of the software.

Criteria for choosing the appropriate methodology


1) Project Goals: Consider the goals of the project, the requirements, the
scope, and the timelines. Is the goal to create a new product or to maintain
an existing one? How important is time-to-market or time-to-release? What
is the expected project size?

16
2) Team Size and Expertise: Consider the size of the team, their expertise,
and their familiarity with the methodology. For example, if the team is
small and experienced, an agile methodology may be suitable, whereas a
larger team with less experience may benefit from a more structured
approach such as the Waterfall model.
3) Development Environment: Consider the nature of the development
environment, including the technology stack, tools, and infrastructure.
Certain methodologies may be better suited for specific technologies or
tools, such as DevOps for cloud-native applications.
4) Customer Involvement: Consider the level of involvement of the customer
or end-user in the development process. If the customer is highly involved,
an agile methodology may be better suited to incorporate feedback and
adjust the product accordingly.
5) Flexibility vs. Structure: Consider the level of flexibility required in the
development process. Some methodologies are more rigid and structured,
such as Waterfall, while others are more flexible and adaptable, such as
Agile.
6) Risk Tolerance: Consider the level of risk tolerance for the project. If the
project involves high levels of risk, such as safety-critical systems, a more
structured and rigorous methodology may be appropriate, such as the V-
Model.

17
CHAPTER 2

PHASES OF PROGRAM DEVELOPMENT ARE IDENTIFIED


Program/System design is the process of defining the software structure
(components/modules, interfaces, and data) to satisfy/realize specified user
requirements.
Program development refers to all the activities and processes involved
between the conception of the desired software through to the final
manifestation of the software, in a planned and structured manner.
Program Development Life Cycle
This refers to the stages that form the framework for planning and controlling the
creation of an information system. The SDLC is a methodology that aims at
producing a high quality system that meets or exceeds customer
expectations, reaches completion within time and cost estimates, works
efficiently and is inexpensive to maintain and cost-effective to
implement. The following are the phases of SDLC:

1) Project planning stage: The fundamental process of understanding why


a system should be built and determining how the project team will go
about building it. It involves the following feasibility studies:
a. Technical feasibility study: can the system be built
b. Economic feasibility study: will the system provide business value,
and what are the risks?
c. Organizational feasibility study: if built, will the system be used,
accepted by the users etc.
2) Systems analysis/requirements definition: this phase identifies the
users of the system and what the system will do or is expected to do. It
involves
a. Analysis of the old system
b. Requirements gathering. Various tools for collecting information are
used. These include interviews, questionnaires, observation of the
users of the old system etc.
c. Development of the new system proposal document.
3) Systems design: describes how the system will operate, in terms of
hardware, software, network infrastructure, user interface, forms and
reports that will be used, databases and files that will be needed. Design
phase steps include;
a. Coming up with a design strategy: in-house, outsourced, or
purchased
b. Architecture design – hardware , software, network infrastructure,
and user interface is designed
c. Database and file specification is done
d. Program design: defines the program that needs to be done and
exactly what each module will do.
e. System inputs and outputs are determined

18
4) System Implementation: The real code is written at this stage. The
software design is translated into source code. Tasks are divided into units
or modules and assigned to the various developers.
5) Integration and testing: Brings all the modules together into a special
testing environment. The integrated system then checks for errors and
interoperability.
6) Acceptance, installation and deployment: The final stage of initial
development, where the software is put into use(deployed) and runs actual
business.
7) Maintenance: This is what happens during the rest of the software's life:
changes, correction, additions, and moves to a different computing
platforms etc. This step, perhaps most important of all, goes on seemingly
forever.
The SDLC is a cycle i.e. iterative in that a new requirement might initiate
the whole process again.

TASK:
Janet, a computer programmer intends to create a program using C
programming language. State the program development stage in which
she could:
(i) Create flow charts;
(ii) Determine end-user needs;
(iii) Determine what OS to develop their system for;
(iv) Check whether the program is giving the desired result;
(v) Adjust the program to meet new demands.

19
CHAPTER 3

20
PROGRAM DESIGN TOOLS
1. Pseudocode
Pseudocode is an informal high-level description of the operating
principle of a computer program or other algorithm and is intended for
human reading rather than machine reading. pseudo-code represents
instructions independent of any programming language.
For example, the Pseudocode for comparing two numbers might be written:

Begin
Get first number, A and second number, B
If A is greater than B
Display A is Bigger
Otherwise
Display B is Bigger
Otherwise
They are equal
End

Pseudocode cannot be compiled nor executed, and there are no real formatting
or syntax rules. It is simply one step - an important one - in producing the final
code

Pseudocode to compute the area of a rectangle:


Begin
Get the length, l, and width, w
Multiply l by w to get the area
Display the area
End

2. Algorithm
This refers to a finite sequence of well defined, computer-implementable
instructions designed to solve a problem or to perform a computation.
Algorithms can be expressed in any language including natural languages such
as English. Algorithm means a method/ logic for solving a given problem.
Starting from an initial state and initial input, the instructions describe a
computation that, when executed, proceeds through a finite number of well-
defined successive states, eventually producing output and terminating at a
final ending state.

Pseudocode is successively refined to get the step by step detailed algorithm


that is very close to a computer language.

An algorithm to find the larger of two numbers entered by user.


Step 1: Start
Step 2: Declare variables a and b.
Step 3: Input a and b.
Step 4: If a > b

21
Print “a is the greater”
Else IF b > a
Print “b is the greate”
Else+
Print “They are equal”
End if
Step 5: Stop
Exercise
A student designed a program to accept the age of an employee and then
calculate the employee’s retirement year. If the user keys in a value below 0,
the program should prompt the user for a valid input. Draw a flow chart to
represent the logic above.
Required:
a. Write out the pseudo-code and the algorithm for the program
b. Write the program in both C and Pascal
3. Flowchart
A flowchart is a type of diagram that represents an algorithm or process,
showing the steps as boxes of various kinds, and their order by connecting
them with arrows. This diagrammatic representation illustrates a solution to
a given problem.

Uses of Flowcharts
i. Designing and documenting complex processes or programs.
ii. Like other types of diagrams, they help to visualize and therefore,
understand a process
iii. They also find flaws/errors and bottlenecks in the process.

SYMBOLS USED IN FLOWCHARTS

Different symbols are used for different states in flowcharts. The table below
describes all the symbols that are used in making flowchart

22
Symbol Purpose Description
Used to indicate the flow of logic by
Flowline
connecting symbols.
Terminal(Start/ Used to represent start and end of
Stop) flowchart.

Input/Output Used for input and output operation.

Used for arithmetic operations and


Processing
data-manipulations.
Used to represent the operation in
Decision which there are two alternative
outcomes, true and false.

On-page Connector Used to join different flow lines

Used to connect flowchart portions on


Off-page Connector
different pages.

Annotation/ Used to add comments or clarification


Comment
Shows named process which is defined
elsewhere.
Predefined This means the flowchart for the
Process/Function predefined process has to be already
drawn, and you should reference the
flowchart for more information.

Database Open or save data to a database

Document Open or save a document

23
Draw flowchart to find the largest among three different numbers
entered by user.

Or a flowchart to ask for a number from user and multiply with another number
and print result as follows:

Examples of flowcharts include Activity diagram, Data flow diagram and


sequence diagrams etc.
Exercise 1
Draw a flow chart to represent the program described in exercise 2 above.
4. Data Flow Diagrams
Data flow diagram is graphical representation of the flow of data in an
information system. It is capable of depicting incoming data, outgoing data and
stored data.
While a flowchart depicts the flow of control in a process, a DFD depicts the
flow of data in the system.
24
DFD Principles
The general principle in Data Flow Diagramming is
that a system can be decomposed into subsystems,
and subsystems can be decomposed into lower level
subsystems, and so on.
Each subsystem represents a process or activity in
which data is processed. At the lowest level,
processes can no longer be decomposed.
Each 'process' (and from now on, by 'process' we mean
subsystem and activity) in a DFD has the
characteristics of a system.
Just as a system must have input and output (if it is
not dead), so a process must have input and
output.
Data enters the system from the environment; data
flows between processes within the system; and
data is produced as output from the system
DFD Components
DFD can represent Source, destination, storage and flow of data using the
following set of components.

 External Entities - Entities are sources and destination of data.


 Process – This is a procedure or an action taken on incoming data,
changing it, and producing an output.
 Data Store – They hold data for later use. Data inputs must flow through
a process to a data store, while data outputs flow out of a data store and
then through a process.
 Data Flow - Movement of data is shown by pointed arrows. Data
movement is shown from the base of the arrow as its source towards
head of the arrow as destination.
DFD Levels
DFDs can go from Level 0 upto level 3 with each level showing more detail than
the previous one.

 Level 0 DFD - These provide a broad view that is easily digestible but
conceals all the underlying details. Level 0 DFDs are also known as
context level DFDs.

25
 Level 1 DFD – These are still a general overview, but they go into more
detail than a context diagram. Level 1 DFD depicts basic modules in the
system and flow of data among various modules. Level 1 DFD also
mentions basic processes and sources of information.

5. Decision Tables
Decision tables provide a compact way to represent complex business
logic. It is a tabular representation of the decision making process and in both
testing and requirements management.
Decision tables make it easy to ensure that all possible combinations of
conditions have been considered.
In a decision table, business logic is divided into conditions, actions
(decisions) and rules for representing the various components that form the
business logic. Each column in the table corresponds to a rule in the business
logic that describes the unique combination of circumstances that will result in
the actions.

There is one row for each condition and one vertical column for each
combination of values and resulting actions. Conditions are the factors to
consider when making certain business decisions. Actions are the possible
actions to take when a condition is met or a certain business decision is made.

26
Each vertical column of a decision table is called a rule and each rule
symbolizes the combinations of condition(s) and action(s) that form the
business decision. If constructed properly, the decision table has a rule to cover
every combination. Rules are made of selectors symbolized by Y (Yes), N (No)
and – (for redundant or irrelevant rules).

COMPLETING THE TABLE


 If the number of conditions identified is n, then the number of possible rules
is found by applying the formula; Number of rules = 2n where n is the
number of conditions.
 Entries opposite the lowest condition should be completed first using Y and
N alternately until all the vertical rules have been dealt with.
 Entries opposite the second lowest condition should be completed using Y
and N in pairs until all the vertical rules have been dealt with.
 Entries for the next condition are then completed next using Ys and Ns in
fours.
 This process continues using twice the number of Ys and Ns each time until
all conditions are completed.
 Once entered, the rules are read vertically in each column and an X entered
at the action that appropriately completes that rule. Actions which are
mutually exclusive can be combined on a single line.

EXAMPLE
A student who passes the examinations and completes the coursework and
project satisfactorily is awarded a pass. If the course work and the project are
unsatisfactory, the student is asked to resubmit the unsatisfactory work, as
long as the exams have been passed. A student who fails the examinations is
deemed to have failed the whole course unless both the course work and the
project are satisfactory, in which case the student is allowed to re-sit the
examination.

SOLUTION

27
Before an overall pass
Rules
Exams Passed? Y Y Y Y N N N N
Conditio
ns Completed Course
Y Y N N Y Y N N
work?
Completed Project? Y N Y N Y N Y N
Pass X
Re-sit Exam X
Resubmit
Actions X X
Coursework
Resubmit Project X X
Failed X X X

28
ASSIGNMENT 1
Candidates are accepted for permanent employment if they pass an interview
and their qualifications and referees are satisfactory. If they pass the interview
and the qualifications or referees (but not both) are unsatisfactory, a job for a
probationary period is offered. In all other circumstances, the candidate’s
application is rejected.

Assignment 2
A customer is given a full loan with low interest if he has the required
savings, has a good credit score and his A/C is at least six months old. If he has
a good credit score and the account is at least six months old but doesn’t have
the required saving, then he the loan amount is reduced and is given the full
amount but at a higher interest rate if has poor credit score. If the A/C is less
than six moths old but meets the other two requirements, he is told to try
again later or reduce the amount. In all other circumstances the loan is
denied.

Draw a decision table to represent the logic above.

6. Entity Relationship Diagrams


ERDs are most often used to design or illustrate the logical structure of relational
databases. They use a defined set of symbols such as rectangles and connecting
lines to depict the interconnectedness of entities, relationships and their
attributes.
Key components of an Entity-Relationship Diagram include:
1. Entities: These represent the main objects or concepts in the database.
Entities are typically depicted as rectangles or squares and are labeled with
their names (e.g., "Customer," "Product," "Order"). Each entity corresponds
to a table in the database.
2. Attributes: Attributes are the properties or characteristics of entities. For
example, a "Customer" entity might have attributes like "CustomerID,"
"FirstName," "LastName," and "Email."
3. Relationships: Relationships define how entities are related to each other
within the database.
4. Cardinality: Cardinality describes the number of instances of one entity that
can be related to the number of instances of another entity through a
relationship. Common cardinality notations include "one-to-one" (1:1), "one-
to-many" (1:N), and "many-to-many" (M:N). These notations help specify
how data is structured and related in the database.

29
7. HIPO Diagrams
HIPO diagrams, also known as a "Hierarchy Input-Process-Output" diagram,
represents the hierarchy of modules in the software system. It is a combination
of Hierarchy diagram and an IPO (Input Process Output) Chart.
Analysts use HIPO diagrams in order to obtain high-level view of system
functions. It decomposes functions into sub-functions in a hierarchical manner.
It depicts the functions performed by the system.
Using the HIPO technique, designers can evaluate and refine a program’s design,
and correct flaws prior to implementation.

A HIPO diagram depicts the hierarchical structure of a system's


components, along with their inputs, processes, and outputs.
The key components of a HIPO diagram include:
1. Hierarchy: The diagram starts with a top-level box representing the
main function or process of the system. This box is then divided into sub-
functions or subprocesses, forming a hierarchical structure that breaks
down the system's functionality into manageable units.

30
2. Input-Process-Output: Each box in the hierarchy is accompanied by
three smaller boxes, usually arranged horizontally or vertically. These
smaller boxes represent the inputs, processes, and outputs associated
with the corresponding function or process. The "Input" box represents
the data or information required by the process, the "Process" box
represents the actions or operations performed on the inputs, and the
"Output" box represents the resulting data or outcomes.
3. Connections: Arrows or lines connect the input, process, and output
boxes to show the flow of data or information within the system. Arrows
typically indicate the direction of flow from inputs to processes and from
processes to outputs
With HIPO, you focus on the processes and how they relate to one another
to form a complete application. For example, you can have this HIPO
diagram:

And one of these processes is authentication, which would use this IPO diagram:

Here you see the input move from input into the process and generating output.

8. Structure Charts (module chart, hierarchy chart)


A structure chart is a graphic depiction of the decomposition of a
program. A structure chart is a hierarchical chart that is used to break down a
problem/process into more detail. e.g. “Sign In” might be a top layer process, 2nd
layer process might be “Enter Details” & “Validate Details”, 3rd layer for “Enter
Details” might be “Enter User ID” “Enter Password”

31
The top of the chart is a box representing the entire problem, the bottom of the
chart shows a number of boxes representing the less complicated sub-
problems (e.g. Phone Bill System).

Each block represents some function in the system, and thus should contain a
verb phrase, e.g. "Print report."

EXERCISE
Draw a structure chart for an electricity billing system.

Software Design Levels


The commonly recognized levels of software design include:
1. High-Level Design
High-level design focuses on defining the overall structure and architecture of
the software system. It identifies major components, modules, and their
interactions. HLD addresses issues like data flow, control flow, and system-wide
decisions. At this level, the focus is on creating a conceptual design that
provides a big picture of the system's organization and functionality.
2. Detailed System Design:
Detailed system design digs deeper into the specifics of individual components,
modules, and interactions within the system. It involves defining how each
module will fulfill its responsibilities, how data will flow between them, and
what interfaces they will expose. This type of design focuses on data
structures, algorithms, and specific functions within each module.

Types of System Design


1. Interface Design:
32
Interface design is a critical aspect of software design that focuses on defining
the interactions and communication between different components or modules.
It includes designing APIs (Application Programming Interfaces) that outline
how different parts of the software can interact with each other, ensuring that
these interactions are well-defined and consistent.
2. Database Design
For software systems that involve data storage, database design is crucial. It
involves defining the structure of the database, including tables, relationships,
constraints, and indexes. Effective database design ensures efficient data
storage, retrieval, and manipulation while maintaining data integrity.
3. User Interface (UI)/Form Design
UI design focuses on designing the user interface elements of the software,
such as screens, forms, buttons, and menus. It includes considerations of
usability, user experience (UX), visual aesthetics, and ensuring that the
interface aligns with user needs and expectations.
4. Algorithm Design:
Algorithm design involves creating efficient and effective algorithms to solve
specific problems within the software. This includes selecting appropriate data
structures, determining the sequence of steps, and optimizing for performance
and resource utilization.
5. Security Design:
Security design addresses the protection of the software system against
various security threats and vulnerabilities. It involves designing mechanisms
for authentication, authorization, encryption, and other security measures to
ensure the system's data and functionality are adequately safeguarded.
6. Network Design
Network design is relevant for systems that involve communication between
multiple components or systems. It includes planning the network topology,
protocols, security measures, and data transfer mechanisms to ensure efficient
and secure communication.

Factors Affecting Program Design and Analysis


1) Purpose and Goals: The purpose and goals of the program will
influence its design and analysis. For instance, a program that aims to
process large amounts of data will have different design considerations
than a program that aims to perform complex calculations.
2) User Requirements: The user requirements of the program, such as
the user interface, input/output formats, and performance expectations,
will also influence its design and analysis.
3) Hardware and Software Constraints: The hardware and software
constraints of the target platform where the program will run, such as
memory limitations, processor speed, and operating system
compatibility, will influence the program design and analysis.

33
4) Availability of Resources: The availability of resources, such as time,
budget, and personnel, will also affect program design and analysis.
Limited resources may require compromises in the design and analysis of
the program.
5) Security and Privacy Requirements: If the program deals with
sensitive information or critical systems, security and privacy
requirements will influence the program design and analysis. Special
measures may be necessary to ensure the program's security and
prevent data breaches or cyber attacks.
6) Scalability and Maintainability: The scalability and maintainability of
the program will also impact its design and analysis. A program that is
expected to grow or change over time will require a more flexible and
modular design than a program that has a fixed set of requirements.
Additionally, the ease of maintaining and updating the program will affect
its long-term viability.
7) Programming Language and Tools: The programming language and
tools available for the program will also influence its design and analysis.
Some programming languages are better suited for certain tasks, and
some tools can make the development process more efficient or provide
additional features that can enhance the program's functionality.

34
CHAPTER 3

3.PROGRAM STRUCTURE
Format of a Computer Program
Source Code Files
When you write a program in C language, your instructions form the source
code/file. C files have an extension .c. The part of the name after the period is
called the extension.

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

 A program that translates from a low level language to a higher level one is
a decompiler.

 A program that translates between high-level languages is called a source-


to-source compiler or transpiler.
Step by Step Creation and Execution of a C Program
Step1: Creating and editing the program
i. Write C program using a text editor
ii. Save program using .c extension i.e. the Source Code
Step 2: Preprocessing
iii. File Inclusion: The pre-processor handles file inclusion using the #include
directive. It inserts the contents of the included file at the specified
location. The preprocessor replaces the directives
iv. It also strips away the comments and white space.
v. Macro Expansion: The pre-processor replaces macro definitions with their
corresponding values and code snippets before the actual compilation
takes place. Macros are defined using the #define directive.

Step 3: Compiling
vi. The source code is converted into machine equivalent instruction to
produce the intermediate object code
vii. The compiler checks for errors. If the source code is error free, the source
code is converted to object code. If there are errors, the compiler will
report them.

Step 4: Linking

35
Linking is the process where the object code modules generated by the
compiler together with the start up code and the code for library routines used
in the program (all in machine language) are combined into a single file to
generate the executable file.
Library Linking: The linker can link in static libraries (.a or .lib files) or
dynamic/shared libraries (.so or .dll files) to provide the necessary
dependencies for the program. Static libraries are linked directly into the
executable, while dynamic libraries are linked at runtime.
The linker also checks for errors and reports them.

Fundamentals of Structured Programming using C


Language
The C programming language was designed by Dennis Ritchie as a systems
programming language for Unix.

A C program basically has the following structure:


 Preprocessor Commands/directive
 Functions

36
 Variable declarations
 Statements & Expressions
 Comments

Example:
#include <stdio.h>
int main()
{
/*My first program*/
printf("Hello, World! \n");

return 0;
}

int max( )
{

}
Preprocessor Commands/Directives
These commands tell the compiler to do preprocessing before doing actual
compilation. Like #include <stdio.h> is a preprocessor command which tells
a C compiler to include stdio.h file before going to actual compilation. The
standard input and output header file (stdio.h) allows the program to interact
with the screen, keyboard and file system of the computer.

NB/ Preprocessor directives are not actually part of the C language, but rather
instructions from you to the compiler.
NB/ A header files is simply a listing of the functions that are defined in a
source file e.g. stdio.c , and we simply list the function prototypes, not the
function definitions themselves.

Functions
These are main building blocks of any C Program. Every C Program will have
one or more functions and there is one mandatory function which is called
main() function. When this function is prefixed with keyword int, it means this
function returns an integer value when it exits. This integer value is retuned
using return statement.
The C Programming language provides a set of built-in functions. In the above
example printf() is a C built-in function which is used to print anything on the
screen.
A function is a group of statements that together perform a task. A C
program can be divided up into separate functions but logically the division
usually is so each function performs a specific task. A function declaration tells
the compiler about a function's name, return type, and parameters. A function
definition provides the actual body of the function.
The general form of a function definition in C programming language is as
follows:
37
return_type function_name( parameter list)
{
body of the function/Function definition
}

Variable Declarations
In C, all variables must be declared before they are used. Thus, C is a strongly
typed programming language. Variable declaration ensures that appropriate
memory space is reserved for the variables. Variables are used to hold
numbers, strings and complex data for manipulation e.g.
int x;
int num; int z;
int num,z;

Static vs. dynamic typing


C uses static typing, because in dynamic typing type-checking happens at
runtime. That would mean a line like i = 4 + “string”; would be possible, which
is not true. In statically typed languages type checking is done at compile time.

Statements & Expressions


Expressions combine variables and constants to create new values e.g.
x + y;

Statements in C are expressions, assignment statements (copy


assignment), function calls, or control flow statements which make up C
programs.
Copy assignment is named such because it copies the value on the right-hand
side of the = operator to the variable on the left-hand side.

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 an
expression on the right.
z = x + y;

Comments
These are non-executable program statements meant to enhance
program readability and allow easier program maintenance- they
document the program (internal program documentation). They are
ignored by the compiler. These are used to give additional useful
information inside a C Program. All the comments will be put inside /*...*/ or //
for single line comments also known as end-of-line comments as given in
the example above. A comment can span through multiple lines and are known
as block comments.
/* Author: Mzee Moja */

or

38
/*
Author: Mzee Moja
Purpose: To show a comment that spans multiple lines.
Language: C
*/

or
Fruit = apples + oranges; // get the total fruit

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.

They include:
\a Alert/bell
\b Backspace
\n New line
\t Horizontal tab
\v Vertical tab
\\ Back slash
\” Double quote
\0 Null

Note the following

 A C identifier is a name used to identify a variable, function, or any


other user-defined item. An identifier starts with a letter A to Z or a to z
or an underscore _ followed by zero or more letters, underscores, and
digits (0 to 9). C does not allow punctuation characters such as @, $, and
% within identifiers.
 A keyword is a reserved word in C. Reserved words may not be used
as constants or variables or any other identifier names

Characteristics of C Language

1. C is a case sensitive programming language. It means in C printf and


Printf will have different meanings.
2. C is a strongly typed language i.e. variables must be declared before
they are used.
3. End of each C statement must be terminated with a semicolon.

39
4. C is a free-form language as the C compiler chooses to ignore
whitespaces. Spaces in the code, tabs or newlines are called white
space. Whitespaces are allowed in any format to improve readability of
the code.
Statements in C can be written from any position. Unlike in Python where
tab sapces are used to block code statements
5. C is a modular language: we can split the C program into a number of
modules instead of repeating the same logic statements (sequentially). It
allows reusability of modules.
6. General purpose programming language: C can be used to
implement any kind of applications such as math’s oriented, graphics,
business oriented applications and system software.
7. C is highly Portable: we can compile or execute C programs in any
operating system (UNIX, dos, windows).
8. C is a high level language

SAMPLE PROGRAM
//First program
#include<stdio.h>
main()
{
int num; // Declaration

num =1; // Assignment statement


printf(" My favorite number is %d because", num);
printf(" it is first.\n");
return 0;
}
The program will output (print on screen) the statement “My favorite number
is 1 because it is first”.
The %d instructs the computer where and in what form to print the value. %d is
a type specifier used to specify the output format for integer numbers.

List of Keywords (Reserved Words)


The following list shows the reserved words in C. These reserved words may
not be used as constants or variables or any other identifier names.

40
auto else Long switch
break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _packed
double

C DATA TYPES
In the C programming language, data types refer to a system used for
declaring variables or functions of different types. A data type is, therefore,
a data storage format that can contain a specific type or range of
values. The type of a variable determines how much space it occupies in
storage and how the bit pattern stored is interpreted.

The basic data types in C are as follows:


Type Description
Char Character data and is used to hold a single character. A
character can be a letter, number, space, punctuation mark, or
symbol - 1 byte long
Int A signed whole number in the range -2147483648 to
2147483647. - 2 to 4 bytes long
Float A real number (that is, a number that can contain a fractional
part) – 4 bytes. A float has a 7 decimal digits of precision
Double A double-precision floating point value. Has more digits to the
right of the decimal point than a float – 8 bytes. A double has a
15 decimal digits of precision
Void Represents the absence of type. i.e. represents “no data”

41
USING C’S DATA TYPE MODIFIERS
The five basic types (int, float, char,double and void) can be modified to your
specific need using the following specifiers.
 Signed
Signed Data Modifier implies that the data type variable can store
positive values as well as negative values.
The use of the modifier with integers is redundant because the default
integer declaration assumes a signed number. The signed modifier is
used with char to create a small signed integer. Specified as signed, a
char can hold numbers in the range -128 to 127.
 Unsigned
If we need to change the data type so that it can only store positive
values, “unsigned” data modifier is used.
This can be applied to char and int. When char is unsigned, it can hold
positive numbers in the range 0 to 255.
 Long
Sometimes while coding a program, we need to increase the Storage
Capacity of a variable so that it can store values higher than its
maximum limit which is there as default.
This can be applied to both int and double. When applied to int, it
doubles its length, in bits, of the base type that it modifies. For example,
an integer is usually 16 bits long. Therefore a long int is 32 bits in
length. When long is applied to a double, it roughly doubles the
precision.
 Short
A “short” type modifier does just the opposite of “long”. If one is not
expecting to see high range values in a program.
For example, if we need to store the “age” of a student in a variable, we
will make use of this type qualifier as we are aware that this value is not
going to be very high

The type modifier precedes the type name. For example this declares a long
integer.

short int age;

Integer Types
Following table gives you details about standard integer types with its storage
sizes and value ranges:

42
SIZE
(IN
BYTES FORMAT
DATA TYPE ) RANGE SPECIFIER

-2147483648 to
int 4 2147483647 %d

unsigned int 4 0 to 4294967295 %u

short 2 -32768 to 32767 %hd

unsigned
short 2 0 to 65535 %hu

-9223372036854775808
to
long 8 9223372036854775807 %ld

0 to
unsigned long 8 18446744073709551615 %lu

-9223372036854775808
to
long long 8 9223372036854775807 %lld

unsigned long 0 to
long 8 18446744073709551615 %llu

Floating-Point Types
Following table gives you details about standard floating-point types with
storage sizes and value ranges and their precision:
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 7 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 19 decimal places
1.1E+4932

43
The void Type
The void type specifies that no value is available. It is used in three kinds of
situations:

Types and Description


1 Function returns as void. There are various functions in C
which do not return value or you can say they return void. A
function with no return value has the return type as void. For
example, void exit (int status);
2 Function arguments as void. There are various functions in C
which do not accept any parameter. A function with no
parameter can accept as a void. For example, int rand(void);
3 Pointers to void A pointer of type void * represents the
address of an object, but not its type. For example, a memory
allocation function void *malloc( size_t size ); returns a
pointer to void which can be casted to any data type.

44
VARIABLES
A variable is a memory location whose value can change during program
execution. In C a variable must be declared before it can be used i.e. C is
strongly typed.

Variable Declaration
Declaring a variable tells the compiler to reserve space in memory for that
particular variable. A variable definition specifies a data type and the
variable name and contains a list of one or more variables of that type.
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;
int i, j, k;
char c, ch;
float f, salary;

Variables can be initialized when they are declared. This is done by adding an
equals sign and the required value after the declaration.
REP: When a variable is defined, you can also provide an initial value for the
variable at the same time. This is called initialization.

Int high = 250; /*Maximum Temperature*/


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

TYPES OF VARIABLES
The Programming language C has two main variable types
 Local Variables
 Global Variables

Local Variables
A local variable is a variable that is declared inside a function.
 Local variables scope is confined within the block or function where it is
defined. Local variables must always be defined at the top of a block.
 When execution of the block/module starts the variable is available, and
when the block ends the variable 'dies'. This is referred to as the lifespan
of a variable.

Global Variables
A global variable is defined at the top of the program file and it can be visible
and modified by any function that may reference it. Global variables are
declared outside all functions.

Sample Program.

45
#include <stdio.h>
int area; //global variable

int main ()
{
int a, b; //local variable

/* actual initialization */
a = 10;
b = 20;

printf("\t Side a is %d cm and side b is %d cm long\n",a,b);

area = a*b;
printf("\t The area of your rectangle is : %d \n", area);

return 0;
}

Variable Names
Every variable has a name and a value. The name identifies the variable and
the value stores data.
1. Every variable name in C must start with a letter; the rest of the name
can consist of letters, numbers and underscore characters.
2. C is case sensitive i.e. it recognizes upper and lower case characters as
being different.
3. You cannot use any of C’s keywords like main, while, switch etc as
variable names.
4. A variable name cannot contain a space.
5. Variables must be unique in the same scoping eg in the same function

Examples of legal variable names:

X result outfile x1 out_file etc


It is conventional in C not to use capital letters in variable names. These are
used for names of constants.

Declaration vs Definition

46
A declaration provides basic attributes of a symbol: its type and its name.
A definition provides all of the details of that symbol--if it's a function,
what it does; if it's a class, what fields and methods it has; if it's a variable,
where that variable is stored. Often, the compiler only needs to have a
declaration for something in order to compile a file into an object file, expecting
that the linker can find the definition from another file. If no source file ever
defines a symbol, but it is declared, you will get errors at link time complaining
about undefined symbols. In the following short code, the definition of variable
x means that the storage for the variable is that it is a global variable.

int x;
int main()
{
x = 3;
}

Inputting Numbers From The Keyboard Using Scanf()


Variables can also be initialized during program execution (run time). The
scanf() function is used to read values from the keyboard. For example, to
read an integer value use the following general form:
scanf(“%d”, &var_name)
As in
scanf(“%d”, &num)

The %d is a format/type specifier which tells the compiler that the next
argument will be receiving an integer value.
The & preceding the variable name means “address of”. The function allows
the function to place a value into one of its arguments.
The table below shows format specifiers or codes used in the scanf() function
and their meaning.

%c Read a single character


%d Read an integer
%f Read a floating point number
%lf Read a double
%s Read a string
%u Read a an unsigned integer
%ld Read a long integer
%i Read a short integer

47
When used in a printf() function, a type specifier informs the function that a
different type item is being displayed.

SAMPLE PROGRAM USING SCANF()


#include <stdio.h>
int area; //global variable

int main ()
{
int a, b; //local variables

/* actual initialization */
printf("Enter the value of side a: ");
scanf("%d", &a);

printf("Enter the value of side b: ");


scanf("%d", &b);
printf("\n\t You have entered %d for side a and %d for side b\n", a, b);

area = a*b;
printf("\t The area of your rectangle is : %d \n", area);

return 0;
}

CONSTANTS
C allows you to declare constants. When you declare a constant it is a bit like a
variable declaration except the value cannot be changed during program
execution.
The const keyword is used to declare a constant, as shown below:
int const A = 1;
const int A = 5;
const char name= ‘c’;

These fixed values are also called literals.


Constants can be of any of the basic data types like an integer constant, a
floating constant, a character constant, or a string literal. There are also
enumeration constants as well.
The constants are treated just like regular variables except that their values
cannot be modified after their definition.

48
TYPE CASTING
Type casting is a way to convert a variable from one data type to another. For
example, if you want to store a long value into a simple integer then you can
type cast long to int. You can convert values from one type to another explicitly
using the cast operator as follows:

(type_name) expression

Consider the following example where the cast operator causes the division of
one integer variable by another to be performed as a floating-point operation:

#include <stdio.h>

main()
{
int sum = 17, count = 5;
double mean;

mean = (double) sum / count;


printf("Value of mean is %lf \n", mean );

When the above code is compiled and executed, it produces the following
result:

Value of mean: 3.400000

It should be noted here that the cast operator has precedence over division, so
the value of sum is first converted to type double and finally it gets divided by
count yielding a double value.

Type conversions can be implicit which is performed by the compiler


automatically, or it can be specified explicitly through the use of the cast
operator. It is considered good programming practice to use the cast operator
whenever type conversions are necessary.

C PROGRAMMING OPERATORS
An operator is a symbol which operates on a value or a variable (operand). For
example: + is an operator to perform addition.

C programming language has a wide range of operators to perform various


operations. For better understanding of operators, these operators can be
classified as:

OPERATORS IN C PROGRAMMING
49
1. Arithmetic Operators
2. Increment and Decrement Operators
3. Assignment Operators
4. Relational Operators
5. Logical Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators

ARITHMETIC OPERATORS
Assume variable A holds 10 and variable B holds 20 then
Operator Description Example
+ Adds two operands A + B will give
30
- Subtracts second operand from the A - B will give -
first 10
* Multiplies both operands A * B will give
200
/ Divides numerator by de- B / A will give 2
numerator
% Modulus Operator - remainder of B % A will give
an integer division 0
Note: % operator can only be used
with integers.

50
INCREMENT AND DECREMENT OPERATORS – Unary
Operators
In C, ++ and -- are called increment and decrement operators respectively.
Both of these operators are unary operators, i.e, used on single operand. ++
adds 1 to operand and -- subtracts 1 to operand respectively. For example:

Let a=5
a++; //a becomes 6
a--; //a becomes 5
++a; //a becomes 6
--a; //a becomes 5

Difference between ++ and -- operator as postfix


and prefix
When ++ is used as prefix(like: ++var), ++var will increment the value of var
and then return it but, if ++ is used as postfix(like: var++), operator will return
the value of operand first and then increment it. This can be demonstrated by
an example:

#include <stdio.h>
int main(){
int c=2;
printf("%d\n",c++); /*this statement displays 2 then, only c
incremented by 1 to 3.*/
printf("%d",++c); /*this statement increments 1 to c then, only
c is displayed.*/
return 0;
}

Output
2
4

ASSIGNMENT OPERATORS – Binary Operators

The most common assignment operator is =. This operator assigns the value in
the right side to the left side. For example:

var=5 //5 is assigned to var


a=c; //value of c is assigned to a
5=c; // Error! 5 is a constant.

51
Operator Example Same as
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
NB/ += means Add and Assign etc.

RELATIONAL OPERATORS - Binary Operators


Relational operators check relationship between two operands. If the relation is
true, it returns value 1 and if the relation is false, it returns value 0. For
example:

a>b

Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then,
it returns 0.

Relational operators are used in decision making and loops in C programming.

Operator Meaning of Operator Example


== Equal to 5= =3 returns false (0)
> Greater than 5>3 returns true (1)
< Less than 5<3 returns false (0)
!= Not equal to 5!=3 returns true(1)
>= Greater than or equal to 5>=3 returns true (1)
<= Less than or equal to 5<=3 return false (0)

LOGICAL OPERATORS - Binary Operators


Logical operators are used to combine expressions containing
relational operators. In C, there are 3 logic\al operators:

Operat Meaning of
Example
or Operator
If c=5 and d=2 then,((c= =5) &&
&& Logical AND
(d>5)) returns false.
If c=5 and d=2 then, ((c=
|| Logical OR
=5) || (d>5)) returns true.
! Logical NOT If c=5 then, !(c= =5) returns false.

52
The following table shows the result of operator && evaluating the
expression a&&b:

&& OPERATOR
(and)
a b a && b
true true true
true false false
false true false
false false false

The operator || corresponds to the Boolean logical operation OR, which


yields true if either of its operands is true, thus being false only when both
operands are false. Here are the possible results of a || b:

|| OPERATOR
(or)
a ||
a b
b
true true true
fals
true true
e
fals
true true
e
fals fals
false
e e

53
Explanation

For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be
true but, (d>5) is false in the given example. So, the expression is false. For
expression ((c==5) || (d>5)) to be true, either the expression should be true.

Since, (c==5) is true. So, the expression is true. Since, expression (c==5) is true,
!(c==5) is false.

CONDITIONAL OPERATOR – Ternary Operators


Conditional operator takes three operands and consists of two symbols ? and
: . Conditional operators are used for decision making in C. For example:
d=(c>0)?10:-10;

If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will


be -10.

PRECEDENCE OF OPERATORS
If more than one operator is involved in an expression then, C language has a
predefined rule of priority of operators. This rule of priority of operators is
called operator precedence.

Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.

Category Operator Associativit


y
Brackets & () Left to right
Postfix
Multiplicative */% Left to right
Additive +- Left to right
Relational < <= > >= Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= Right to left
^= |=

54
ASSOCIATIVITY OF OPERATORS
Associativity indicates in which order two operators of the same precedence
(priority) executes. C has left operator associativity.
Let us suppose an expression:
a= =b!=c

Here, operators = = and != have the same precedence. The associativity of


both = = and != is left to right, i.e., the expression in left is executed first
and execution take pale towards right. Thus, a= =b!=c equivalent to :
(a= =b)!=c
Operators may be left-associative (meaning the operations are grouped from
the left), right-associative (meaning the operations are grouped from the
right)

Operator Associativ Operators


Name ity

Multiplicative left to right * / %

Additive left to right + -

Relational left to right < > <= >=

Equality left to right == !=

Logical AND left to right &&

Logical OR left to right ||

Conditional right to left ?:

Assignment right to left = += -= *= /= <<= >>= %=


&= ^= |=

Comma left to right ,

55
MORE SAMPLE PROGRAMS
1. Program to return the square and square root of a number.
#include <stdio.h>
#include <math.h>

int main ()
{
int num, sqr; double squarert;

printf("Key in a number to get its square root: ");


scanf("%d",&num);

squarert=sqrt(num);
sqr=num*num;

printf("Square root of \"%d\" is \"%lf\"\n",num,squarert);


printf("The square of the number is %d\n",sqr);

return(0);
}

2. Program to return a number raised to the power of another


number.

#include<stdio.h>
#include<math.h>

void main()
{
int num, power;
double result;

printf("Key a number : ");


scanf("%d",&num);
printf("Key the power : ");
scanf("%d",&power);

result=pow(num,power);
56
printf("%d raised to power %d is %lf",num,power,result);
}

57
Chapter 4

CONTROL STRUCTURES
Definition
Control structures represent the forms in which statements in a program are
executed. Flow of control refers to the order in which the individual statements,
instructions or function calls of a program are executed or evaluated.
IMPORTANCE OF CONTROL STRUCTURES
Generally, a program should execute the statements one by one until the defined
end. This type of a program structure is called sequential structure. The
functionality of this type of program is limited since it flows in a single direction.
However, all high-level programming languages enable the programmer to change
the flow of program execution. This is done by the use of control structures whose
main benefits are to enable decision making and repetition as well as giving the
power to do far more complex processing and provide flexibility with logic.
The sophisticated logic is necessary for a program to solve complex problems.
The kinds of control flow statements supported by different languages vary, but can
be categorized by their effect:
 continuation at a different statement i.e. unconditional jump e.g. GoTo
statements
 executing a set of statements only if some condition is met i.e.
choice/decision
 executing a set of statements zero or more times, until some condition is met
i.e. loop
 executing a set of distant statements, after which the flow of control usually
returns e.g. subroutines/functions

TYPES OF CONTROL STRUCTURES


There are three types in C:
1. Sequence structures
Program statements are executed in the sequence in which they appear in the
program.
2. Selection structures/Decision/Branching Structures
Statement block is executed only if some condition is met. These structures
include if, if/else, and switch. Selection structures are extensively used in
programming because they allow the program to decide an action based upon
user's input or other processes for instance in password checking.

58
3. Repetition/Iterative/Looping structures
These are structures which allow the execution of a statement or a group of
statements multiple times until a condition either tests true or false. These include
while, do/while and for
SELECTION STRUCTURES
(a) THE IF SELECTION STRUCTURE
– Used to choose among alternative courses of action i.e. the if statement provides
a junction at which the program has to select which path to follow. The if
selection performs an action only if the condition is true.
General form
If (expression)
statement
Pseudocode:
If student’s marks is greater than or equal to 600
Print “Passed”
As in
if (marks>=600)
printf(“Passed”);

If condition is true
– Print statement executed and program goes on to next statement
– If false, print statement is ignored and the program goes onto the next
statement
NB/ Indenting makes programs easier to read

true
grade >= print “Passed”
60

false

Flow chart for the if selection structure

59
NB/ The statement in the if structure can be a single statement or a block
(Compound statement).
If it’s a block of statements, it must be marked off by braces.
if (expression)
{
Block of statements
}
As in
If (salary>15000)
{
PAYE = salary * 0.3;
printf(“Tax charged is %f”, PAYE);
}

(b) THE IF/ELSE

While if only performs an action if the condition is true, if/else specifies an action
to be performed both when the condition is true and when it is false. E.g.

Pseudocode:
If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”

false true
grade >= 60

print “Failed” print “Passed”

Flow chart for the if/else selection structure

Example
if (x >=100)
{
printf(“Let us increment x:\n”);
x++;
}

60
else

printf(“x < 0 \n);

(c) THE IF...ELSE IF...ELSE STATEMENT

– Test for multiple cases.


– Once a condition is met, the other statements are skipped

Pseudocode for an if..else if..else structure


If student’s grade is greater than or equal to 90
Print “A”
Else If student’s grade is greater than or equal to 80
Print “B”
else If student’s grade is greater than or equal to 70
Print “C”
else If student’s grade is greater than or equal to 60
Print “D”
else
Print “F”

Example

#include <stdio.h>

main()
{
int marks;
printf("Please enter your MARKS:");
scanf("%d", &marks);

if (marks>=90 && marks <=100)


printf("Your grade is A\n");

else if (marks>=80 && marks <=89)


printf("Your grade is B\n");

else if (marks>=70 && marks <=79)


printf("Your grade is C\n");

else if (marks>=60 && marks <=69)


61
printf("Your grade is D\n");
else if (marks >100)
printf("Marks out of range\n");
else
printf("Your grade is F\n");
}

(d) NESTED IF STATEMENTS


One if or else if statement can be used inside another if or else if statement(s).

Syntax
The syntax for a nested if statement is as follows:

if (boolean_expression 1)
{
/* Executes when the boolean ex

pression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}

You can nest else if...else in the similar way as you have nested if statement.

Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
/* check the boolean condition */
if( a = = 100 )
{
/* if condition is true then check the following */
if( b = = 200 )
{
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );

62
}
}
return 0;
}

(e) SWITCH STATEMENT


A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked
for each switch case.

Syntax
The syntax for a switch statement in C programming language is as follows:

switch(expression)
{
case constant-expression:
statement(s);
break;
case constant-expression :
statement(s);
break;
/* you can have any number of case statements */
default :
statement(s);
}

63
The following rules apply to a switch statement:
1) You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
2) The constant-expression for a case must be the same data type as the
variable in the switch
3) When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
4) When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.
5) Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.
6) A switch statement can have an optional default case, which must appear at
the end of the switch. The default case can be used for performing a task
when none of the cases is true. No break is needed in the default case.

Sample Switch Statement

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

char grade;
printf("Enter your grade:");
scanf("%c", &grade);

switch (grade)
{
64
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Very Good!\n");
break;
case 'C':
printf("Good!\n");
break;
case 'D':
printf("Work harder!\n");
break;
default:
printf("Fail!\n");
}
return 0;
}

NB\ The break statement is used to terminate loops or to exit from a switch.

(f) NESTED SWITCH STATEMENTS


It is possible to have a switch as part of the statement sequence of an outer switch.
Even if the case constants of the inner and outer switch contain common values, no
conflicts will arise.

Syntax
The syntax for a nested switch statement is as follows:
switch(ch1) {
case 'A':
printf("This A is part of outer switch" );
switch(ch2) {
case 'A':
printf("This A is part of inner switch" );
break;
case 'B':
}
break;
case 'B':
}
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
65
int b = 200;
switch(a) {
case 100:
printf("This is part of outer switch\n", a );
switch(b) {
case 200:
printf("This is part of inner switch\n", a );
printf(“A is equals to %d and B is equals to %d”, a, b);
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}

When the above code is compiled and executed, it produces the following result:

This is part of outer switch


This is part of inner switch
A is equals to 100 and B is equals to 200
Exact value of a is : 100
Exact value of b is : 200

REPETITION/ITERATIVE/LOOP STRUCTURES

A loop statement allows the execution of a statement or a group of statements


multiple times until a condition either tests true or false. There are two types of
loops: Pre-test and post-test loops.
In a pretest loop, a logical condition is checked before each repetition to determine
if the loop should terminate. These loops include:
– while loop
– for loop
Post-test loops check a logical condition after each repetition for termination. The
do-while loop is a post-test loop.

66
(a) WHILE LOOP IN C
A while loop statement repeatedly executes a target statement as long as a given
condition is true.
The statement(s) may be a single statement or a block of statements. The loop
iterates while the condition is true. When the condition becomes false, program
control passes to the line immediately following the loop.
The while loop starts with the checking of the condition. If it evaluates to true, then
the loop body statements are executed otherwise the first statement following the
loop is executed. For this reason, it is also called entry control loop.

The syntax of a while loop in C programming language is:

while(condition)
{
statement(s);
update expression
}

Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10; //loop index

/* while loop execution */


while( a < 20 )
67
{
printf("value of a: %d\n", a);
a++;
}
return 0;
}

When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

(b) FOR LOOP IN C


A for loop is a repetition control structure used to write a loop that needs to
execute a specific number of times.

Syntax
The syntax of a for loop in C programming language is:

for ( initial expression;logical condition; update expression )


{
statement(s);
}

Here is the flow of control in a for loop:


1. This step initializes any loop control variables/index. You are not required to
put a statement here, as long as a semicolon appears.

2. Next, the condition is evaluated. If it is true, the body of the loop is executed.
If it is false, the body of the loop does not execute and flow of control jumps
to the next statement just after the for loop.

68
3. After the body of the for loop executes, the flow of control jumps back up to
the update expression. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears
after the condition.
4. The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself. After the condition becomes false, the for loop
terminates.

Flow Diagram

Example
#include <stdio.h>
int main ()
{
int a;//loop index
/* for loop execution */
for(a = 10; a < 20; a++)
{
printf("value of a: %d\n", a);
}
return 0;
}

69
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

(c) DO...WHILE LOOP IN C – Post Test Loop


Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop in C checks its condition at the bottom of the loop. It checks the
condition after executing the statements in the body, and therefore is also known as
an exit control loop.

A do...while loop is similar to a while loop, except that a do...while loop is


guaranteed to execute at least one time. The structure, therefore loops until a
condition tests false i.e. loop until.

Syntax
do
{
statement(s);
update expression;
}while( condition );

If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop execute again. This process repeats until the given
condition becomes false.

70
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return

When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
71
(d) NESTED LOOPS IN C
C programming language allows the use of one loop inside another loop. The
following section shows a few examples to illustrate the concept.
Syntax
The syntax for a nested for loop statement in C is as follows:

for ( init; condition; increment )


{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}

The syntax for a nested while loop statement in C programming language is as


follows:

while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}

The syntax for a nested do...while loop statement in C programming language is as


follows:

do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );

72
A final note on loop nesting is that you can put any type of loop inside of any other
type of loop. For example, a for loop can be inside a while loop or vice versa.

Example

#include <stdio.h>

int main()
{
int n, c, k;

printf("Enter number of rows:");


scanf("%d",&n);

for ( c = 1 ; c <= n ; c++ )


{
for( k = 1 ; k <= c ; k++ )
{
printf("%d",k);
}
printf("\n");
}

return 0;
}

Result:
If the user interred 5 as the number of rows, the output would be:
1
12
123
1234
12345

73
TERMINATING LOOPS
• Counter-controlled loops - a loop controlled by a counter variable, generally where
the number of times the loop will execute is known ahead of time especially in for
loops.
• Event-controlled loops - loops where termination depends on an event rather than
executing a fixed number of times for example when a zero value is keyed in or
search through data until an item is found. Used mostly in while loops and do-while
loops.
Using a Sentinel
• The value -999 is sometimes referred to as a sentinel value. The value serves as
the “guardian” for the
termination of the loop. It is a good idea to make the sentinel a constant:
#define STOPNUMBER -999
while (number != STOPNUMBER) ...

LOOP CONTROL STATEMENTS – Jump Structures in C


These structures change the flow of execution by transferring control to other parts
of the program.
 break statement
 continue statement
 return statement: Exits from the current method and optionally returns a
value.

(a)BREAK STATEMENT
The break statement forces an immediate termination of a loop and control
resumes at the next statement following the loop.
#include<stdio.h>
int main()
{
int x;
for(x=1;x<=10;x++)
{
if(x==5)
{
break;
74
}
printf("%d\t",x);
}
return 0;
}
Output: 1 2 3 4 5

(b)CONTINUE STATEMENT
Instead of forcing termination, continue statement, forces the next iteration of the
loop to take place, skipping any code in between.

Example
//program to demonstrate the working of continue statement in C programming
#include<stdio.h>
int main()
{
int x;
for(x=1;x<=10;x++)
{
if(x==5)
{
break;
}
printf("%d\t",x);
}
return 0;
}
Output: 1 2 3 4 6 7 8 9 10

THE COMMA OPERATOR in C


The comma operator (,) permits two expressions to appear in situations where only
one expression would ordinarily be used.
#include <stdio.h>
int main ()
{
/* for loop execution */
int a,b,product=0,product2;

for(a = 10,b=10; a <=20;a++,b--)


{
product = 10 * a; product2 = 10 * b;

printf("10 * %d = %d ", a,product);


printf("10 * %d = %d\n", b,product2);

75
}
return 0;
}

THE INFINITE LOOP


A loop becomes infinite loop if a condition never becomes false for example when
the update expression is missing in a loop.
The for loop is traditionally used to demonstrate the concept of an infinite loop..
Since none of the three expressions that form the for loop are required, you can
make an endless loop by leaving the conditional expression empty.

#include <stdio.h>
int main ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
}
return 0;
}

When the conditional expression is absent, it is assumed to be true. You may have
an initialization and increment expression, but C programmers more commonly use
the for(;;) construct to signify an infinite loop.
NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.

76
CHAPTER 5

SUBPROGRAMS IN C
A sub-program, also known as a function, procedure or a subroutine
is a section of code that performs a specific task and can be called
from other parts of a program. Every C program has at least one
function, which is main().

A function declaration tells the compiler about a function's name,


return type, and parameters and how to call the function. A function
definition provides the actual body of the function.

Benefits of using sub-programs in programming are:


 Improved readability of the code as the program is broken into
several but logical sections
 The smaller programs make programming, debugging and
maintenance easier.
 They also help in coding repeated operations such as
frequently used calculations thus making programming less
repetitive and faster.
 Procedures used in one program can be used in other
programs i.e. code re-use. Examples include the library
functions such as printf() and scanf().
 Programmers working on large projects can share the
workload by making different functions.

TYPES OF FUNCTIONS
There are two types of functions in C:
 Library functions
 User defined functions

LIBRARY FUNCTIONS

A library function also known as predefined or built-in function is a


pre-written piece of code that can be called from within a user-
defined program. They are a core part of the C programming
language.

Library functions save time by helping developers avoid writing


repetitive code. They are often highly optimized and tested
making them a reliable and efficient way to perform tasks.

They are For example:

printf()

77
- printf() is used for displaying output in C.
The general syntax of the printf() function is written as
printf ( control string, arg7, arg2, . . . , argn)
where control string refers to a string that contains formatting
information, and arg7, arg2, . . . ,argn are arguments that represent
the individual output data items. The arguments can be written as
constants, single variable or array names, or more complex
expressions.

scanf()
- scanf() is used for taking input in C.

USER DEFINED FUNCTIONS

C allows programmers to define their own function according to


their requirements known as user defined functions.

How user-defined function works in C


Programming?
#include <stdio.h>
void function_name(){
................
................
}
int main(){
...........
...........
function_name();
...........
...........
}

As mentioned earlier, every C program begins from main() and


program starts executing the codes inside main() function. When the
control of program reaches to function_name() inside main() function.
The control of program jumps to void function_name() and executes the
codes inside it. When, all the codes inside that user-defined function
are executed, control of the program jumps to the statement just
after function_name() from where it is called. Analyze the figure below
for understanding the concept of function in C programming.

78
Remember, the function name is an identifier and should be unique.

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

return_type function_name ( parameter list )


{
body of the function
}

A function definition refers to the creation of a function. In C


programming language a function definition consists of a function
header and a function body. Here are all the parts of a function:
1. The header is made up of :
i. 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.
ii. Function Name: This is the actual name of the function. The
function name and the parameter list together constitute the
function signature.

79
iii. Parameter list: This is a comma-separated list of parameters
that the function takes. A parameter is a value passed to a
function as an input when the function is called.
When a function is invoked/called, you pass a value to the
formal parameter. This value is referred to as actual
parameter or argument.
When calling a function the actual arguments must match the
formal parameters in terms of type, order, and number.
Parameters are optional.

2. Function Body: The function body contains a collection of


statements that define what the function does.

Example
Following is the source code for a function called max(). This
function takes two parameters num1 and num2 and returns the
maximum between the two:

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

80
}
FUNCTION DECLARATIONS
A function declarations also known as forward declaration is a
statement that 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 the 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 the 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. Therefore, the calling program is suspended during
execution of the called subprogram.
To call a function, you simply need to pass the required
parameters along with function name, and if the function
returns a value, then you can store the returned value. For example:

#include <stdio.h>
/* function declaration */
int max(int num1, int num2);

81
int main ()
{
/* local variable definition */
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 );
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;
}

The formal parameters behave like other local variables inside the
function and are created upon entry into the function and destroyed
upon exit.

While calling a function, there are two ways that arguments can be
passed to a function:

82
Pass Type Description
This method copies the actual value of an
argument into the formal parameter of the
Pass by value function. In this case, changes made to the
parameter inside the function have no effect on
the original argument.
This method copies the address of an
argument into the formal parameter. Inside the
Pass by function, the address is used to access the actual
reference argument used in the call. This means that
changes made to the parameter affects the
original argument.

83
By default, C uses pass by value to pass arguments. In general,
this means that code within a function cannot alter the arguments
used to call the function and above mentioned example while calling
max() function used the same method.

FUNCTION ARGUMENTS
If a function is to use arguments, it must declare variables that
accept the values of the arguments. These variables are called the
formal parameters of the function.
The formal parameters behave like other local variables inside the
function and are created upon entry into the function and destroyed
upon exit.
A formal parameter is a dummy variable listed in the subprogram
header and used in the subprogram. An actual parameter
represents a value used in the subprogram call statement.

When max() is called, we pass it the arguments which the function


uses as the values of ret. This process is called parameter
passing.
*****
Parameters refer to the list of variables in a method declaration.
Arguments are the actual values that are passed when the method
is invoked.
When calling a function, the arguments used must match the
formal parameters in type, order and number.
Inbuilt Functions

84
Functi
on Description

This function returns the absolute value of an integer. The


absolute value of a number is always positive. Only integer
abs ( ) values are supported in C.

This function returns the nearest integer which is less than or


floor ( ) equal to the argument passed to this function.

round( This function returns the nearest integer value of the


) float/double argument passed to this function.

This function returns nearest integer value which is greater than


ceil ( ) or equal to the argument passed to this function.

log ( ) This function is used to calculates natural logarithm.

This function is used to find square root of the argument passed


sqrt ( ) to this function.

This is used to find the power of the given number. Takes two
pow ( ) integer values and returns a double value. E.g. pow(2,3)

isupper(
) Checks if a character is uppercase or not. Requires ctype.h

tolower(
) Converts an uppercase character to lowercase

toupper
()

85
EXERCISES

1. Write a C program to add two integers. Define a function


add to add integers and display sum in main() function.

//main function
#include<stdio.h>
int add(int a, int b);
int main()
{
int a, b, sum;

printf ("Enter the first integer:");


scanf ("%d", &a);

printf("Enter the second integer:");


scanf("%d", &b);

sum = add(a,b);
printf("The sum of the two numbers is %d\n", result);

//start of second function


int add(int a,int b)
{
int result;
result = a+b;
return result;
}

2. Write a C program– max()- to determine the greater of two


integers. Call the function from main() and supply it with two
integers and then display the greater of the two.

86
#include <stdio.h>

/* function declaration */
int max(int, int);

int main ()
{
/* local variable definition */
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 );

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

87
CHAPTER 6

DATA STRUCTURES
These refer to groups of data elements that are organized as a single
unit so that they can be used more efficiently as compared to the simple
variables such as integers. Ordinary variables store one value at a time while a
data structure will store more than one value at a time under a single variable
name.

Data structures are important for grouping sets of related data together
and passing them as one. For example, if you have a method that prints a
set of data but you don't know when writing the procedure how large that set is
going to be, you could use an array to pass the data to that method and loop
through it.
The data structures available in C include arrays, Linked Lists, Stacks,
Queues, Trees, Graphs, Tables, Sets, Pointers and References.
In Pascal, the data structures include arrays, records, files and sets.
Data structures can be classified using various criteria.

a) Linear
In linear data structures, elements are arranged in a linear fashion. Such
structures traverse the data elements sequentially. The elements in the
structure are adjacent to one another other and every element has exactly two
neighbour elements to which it is connected. Arrays, linked lists, stacks and
queues are examples of linear data structures.
b) Non-Linear
The data values in this structure are not arranged in order but every data item
is attached to other data items in a way that is specific for reflecting
relationships. Trees, graphs, tables and sets are examples of non-linear data
structures.
c) Homogenous
In this type of data structures, values of the same types of data are stored, as
in an array.
d) Non-homogenous
In this type of data structures, data values of different types are grouped
together, as in structures and classes.
e) Dynamic
Dynamic data structures are those whose size can be changed during program
execution. These data structures can grow and shrink during execution. These
include references and pointers.
f) Static
With a static data structure, the size of the structure is fixed. Static data
structures such as arrays are very good for storing a well-defined number of
data items.

88
ARRAYS
An array is a named list of elements, all with the same data type. It is also
defined as a consecutive group of memory locations all of which have the same
name and the same data type. Arrays store a fixed-size sequential collection of
elements of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and


number99, you declare one array variable such as numbers and use
numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address


corresponds to the first element and the highest address to the last element.

CREATING/DECLARING ARRAYS

There are three ways of creating an array in C:

i. Declare the size the array and data type of the elements it will hold as
follows:

89
type arrayName [ arraySize ];
e.g. int myArray[5];

ii. Declare and initialize the array with values. The elements are enclosed in
curly braces separated by commas e.g.
int myArray[]={3,1,7};

iii. Dynamically allocate memory for the array using the malloc function as
follows:
int* myArray;
myArray = malloc(4 * sizeof(int));

INITIALIZING ARRAYS

You can initialize an array in C either one by one or using a single statement as
follows:

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ]. Following
is an example to assign a single element of the array:

If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write:

double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

You will create exactly the same array as you did in the previous example.

balance[4] = 50.0;

The above statement assigns element number 5 in the array a value of 50.0.
Array with 4th index will be 5th ie. last element because all arrays have 0 as
the index of their first element which is also called base index. Following is
the pictorial representation of the same array we discussed above:

ACCESSING ARRAY ELEMENTS

An element is accessed by indexing the array name. This is done by placing


the index of the element within square brackets after the name of the array.
For example:

double salary = balance[9];

90
The above statement will take 10th element from the array and assign the
value to salary variable. Following is an example which will use all the above
mentioned three concepts viz. declaration, assignment and accessing arrays:

#include <stdio.h>

int main ()
{
int n[ 9 ]; /* n
int i,j;

/* initialize elements of array n to 0 */


for ( i = 0; i < 9; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}

/* output each array element's value */


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

return 0;
}

When the above code is compiled and executed, it produces the following
result:

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

MULTIDIMENSIONAL ARRAYS
C programming language allows multidimensional arrays. Here is the general
form of a multidimensional array declaration −
91
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer
array −
int threedim[5][10][4];
The simplest form of multidimensional array is the two-dimensional array. A
two-dimensional array is, in essence, a list of one-dimensional arrays. To
declare a two-dimensional integer array of size [x][y], you would write
something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C
identifier. A two-dimensional array can be considered as a table which will
have x number of rows and y number of columns. A two-dimensional array a,
which contains three rows and four columns can be shown as follows −

Thus, every element in the array a is identified by an element name of the


form a[ i ][ j ], where 'a' is the name of the array, and 'i' and 'j' are the
subscripts that uniquely identify each element in 'a'.

Initializing Two-Dimensional Arrays


Multidimensional arrays may be initialized by specifying bracketed values for
each row. Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The
following initialization is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements


An element in a two-dimensional array is accessed by using the subscripts,
i.e., row index and column index of the array. For example −
int val = a[2][3];
The above statement will take the 4th element from the 3rd row of the array.
You can verify it in the above figure. Let us check the following program where
we have used a nested loop to handle a two-dimensional array −
Live Demo

92
#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;

/* output each array element's value */


for ( i = 0; i < 5; i++ ) {

for ( j = 0; j < 2; j++ ) {


printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}

return 0;
}
When the above code is compiled and executed, it produces the following
result −
a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
a[3][0] = 3
a[3][1] = 6
a[4][0] = 4
a[4][1] = 8
SORT TECHNIQUES
1. Bubble sort
2. Selection sort
3. Merge sort
4. Quick sort
5. Exchange sort
6. Shell sort
Bubble Sort

93
In the bubble sort, as elements are sorted they gradually "bubble" (or rise) to
their proper location in the array, like bubbles rising in a glass of soda. The
bubble sort repeatedly compares adjacent elements of an array. The first
and second elements are compared and swapped if out of order. Then the
second and third elements are compared and swapped if out of order. This
sorting process continues until the last two elements of the array are compared
and swapped if out of order.

When this first pass through the array is complete, the bubble sort returns to
elements one and two and starts the process all over again.

The table below follows an array of numbers before, during, and after a bubble
sort fordescending order. A "pass" is defined as one full trip through the array
comparing and if necessary, swapping, adjacent elements. Several passes
have to be made through the array before it is finally sorted
Array at
84 69 76 86 94 91
beginning:

After Pass #1: 84 76 86 94 91 69

After Pass #2: 84 86 94 91 76 69

After Pass #3: 86 94 91 84 76 69

After Pass #4: 94 91 86 84 76 69

After Pass #5
94 91 86 84 76 69
(done):

94
The bubble sort is an easy algorithm to program, but it is slower than
many other sorts. In most cases, the process is finished before this last pass
is made, but all the passes must be mae whether the array is sorted or not,
making algorith inefficient.

Note the coding required to implement the exchange of items: the current item
of the array (Array [y]) is assigned to a temporary, or "hold" variable (emp).
The adjacent item of the array (myArray [y + 1]) is then copied to the current
item (at this point, both the current and the adjacent items contain the same
value). The temporary variable is then assigned to the adjacent item,
completing the exchange.
// Bubble Sort Function for Descending Order
#include<stdio.h>
main()
{
int control , control2, marks, temp;
int allmarks[5]={9,7,12,5,8};

for (control = 0; control < 4; control++) {


for (control2 = 0; control2 < 4; control2++) {
if (allmarks[control2] > allmarks[control2+1])
{
temp = allmarks[control2];
allmarks[control2]= allmarks[control2+1];
allmarks[control2+1] = temp;
}
}
}

printf("\nThe sorted list of marks is:\n");

for (control=0; control<=4;control++)


{
printf("%d\n", allmarks[control]);
}
}

Selection Sort

95
The selection sort is a combination of searching and sorting.

During each pass, the unsorted element with the smallest (or largest)
value is moved to its proper position in the array.
The number of times the sort passes through the array is one less than the
number of items in the array. In the selection sort, the inner loop finds the
next smallest (or largest) value and the outer loop places that value into its
proper location.

Let's look at our same table of elements using a selection sort for descending
order. Remember, a "pass" is defined as one full trip through the array
comparing and if necessary, swapping elements.
Array at
84 69 76 86 94 91
beginning:

After Pass #1: 84 91 76 86 94 69

After Pass #2: 84 91 94 86 76 69

After Pass #3: 86 91 94 84 76 69

After Pass #4: 94 91 86 84 76 69

After Pass #5
94 91 86 84 76 69
(done):

96
While being an easy sort to program, the selection sort is one of the least
efficient. The algorithm offers no way to end the sort early, even if it
begins with an already sorted list.
// Selection Sort Function for Descending Order
void main()
{
int i, j, first, temp;
int num[6] = {84,69,76,86,94,91};
for (i= 5; i > 0; i--)
{
first = 0; // initialize the subscript of first element
for (j=1; j<=i; j++) // locate smallest value between positions 1 and i.
{
if (num[j] < num[first])
first = j;
}
temp = num[first]; // Swap smallest found with element in position i.
num[first] = num[i];
num[i] = temp;
}
return;
}

Shell Sort
The shell sort is named after its inventor D. L. Shell. Instead of comparing
adjacent elements, like the bubble sort, the shell sort repeatedly compares
elements that are a certain distance away from each other (d represents this
distance). The value of d starts out as half the input size and is halved after
each pass through the array. The elements are compared and swapped when
needed. The equation d= (N + 1) / 2 is used. Notice that only integer values
are used for d since integer division is occurring.

Let's look at our same list of values for descending order with the shell sort.
Remember, a "pass" is defined as one full trip through the array comparing and
if necessary, swapping elements.

Array at
84 69 76 86 94 91 d
beginning:
After Pass #1: 86 94 91 84 69 76 3
After Pass #2: 91 94 86 84 69 76 2
After Pass #3: 94 91 86 84 76 69 1
After Pass #4
94 91 86 84 76 69 1
(done):

97
First Pass: d = (6 + 1) / 2 = 3. Compare 1st and 4th , 2nd and 5th, and 3rd
and 6th items since they are 3 positions away from each other))
Second Pass: value for d is halved d = (3 + 1) / 2 = 2. Compare items two
places away such as 1st and 3rd ……
Third Pass: value for d is halved d = (2 + 1) / 2 = 1. Compare items one
place away such as 1st and 2nd …..
Last Pass: sort continues until d = 1 and the pass occurs without any swaps.

This sorting process, with its comparison model, is an efficient sorting


algorithm.

//Shell Sort Function for Descending Order


void main()
{
int I,d , temp, length[5];
while( (d > 1)) // boolean flag (true when not equal to 0)
{
d = (d+1) / 2;
for (i = 0; i < (5 - d); i++)
{
if (num[i + d] > num[i])
{
temp = num[i + d]; // swap positions i+d and i
num[i + d] = num[i];
num[i] = temp;
flag = 1; // tells swap has occurred
}
}
}
return;
}

Quick Sort
The quicksort is considered to be very efficient, with its "divide and conquer"
algorithm. This sort starts by dividing the original array into two sections
(partitions) based upon the value of the first element in the array. Since our
example sorts into descending order, the first section will contain all the
elements greater than the first element. The second section will contain
elements less than (or equal to) the first element. It is possible for the first
element to end up in either section. This sort uses recursion - the process of
"calling itself".

Let's examine our same example

98
Array at
84 69 76 86 94 91
beginning:
= 1st
86 94 91 84 69 76
partition
= 2nd
94 91 86 84 69 76
partition

99
94 91 86 84 69 76
94 91 86 84 69 76
Done: 94 91 86 84 76 69

100
//Quick Sort Functions for Descending Order
// (2 Functions)
void main()
{
// top = subscript of beginning of array
// bottom = subscript of end of array

int middle;
if (top < bottom)
{
middle = partition(num, top, bottom);
quicksort(num, top, middle); // sort first section
quicksort(num, middle+1, bottom); // sort second section
}
return;
}

//Function to determine the partitions


// partitions the array and returns the middle subscript
int main()
{
int x = array[top];
int i = top - 1;
int j = bottom + 1;
int temp;
do
{
do
{
j - -;
}while (x >array[j]);

do
{
i++;
} while (x <array[i]);

if (i < j)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}while (i < j);
return j; // returns middle subscript
}

101
Merge Sort
The merge sort combines two sorted arrays into one larger sorted array.
As the diagram below shows, Array A and Array B merge to form Array C.

Arrays to be merged MUST be SORTED FIRST!!

Be sure to declare Array C in main( ) and establish its size.

Example: Ascending Order


Array A: {7. 12}
Array B: {5, 7, 8}
Array C: {5, 7, 7, 8, 12} after merge

Here is how it works: The first element of array A is compared with the first
element of array B. If the first element of array A is smaller than the first
element of array B, the element from array A is moved to the new array C. The
subscript of array A is now increased since the first element is now set and we
move on.

If the element from array B should be smaller, it is moved to the new array C.
The subscript of array B is increased. This process of comparing the elements
in the two arrays continues until either array A or array B is empty. When one
array is empty, any elements remaining in the other (non-empty) array are
"pushed" into the end of array C and the merge is complete.

//Function to merge two pre-sorted arrays


void main()
{
int indexA = 0; // initialize variables for the subscripts
int indexB = 0;
int indexC = 0;
Int arrayC[5];

while((indexA < 5) && (indexB < 5)


{

102
if (arrayA[indexA] < arrayB[indexB])
{
arrayC[indexC] = arrayA[indexA];
indexA++; //increase the subscript
}
else
{
arrayC[indexC] = arrayB[indexB];
indexB++; //increase the subscript
}
indexC++; //move to the next position in the new array
}
// Move remaining elements to end of new array when one merging array is empty
while (indexA < 5)
{
arrayC[indexC] = arrayA[indexA];
indexA++;
indexC++;
}
while (indexB < 5)
{
arrayC[indexC] = arrayB[indexB];
indexB++;
indexC++;
}
return;
}

SEARCHING ARRAYS
When working with arrays, it is often necessary to perform a search or "lookup"
to determine whether an array contains a value that matches a certain key
value The process of locating a particular element value in an array is called
searching. There are two types of search mechanisms: serial/linear search
and binary search
a) Serial Search
The technique used here is called a serial search, because the integer
elements of the array are compared one by one to the user input being looked
for (userValue) until either a match is found or all elements of the array are
examined without finding a match.
In the code below, if a match is found, the text “There is a match” is printed on
the form and the execution of the procedure is terminated (Exit Sub). If no
match is found, the program exits the loop and prints the text “No match
found”.
#include <stdio.h>

int main()
{
int array[5]={10,7,8,2,5}, searchvalue, c;

printf("\tEnter the number to search: ");

103
scanf("%d", &searchvalue);

for (c = 0; c < 5; c++)


{
if (searchvalue == array[c]) // if required element found
{
printf("\n%d is present at location %d.\n", searchvalue, c++);
break;
}
}
if (c == 5) // if looped more than 5 times ie 6 times
printf("\n%d is not present in the array.\n", searchvalue);

return 0;
}

Binary Search
Binary search uses the concept of splitting your searchable array in two,
discarding the half that does not have the element for which you are looking.
You place your items in an array and sort them. Then you simply get the
middle element and test if it is <, >, or = to the element for which you are
searching. If it is less than, you discard the greater half, get the middle index of
the remaining elements and do it again. Binary search divides your problem in
half every time you execute your loop.

#include <stdio.h>

int main()
{
int c, first, last, middle, n, search, array[10];

printf("Enter number of elements\n");


scanf("%d",&n);

printf("Enter %d integers\n", n);

for ( c = 0 ; c < n ; c++ )


scanf("%d",&array[c]);

printf("Enter value to find\n");


scanf("%d",&search);

first = 0;
last = n - 1;
104
middle = (first+last)/2;

while( first <= last )


{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if ( first > last )
printf("Not found! %d is not present in the list.\n", search);

return 0;
}

C STRINGS
In C, one or more characters enclosed between double quotes is called a string.
C does not have built-in string data type. Instead, C supports strings using one-
dimensional arrays. A string is defined as a null terminated array i.e. \0.
This means that the array be one byte larger than the largest string it is going
to hold, in order 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 string.h header file. 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. E.g.

#include<stdio.h>
main ( )
{
char name [80];
printf (” Enter a string: \n”);
gets(name);

//Output the name


printf(name);
}

105
The following declaration and initialization create a string consisting of the
word "Hello". To hold the null character at the end of the array, the size of the
character array containing the string is one more than the number of
characters in the word "Hello".

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Initialization of strings

In C, string can be initialized in a different number of ways.

char c[]="abcd";
OR,
char c[5]="abcd";
OR,
char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};

Strings can also be initialized using pointers

char *c="abcd";
char c[20];
scanf("%s",c);

String variable c can only take a word. It is beacause when white space is
encountered, the scanf() function terminates.

Write a C program to illustrate how to read strings from terminal.


Here, program will ignore Ritchie because, scanf() function takes only string
before the white space.
#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
}

Output

Enter name: Dennis Ritchie


Your name is Dennis.

106
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 an integer indicating the length of a string.
4. strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if
s1<s2; greater than 0 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.
Strlwr()
7.
converts string to lowercase
8. strupr()
converts string to uppercase
9. Strrev()
To reverse a string

107
The C library function int strcmp(const char *str1, const char *str2)
compares the string pointed to by str1 to the string pointed to by str2.

Following is the declaration for strcmp() function.

strcmp(str1, str2)

PARAMETERS

 str1 -- This is the first string to be compared.


 str2 -- This is the second string to be compared.

RETURN VALUE

This function returned values are as follows:

 if Return value < 0 then it indicates str1 is less than str2


 if Return value > 0 then it indicates str2 is less than str1
 if Return value = 0 then it indicates str1 is equal to str2

Example

The following example shows the usage of strncmp() function.

#include <stdio.h>
#include <string.h>

int main ()
{
char str1[15];
char str2[15];
int ret;

strcpy(str1, "abcdef");
strcpy(str2, "ABCDEF");

ret = strcmp(str1, str2);


if(ret > 0)
{
printf("str1 is less than str2");
}
else if(ret < 0)
{
printf("str2 is less than str1");
}
else
{

108
printf("str1 is equal to str2");
}
return(0);
}

109

You might also like