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

Basics of Programming

programming notes

Uploaded by

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

Basics of Programming

programming notes

Uploaded by

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

BIT 1203: INTRODUCTION PROGRAMMING (C)

LECTURER: DOROTHY MUTUA

Introduction
This module is divided into 11 Lectures. The module introduces students to basic
programming technology, concepts and best practices. It will also enable students to
design write and test logical structures in order to solve computer problems as well as
enhance usage of computers. The module will provide the learner with a general body
of knowledge about programming languages and the ability to reason critically about
programming languages in software engineering work. Moreover, this course serves
as a background for further study in areas of compiler and interpreter construction as
well as software design and development.

Assignments/self tests
There are two (2) assignments and two (2) continuous assessment tests that the
learner will undertake in the course of the study. The coursework (continuous
assessment tests and assignments) will account 30% of the final score.

Examinations
The examination will be a sit-in and will contribute 70% of the final score.

Recommended Reading
[1].An introduction to programming by Wu Thomas, Norman and Theodore: McGrill
(1997).
[2]. Computer Fundamentals and Programming in C, Pradip Dey and Manas Gosh
(2008)
Additional Reading
[1].C programming language by Brian W. Kernighan, Dennis Ritchie, 2nd ed: prentice
hall(2003).
[2]. C how to program by H.M. Deitel and P.J.Deitel, 3rd ed: Prentice hall(2001).
[3]. An introduction to algorithms by Cormen etal: MIT Press(2000).

Objectives
After successful completion of this module the learner will be able to demonstrate
satisfactory performance in the following areas:
▪ Placing context development in programming languages and reasons for
evolutions.
▪ Recognize and apply appropriate ways to control and manipulate data
▪ Break down and formulate data into structures appropriate for the problem to
be addressed.
▪ Define and apply a range of testing approaches to check correctness of
programming code.
▪ Put programming activities into the context of software development as a
whole with emphasize on the importance of documentation.
Lesson 1: Introduction

Prepared By Dorothy Mutua 1


1.1. Introduction
1.2. Lesson objectives
1.3. Lesson outline
1.4. Definitions
1.5. System development life cycle (SDLC)
1.6. Program development life cycle (PDLC)
1.7. Algorithm development activities
1.8. Algorithms and object oriented development approach
1.9. Revision questions
1.10. Summary
1.11. Suggested reading
Lesson 2: Programming paradigms
2.1. Introduction
2.2. Lesson objectives
2.3. Lesson outline
2.4. Imperative paradigm
2.5. Functional paradigm
2.6. Object oriented paradigm
2.7. Logical paradigm
2.8. Structured programming
2.8. Revision questions
2.9. Summary
2.10. Suggested reading
Lesson 3: Program development life cycle
3.1. Introduction
3.2. Lesson objectives
3.3. Lesson outline
3.4. Program development life cycle
3.5. Problem solving phases
3.6. Structured programming concepts
3.7. Program design
3.8. Revision questions
3.9. Summary
3.10. Suggested reading
Lesson 4: Programming languages
4.1. Introduction
4.2. Lesson objectives
4.3. Lesson outline
4.4. Programming language
4.5. Characteristics of a good programming language
4.6. Generations of programming languages
4.7. Classification of programming languages
4.8. Programming tools
4.9. Revisions
4.10. Summary
4.11. Suggested reading

Prepared By Dorothy Mutua 2


Lesson 5: Writing and compiling a program
5.1. Introduction
5.2. Lesson objectives
5.3. Lesson outline
5.4. Types of c files
5.5. Preprocessors
5.6. Steps for writing and compiling c program
5.7. Program structure
5.8. Testing vs debugging
5.9. Types of errors
5.10. Revision questions
5.11. Summary
5.12. Suggested reading
Lesson 6: Variables and data types
6.1. Introduction
6.2. Lesson objectives
6.3. Lesson outline
6.4. Character sets
6.5. Keywords
6.6. Variables
6.7. Data types
6.8. Qualifiers
6.9. Constants
6.10. Statements
6.11. Expressions
6.12. Revision questions
6.13. Summary
6.14. Suggested reading
Lesson 7: Operators
7.1. Introduction
7.2. Lesson objectives
7.3. Lesson outline
7.4. Arithmetic operators
7.5. Relational operators
7.6. Logical operators
7.7. Bitwise operators
7.8. Assignment operators
7.9. Misc operators
7.10. Order of precedence
7.11. Associativity of operators
7.12. Revision questions
7.13. Summary
7.14. Suggested reading
Lesson 8: Program control structures
8.1. Introduction
8.2. Lesson objectives

Prepared By Dorothy Mutua 3


8.3. Lesson outline
8.4. Sequence structure
8.5. Selection structure
8.6. Repetition structure
8.7. Break statement
8.8. Continue statement
8.9. Revision questions
8.10. Summary
8.11. Suggested reading
Lesson 9: Arrays
9.1. Introduction
9.2. Lesson objectives
9.3. Lesson outline
9.4. Definition
9.5. Types of arrays
9.6. Declaration of one dimensional array
9.7. Initialization of one dimensional array
9.8. Accessing array elements
9.9. Declaration of multidimensional array
9.10. Initialization of multidimensional array
9.11. Revision questions
9.12. Summary
9.13. Suggested reading
Lesson 10: Pointers
10.1. Introduction
10.2. Lesson objectives
10.3. Lesson outline
10.4. Accessing variable address
10.5. Definition of a pointer
10.6. Pointer declaration
10.7. Using pointers
10.8. Pointer operators
10.9. Working with pointers
10.10. Pointer arithmetic
10.11. Dynamic memory allocations
10.12. Revision questions
10.13. Summary
10.14. Suggested reading
Lesson 11: Procedures and functions
11.1. Introduction
11.2. Lesson objectives
11.3. Lesson outline
11.4. Functions vs. procedures
11.5. Classification of functions
11.6. Library functions
11.7. User defined functions

Prepared By Dorothy Mutua 4


11.8. Function prototype
11.9. Function call
11.10. Function definition
11.11. How user defined function work
11.12. Passing arguments to functions
11.13. Revision questions
11.14. Summary
11.15. Suggested reading

Lesson 1: Introduction

1.1. Introduction
Programming methodology is the study of analysis, design and implementation of
programs (software).Organizations and individuals are continually searching for
more efficient ways to perform the software development process. One way of
reducing the time and cost of development is to standardize software programs and
programming process. The benefits of standardized programs are that they are easier
to code, maintain, debug and modify. In the recent years, a variety of techniques
(paradigms) have appeared to minimize the way programmers design and develop
software.
1.2. Lesson objectives
By the end of this lesson, the learner will be able to:
▪ Define a program
▪ Differentiate between a program and an algorithm
▪ Describe some basic terms used in programming field
1.3. Lesson outline
This lesson is organized as follows:
1.1. Introduction
1.2. Lesson objectives
1.3. Lesson outline
1.4. Definitions
1.5. System development life cycle(SDLC)
1.6. Program development life cycle(PDLC)
1.7. Algorithm development activities
1.8. Algorithms and object oriented development approach
1.9. Revision questions
1.10. Summary
1.11. Suggested reading
1.4. Definitions
Programming: This is the process of writing a set of instructions that can be
interpreted and executed by a computer. Programming is one of the stages of system
development. Recall (Problem definition, Requirements collection, Requirements
analysis, system design, coding (programming), implementation and maintenance).
Program: A program, also known as computer program or software program, is an
organized set of instructions that the computer can execute. There are a number of
facets (qualities) to good programs:

Prepared By Dorothy Mutua 5


● Run correctly
● Run efficiently
● Easy to read and understand
● Easy to debug
● Easy to modify.
Algorithm : This is a procedure and sequence of actions to accomplish some task.
Application Programmer: This is a person with computer programming expertise to
develop application programs.
Bug: In programming, a bug, also called software bug, is an error, flaw, mistake,
failure, or fault in a program that prevents it from working as intended, or produces
an incorrect result. Bugs arise from mistakes and errors, made by designers and
programmers, in either a program's source code or its design.
Code : It refers to source code or machine code. Source code is any series of statements
written in some human-readable programming language, while machine code refers
to instructions for a computer processor in some machine language.
Coding: In software, coding means implementation of a programming logic using a
specific programming language.
Object code: Object code, also known as object file, is an intermediate representation
of code generated by a compiler after it processes a source code file. An object file is
mostly machine code that can be directly executed by a computer's CPU(central
processing unit).
Preprocessor: A preprocessor is a program that takes text and performs lexical
conversions on it. The conversions may include macro substitution, conditional
inclusion, and inclusion of other files.
Software Engineering: Refers to a systematic approach to the analysis, design,
implementation and maintenance of software, in which technologies and practices
from computer science, project management, engineering, application domains and
other fields, are applied.
Software metric: It is a quantitative measure of some property of a piece of software
or its specifications. Common software metrics include order of growth , source lines
of code ,function points, bugs per line of code ,code coverage, number of lines of
customer requirements e.t.c.
Syntax: In programming, syntax refers to the spelling and grammar of a
programming language. Each program defines its own syntactical rules that control
which words the computer understands, which combinations of words are
meaningful, and what punctuation is necessary.
1.5. System development life cycle is the process (SDLC)
This is a framework for defining activities performed during software development. It
defines seven stages: planning, analysis, design, development, testing,
implementation and maintenance.
Activities
Phase/Stage
SN
● Identify and select the system for development
Planning ● Assess project feasibility
1. ● Develop project plan

Prepared By Dorothy Mutua 6


● Gather business requirements
● Create process diagrams e.g. Use case diagrams, sequence
Analysis
2. diagrams, DFD
● Perform a buy versus build analysis
● Design the IT infrastructure e.g. network, hardware and software.
Design ● Design system models e.g. GUI, ERD e.t.c.
3.
● Design programs(algorithms)
● Develop the IT infrastructure e.g. network, hardware and software
Development ● Develop database and application programs
4.
● Write the test conditions
Testing ● Perform the system testing
5.
● System training
Implementatio ● Conversion e.g. parallel, phased, pilot and plunge conversion
6.
n
● Build a build a help desk to support the system users
Maintenance ● Perform system maintenance
7. ● Provide an environment to support system changes.

1.6. Program development life cycle (PDLC)


This is a framework that defines the steps used to build software applications. The
framework defines six steps in program development: Analysis of the problem,
design, code, testing and debugging, documentation and maintenance.
Phase Activity
SN
● Clearly define the problem to solve
1. Problem analysis ● Write program specifications: input, output,
processing

Prepared By Dorothy Mutua 7


● Develop the algorithm using a suitable tool e.g. pseudo
Program design
2. code.
● Translate the algorithm into application program
3. Program coding
● Include internal documentation i.e. comments
● Use test data to find errors
4. Testing and debugging
● Correct the errors(debugging)
● Revise internal documentation
5. Documentation
● Include external documentation
● Provide user training and support
6. Maintenance ● Correct any unanticipated errors
● Perform any modifications as required

1.7. Algorithm development activities


To develop an algorithm the following stages are followed: specify the problem,
specify the input, specify the output, define the processing and test the algorithm.

Prepared By Dorothy Mutua 8


Phase Description
SN
● Define the problem to be solved
Problem definition
1. ● Example: Calculate sum of two integers
● Define the input data clearly.
Specify the inputs
2. ● Example: Declare num1 and num2
● Define the output data clearly.
Specify the outputs
3. ● Example: Declare sum
● Define the calculation to perform
Describe the processing
4. ● Example: sum=num1+num2
● Perform a desk check for the algorithm
Testing ● Example: walk through the algorithm line by
5.
line

1.8. Algorithms in object oriented development approach


Traditional methods of program development have emphasized on procedure oriented
approach to program design. In this approach the data and operations to be performed
on the data are separated. However, in object oriented approach, the data and
operations to be performed on the data are bound together to form objects. When
designing an algorithm using object oriented approach the following steps are
important: problem definition, identification of classes, identification of relationships
between classes, identification of properties and methods for each class, drawing the
class design.
1.9. Revision questions
[a]. Explain why organizations and software developers are interested in searching
for more efficient ways to perform the software development process.
[b]. Explain three benefits of standardized programs.
[c].Describe any four characteristics of a good program.
1.10. Summary

Prepared By Dorothy Mutua 9


In this lesson, we have learnt that programming is one of the stages of system
development. We have observed that programmers and organizations are
continuously looking for better ways to develop software. We have also looked at some
basic terminologies used in programming.
1.11. Suggested reading
[1].An introduction to programming by Wu Thomas, Norman and Theodore: McGrill
(1997).
[2]. C programming language by Brian W. Kernighan, Dennis Ritchie, 2nd ed:
prentice hall(2003).
[3]. C how to program by H.M. Deitel and P.J.Deitel, 3rd ed: Prentice hall(2001).

Lesson 2: Programming paradigms

2.1. Introduction
In our last lesson we introduced programming concepts like program, programmer,
bug, syntax among others as well as program development life cycle. In our lesson
today we will be discussing programming paradigms. Paradigm refers to a way of
organizing thoughts. Programming paradigm in particular refers to basic structuring
of thoughts underlying the programming activity. There are four basic programming
paradigms: Imperative, functional, object oriented and logic paradigms.
2.2. Lesson objectives
By the end of this lesson the learner will be able to:
▪ State and describe major programming paradigms.
▪ Discuss the structured programming paradigm
2.3. Lesson outline
This lesson is structured as follows:
2.1. Introduction
2.2. Lesson objectives
2.3. Lesson outline
2.4. Imperative paradigm
2.5. Functional paradigm
2.6. Object oriented paradigm
2.7. Logical paradigm
2.8. Structured programming
2.8. Revision questions
2.9. Summary
2.10. Suggested reading
2.4. Imperative paradigm
Programming involves ordered steps for solving a problem (procedural
programming).
Computations are performed through a guided sequence of steps, in which these
variables are referred to or changed. The order of the steps is crucial, because a given
step will have different consequences depending on the current values of variables
when the step is executed.
[i].Based on digital hardware technology and the ideas of Von Neumann

Prepared By Dorothy Mutua 10


[ii]. Involves incremental change of the program state as a function of
time.
[iii]. Execution of computational steps(commands) in an order governed
by control structures
[iv]. Similar to descriptions of everyday routines, such as food recipes and
car repair
[v]. The natural abstraction is the procedure
Advantages
[i].There are minimal programming steps for solving a problem.
[ii]. Proving the validity of a given program is simple.
[iii]. Have low memory utilization
[iv]. They relatively efficient
[v]. The most common form of programming in use today.
Disadvantages
[i].Difficulty of reasoning about programs
[ii]. Difficulty of parallelization.
[iii]. It tends to be relatively low level.
2.5. Functional paradigm
Programming involves evaluating functions and using the results. The functional
programming paradigm views all subprograms as functions in the mathematical
sense-informally, they take in arguments and return a single solution. The solution
returned is based entirely on the input, and the time at which a function is called has
no relevance. The computational model is therefore one of function application and
reduction.
[i].It is based on mathematics and theory of functions
[ii]. Time only plays a minor role compared to the imperative paradigm
[iii]. All computations are done by applying (calling) functions
[iv]. Abstracts a single expression to a function which can be evaluated as
an expression
[v]. Functions are full-fledged data just like numbers, lists, ...
Advantages
[i].The high level of abstraction which results into fewer errors.
[ii]. Not dependent on assignment operations, allowing programs to be
evaluated in many different orders.
[iii]. More amenable to mathematical proof and analysis.
Disadvantages
[i].Less efficient
[ii]. Not useful for problems involving many variables or a lot of
sequential activity.
2.6. Object oriented paradigms
Programming involves use of objects and how the communicate using messages.
[i].Based on the theory of concepts, and models of human interaction with
real world phenomena.

Prepared By Dorothy Mutua 11


[ii]. Data as well as operations are encapsulated in objects
[iii]. Information hiding is used to protect internal properties of an object
[iv]. Objects interact by means of message passing
[v]. In most object-oriented languages objects are grouped in classes.
[vi]. Provides for class extension or specialization
Advantages
[i].Allows inheritance and hence code reuse
[ii]. Provides higher degree of modularity
[iii]. Allows information hiding
Disadvantages
[i].The programs are generally larger.
[ii]. The speed of execution is relatively lower because of increased
modularity and size.
2.7. Logical paradigms
Programming involves answering questions through search for solutions. The logic
paradigm fits extremely well when applied in problem domains that deal with the
extraction of knowledge from basic facts and relations.
[i].Based on automatic proofs within artificial intelligence
[ii]. Based on axioms, inference rules, and queries.
[iii]. Program execution becomes a systematic search in a set of facts,
making use of a set of inference rules
Advantages
[i].Good support for reasoning about programs
[ii]. Can lead to concise solutions to problems
Disadvantages
[i].Difficult to see what is actually happening computationally
[ii]. Slow execution
[iii]. Difficulties in understanding and debugging large programs
2.8. Structured programming
This is a sub discipline of procedural programming under imperative programming
paradigm.
It works under the concept that programs use three structures namely: decisions,
sequences and loops. Using this paradigm, programs can be broken into smaller
modules (sub routines). Hence it is said to follow modular programming. There is no
use of GO TO statement. It follows the principle of divide and conquer.
Advantages of structured programming
[i].Complexity can be reduced using concepts of divide and conquer.
[ii]. Logical structures ensure clear flow of control
[iii]. Increases productivity by allowing multiple programmers to work on
different parts of the project independently at the same time.
[iv]. The modules can be re-used many times thus saving time.
[v]. It is easier to update/ fix the program by replacing individual modules
rather than larger amounts of code.
Disadvantages of structured programming

Prepared By Dorothy Mutua 12


[i].Since GO TO statement is not used, the structure of the program must be
planned carefully.
[ii]. The program lacks encapsulation
[iii]. There is same code repetition
[iv]. It lacks information hiding(abstraction) how?
[v]. Change of a data structure will require changes at many places
throughout it and so changes become difficult to track.
[a]. Top-down approach
Top-down approach involves breaking the overall procedure or task into component
parts (modules) and then subdivide each component module until the lowest level has
been reached. It is also called top-down design or top-down decomposition. The
approach begins with the formulation of the overview of the system but no details are
given. Then the first level sub systems are specified but again no details are given.
Each of the sub systems is then refined to lower level subsystems. This proceeds until
the entire system is reduced to base elements. This approach is useful for brand new
systems. This methodology consists of hierarchy structure where details are added at
each level.
[b]. Bottom-up approach
In this design approach the individual base elements (modules) of the system are first
specified in great detail. Involves writing the basic procedures (sub routines) that will
be necessary at some point in the programming and then work up to the more
complex parts of the program. This methodology therefore begins with description of
the lowest level system components and how the components are assembled to form
higher level system components. This approach is sometimes used when reverse
engineering a design; i.e. when we are trying to figure out what somebody else
designed in an existing system.
2.9. Non-structured programming
Mostly all the program code is written in a single continuous main program. The logic
of the program is difficult to follow with the program. Code from other programs is
difficult to incorporate. It’s difficult to test specific portions of the program. The
program is also difficult to debug. Uses GO TO statement to transfer from one part of
the program to another. The connections between parts of the program using GO TO
can become quite haphazard. Such a code is referred to as spaghetti code.
2.10. Revision questions
[a]. Discuss the strengths and weaknesses of the following programming
paradigms:
[i].Imperative
[ii]. Functional
[iii]. Logic
[iv]. Object oriented
[b]. Differentiate between structured and non-structured programming
[c]. Discuss the following approaches used in structured programming.
[i].Bottom up approach
[ii]. Top down approach
2.11. Summary

Prepared By Dorothy Mutua 13


In this lesson we have discussed the four programming paradigms. We have
learnt that Paradigm refers to a way of organizing thoughts. Programming paradigm
in particular refers to basic structuring of thoughts underlying the programming
activity. There are four basic programming paradigms: Imperative, functional, object
oriented and logic paradigms.
2.12. Suggested reading
[1].An introduction to programming by Wu Thomas, Norman and Theodore: McGrill
(1997).
[2]. C programming language by Brian W. Kernighan, Dennis Ritchie, 2nd ed:
prentice hall(2003).
[3]. http://people.cs.aau.dk/~normark/prog3-03/html/notes/paradigms_themes-
paradigm-overview-section.html
[4]. http://larch.cs.iastate.edu/ComS541Fall97/hw-pages/paradigms/major.html
[5]. C how to program by H.M. Deitel and P.J.Deitel, 3rd ed: Prentice hall(2001).

Lesson 3: Program development life cycle

3.1. Introduction
In our previous lesson, we discussed various programming paradigms. In our today’s
lesson we will be discussing program development life cycle and then summarize this
into three phases often referred to problem solving phases.
3.2. Lesson objectives
By the end of this lesson the learner will be able to:
▪ Identify and describe activities of program development life cycle
▪ Group the activities of program development cycle into problem solving phases
3.3. Lesson outline
This lesson is organized as follows:
3.1. Introduction
3.2. Lesson objectives
3.3. Lesson outline
3.4. Program development life cycle
3.5. Problem solving phases
3.6. Structured programming concepts
3.7. Program design
3.8. Revision questions
3.9. Summary
3.10. Suggested reading
3.4. Program development life cycle
A program is a set of instructions that a computer can read and execute. The
programs are written to solve problems or perform a task on a computer. Often
a program is known as a project, application or a solution. The programmers
plan their programs using a sequence of steps called program development life
cycle. This cycle provides a set of phases and steps that are followed by developers
to define, design, develop and maintain a computer program.
[i]. Analysis and specification
[ii]. Design the program

Prepared By Dorothy Mutua 14


[iii]. Design the interface
[iv]. Code the program
[v]. Test the program
[vi]. Document the program
[vii]. Maintain the program
Description of steps involved in program development life cycle
[i].Analyze and specification: Define the problem. Understand the inputs, the
required processing and expected output.
[ii]. Design the program: Plan the solution to the problem. Then, define the
logical sequence of precise steps to solve the problem (Algorithm).The logic
plan can be developed using the three methods: flowcharts, pseudo codes
e.t.c.
[iii]. Design the interface: Determine how the inputs will be obtained and how
the output will be displayed.
[iv]. Code: Translate the algorithm into programming language. In this stage
the programmer will use the algorithm in step [ii] and a given programming
language.
[v]. Test and debug: Locate and remove any errors in the program. Testing is
the process of finding errors in the programs. Debugging is the process of
correcting errors that are found. An error in a program is called a bug.
[vi]. Documentation: Organize all the material that describes the program.i.e
allow another person at a later date to understand the program. Can be
internal documentation (e.g. comments) or user manuals.
[vii]. Maintain the program: This involves training and supporting users as
well as correcting any errors that may arise in future. When the cost of
maintenance exceeds the benefits of the system, the cycle begins again.
3.5. Programming process
There are three phases in programming process
[a]. Problem solving phase
[b]. Implementation phase
[c].Maintenance phase
The following is the description of the programming process or problem solving
stages.
[a]. Problem solving phase
This phase has three stages
[i]. Analysis and specification stage: In this stage programmers must understand
(define) the problem and what the solution must do.
[ii]. General solution (algorithm): Programmers must specify the required data
types and the logical sequence of steps that solve the problem.
[iii]. Verify: Programmers must follow the steps exactly to see if the solution
really does solve the problem.
[b]. Implementation phase
There are three stages in this phase:
[i]. Concrete solution (program): Translate the algorithm (general solution) into a
program using a programming language.

Prepared By Dorothy Mutua 15


[ii]. Test: Allow the computer follow the instructions, then manually check the
results. If errors are found analyze the program and the algorithm to
determine the source of the error and make corrections.
[iii]. Documentation: Add comments in the code and also create documentation
of the whole system.
[c].Maintenance phase
There are two activities involved in this phase:
[i]. Use: Use the program to solve the problem.
[ii]. Maintain: Modify the program to meet changing requirements or correct
any errors that show up while using the program.
3.6. Structured programming concepts
Structured programming can be defined as follows:
▪ Programming without the use of GOTO.
▪ A method of designing computer system components and their relationships to
minimize complexity.
Structured programming minimizes complexity in three ways:
[i]. Using top down analysis for solving the problem.
[ii]. Modularization of program structure and organization.
[iii]. Uses structured code for the individual modules.
The above strategies for minimizing complexity can be described as follows:
[i]. Top down analysis for problem solving
A program is written to tell the computer what to do. The job you want the computer
to do is referred to as a problem. Before you tell the computer what to do, you must
solve the problem yourself, this is called problem analysis. For big problems,
developing a solution can be very complicated. As a result, using top down approach
helps the programmer in the entire process. The problem is subdivided into smaller
tasks or parts. This simplifies the complexity of the problem.
[ii]. Modular programming for program structure
Programs require many instructions for the computer. Modular programming is a
method used to organize these instructions. Large programs are broken down into
separate, smaller sections called modules, subroutines or subprograms. Each module
has a specific job to do and is relatively easy to write. Thus modular programming
simplifies the task of programming by making use of highly structured organizational
plan.
[iii]. Structured coding for each module.
Programs are divided into modules and the modules can be subdivided further. Each
module will consist of instructions and these instructions are organized for execution
in some pattern using various control structures. The control structure will represent
a unique pattern of execution for a specific set of instructions. It determines the order
in which that set of instructions is executed. The component statements within a
specific control structure are executed sequentially, selectively or repetitively. Using
structured code reduces program complexity because the program instructions are
organized into distinct patterns.
3.7. Program design
[a]. Analysis and specification stage:

Prepared By Dorothy Mutua 16


Programmers must understand (define) the problem and what the solution must do.
Computer programming involves solving problems. Decompose the problem
description. This is done using syntactic analysis.
i). Identify all the nouns in the sentence(s). Nouns identify descriptions of
information that you will either identify or keep track of(inputs and outputs).
ii). Identify all the verbs –these identify the actions that the program will perform
(processing).
iii). Link the inputs, processes and outputs.
iv). Use external knowledge to complete the solution e.g. formulating an equation.
[b]. General solution (algorithm):
Programmers must specify the required data types and the logical sequence of
steps that solve the problem. An algorithm is a finite sequence of steps for
accomplishing some computational task.
Characteristics of algorithms
A good algorithm must satisfy the following characteristics
[i]. Ordered: The steps must be properly ordered and logical
[ii]. Concise: The steps must be unambiguous
[iii]. Finiteness: The steps must be finite : start and end at some point.
[iv]. Input: The inputs must be clearly specified
[v]. Output: The expected results must be specified
[vi]. Effectiveness: The steps specified must be doable.
How develop an algorithm
To develop an algorithm the following steps must are necessary:
[i]. Define the problem to solve.
[ii]. Specify the inputs clearly
[iii]. Specify the expected outputs.
[iv]. Describe the steps needed to convert or manipulate inputs to produce
outputs (Processing).
[v]. Test the algorithm: Choose data sets and verify the algorithm works.
Tools for designing algorithms
To develop an algorithm a number of tools can be used:
[i]. Flowchart
[ii]. Pseudo code
[iii]. Top down chart/Hierarchy charts
[iv]. Decision tables

Flowchart
This is a graphical representation of the logical steps needed to carry out a task. Makes
use of symbols to represent the steps.

Prepared By Dorothy Mutua 17


Advantages of flowchart
▪ Flowcharts are a better way of communicating the logic of the system.
▪ With the help of a flowchart, problem can be analyzed easily.
▪ They serve as a good program documentation.
▪ They help in program debugging.
Disadvantages of flowchart
▪ For a complex problem, the flowchart becomes complex and clumsy.
▪ If alterations are required, the flowchart may require redrawing completely.
▪ The flow chart symbols cannot be typed and so reproduction of a flowchart
becomes difficulty.
Guidelines for drawing a flowchart
▪ List all necessary requirements in a logical order.
▪ The flowchart must be neat, clear and easy to follow.
▪ The flowchart is read from left to right and top to bottom.
▪ A process symbol can have only one flow line coming out of it.
▪ For a decision symbol, only one flow line can enter it but multiple lines can
leave it to denote possible answers.
▪ Terminal symbols can only have one flow line in conjunction with them.
Example: Using a flowchart design an algorithm to test if temperature is
greater than 32 degree Celsius. If it exceeds 32 then print “cover tomatoes”
otherwise “uncover tomatoes”.

Pseudo code
▪ It is a representation an algorithm using natural language statements e.g.
structured English. It describes the entire logic of the algorithm.
▪ It is not an executable code.
Guidelines for developing algorithm using pseudo code:
▪ Identify the inputs, processes and outputs
▪ Use natural language e.g. English.

Prepared By Dorothy Mutua 18


▪ Present the statements in clear details.
▪ The variables must be descriptive.
▪ Each activity appears in a single line
▪ The steps must be numbered.
Advantages of pseudo code
▪ Reduced complexity
▪ Easy to understand
▪ Easy to translate to code
▪ No special symbols required
▪ Saves time spent during coding, testing and debugging.
Disadvantages of pseudo code
▪ Can be ambiguous because it uses natural language.
▪ Pseudo code has few rules and it is hard to standardize.
▪ The pseudo code focuses on details than the bigger picture of the algorithm.
3.8. Revision questions
a) Compare and contrast flowchart and pseudo code as algorithm development
tools.
b) Describe the THREE phases of program development typical in structured
programming.
c) Identify the flow chart symbols in each case.
i). Compare x and y integer values
ii). Enter value of x and y
iii). Multiply value of x with 5 and subtract 4 from the product
iv). Display the result of 5x-4
3.9. Summary
In this lesson you have learnt that program development life cycle is a framework that
describes the activities performed during program development process. You have
also learnt that these activities can be placed into three categories referred to as
programming process: Problem solving phase; Implementation phase and
maintenance phase. You have also learnt about problem solving approaches used in
structured programming. Finally you have learnt how to design a program using
flowchart and pseudo code.
3.10. Suggested reading
[1].An introduction to programming by Wu Thomas, Norman and Theodore: McGrill
(1997).
[2]. C programming language by Brian W. Kernighan, Dennis Ritchie, 2nd ed:
prentice hall(2003).
[3]. C how to program by H.M. Deitel and P.J.Deitel, 3rd ed: Prentice hall(2001).

Lesson 4: Programming languages and programming tools

Prepared By Dorothy Mutua 19


4.1. Introduction
In our previous lesson, we discussed program development life cycle. In this lesson we
will be focusing on programming languages: Features and characters and their
evolution. Finally, we will look at various programming tools.
4.2. Lesson objectives:
By the end of this lesson, the learner will be able to:
▪ Describe various features and characteristics of a programming language.
▪ Discuss various ways of classifying programming languages
▪ Discuss strengths and weaknesses of various languages
4.3. Lesson outline.
This lesson is organized as follows:
4.1. Introduction
4.2. Lesson objectives
4.3. Lesson outline
4.4. Programming language
4.5. Characteristics of a good programming language
4.6. Generations of programming languages
4.7. Classification of programming languages
4.8. Programming tools
4.9. Revisions
4.10. Summary
4.11. Suggested reading
4.4. Programming language
This is a standardized communication technique for expressing instructions to a
computer.
There are three important aspects of any programming language.
[i]. Syntax: This is the required grammar and punctuation of the language.
Compile-time errors are syntax errors.
[ii]. Semantics: This is all about meaning. What the statements do and what the
programs do. Logic errors are semantic errors
[iii]. Pragmatics: How people use the program.
4.5. Characteristics of a good programming language
The characteristics of the programming languages are:
[i]. Readability: Must be easy to understand.
[ii]. Writability: Must be easy to write.
[iii]. Cost: Normally affected by influenced by creation, execution and
maintenance.
[iv]. Portability: The ease with which programs can be moved from one
implementation to another.
[v]. Generality: The applicability to a wide range of applications
[vi]. Well-definedness : The completeness and precision of the language’s
official definition
[vii]. Expressivity : A set of relatively convenient ways of specifying
operations. Strength and number of operators and predefined functions
4.6. Generations of programming languages
[a]. Low level language (LLL)

Prepared By Dorothy Mutua 20


This is a programming language used to write hardware programs. It is the
fundamental language of the computer’s processor. All programs are converted into
machine language before they can be executed. It consists of combination of 0’s and
1’s that represent high and low electrical voltage. They are far from human languages.
They are faster to execute because they do not require translation. They are also
difficult to modify. They are not portable (machine specific). They are classified into
first and second generation programming languages.
[i]. First generation programming language(1GL)
They represent the very early computer languages that consisted of 1’s and 0s.The
actual language that the computer understands. Example Machine language.
Machine language- A low level programming language where computation is based
on binary numbers (0s and 1s). The machine understands this language by virtue of
it’s circuitry design.
There is no translation required.
Advantages
▪ Run fast because no translation
▪ Directly understandable by the computer
Disadvantages
▪ Difficult to code
▪ Not easy to understand
▪ Not easy to debug
▪ Not portable
[ii]. Second generation programming language(2GL)
They represent a step up from the first generation languages. They allow the use of
symbolic names instead of numbers (0s and 1s).They are known as assembly
languages.
Assembly language- The code written in assembly language must be converted into
machine language (1GL). They use alphabetic and numeric symbols. They also require
translators called assemblers to translate the code into machine language.
Advantages
▪ Easier to understand and code
▪ Easier to debug and modify
Disadvantages
▪ Not portable
▪ Error correction is tedious
▪ Slow to run since they need translation.
[b]. High level programming languages
They allow the specification of the problem solution in terms closer to those used by
human beings. These languages were designed to make programming easier, less
error-prone and to remove the programmer from having to know the details of the
internal structure of a particular computer. This language is used in third, fourth and
fifth generations generation.
[i]. Third generation languages (3GL)
These languages use words and commands instead of just symbols. Their syntax was
therefore easier to understand. These languages are portable meaning that the object
code created for one type of system can be translated for use on different type of

Prepared By Dorothy Mutua 21


system. Examples of languages at this generation were FORTAN, COBOL, BASIC,
Pascal, c, active, c++, java and JavaScript.
Advantages
▪ Easier to understand and code since programmers do not need to remember
operation codes and instructions while writing the program.
▪ Instructions used can be specified in English like statements.
▪ They are highly portable.
▪ They are easy to develop and learn.
Disadvantages
▪ All the errors must be rectified before compiling.
▪ Execution is slow
▪ Requires more system memory
[ii]. Fourth generation language (4GL)
These languages are even easier to use than 3GLs.They may use text-based
environment like 3GL or may allow the programmer to work in a visual environment
using graphical tools.
▪ Visual basic
▪ SQL
▪ Coldfusion
Advantages
▪ They are easier to learn and use.
▪ Require less time, cost and effort to develop applications
▪ They are efficient to use with data since they are used in implementing various
database concepts.
▪ They have less number of instructions.
▪ Are highly portable.
Disadvantages
▪ Execution is slow
▪ Requires more system memory
[iii]. Fifth generation language (5GL)
Fifth generation programming languages are programming languages that allow
programmers to solve problems by defining certain constraints as opposed to writing
an algorithm. This means that they can be used to solve problems without a
programmer. Because of this reason, 5GL are used in AI (Artificial Intelligence)
research. Many constraint-based languages, logic programming languages and some
of the declarative languages are identified as 5GL. Prolog and Lisp are the most widely
used 5GL for AI applications.
Advantages
▪ Allow users to communicate with the computer in a simple and easy manner.
▪ Programmers can use normal English words while interacting with the system.
▪ Can be used to query the database.
Disadvantages
▪ Not very popular except in academic circles

Prepared By Dorothy Mutua 22


4.7. Classifications of programming languages.
There are several ways of classifying programming languages
[a]. By abstraction level: Some languages can be low level while others are high
level.

[b]. By application domain-Languages can be classified based on areas of


application.

[c].By generality: some languages have variety of features and so can be used for
several purposes while others have limited features and so can only be used for
a given purpose.

Prepared By Dorothy Mutua 23


[d]. By implementation method: Some languages require interpreter so the
program can be executed directly statement by statement. Compiled programs
require translation into lower level machine language.

[e]. By paradigm- some languages support a given programming paradigm


while others can support more than one paradigm.

4.8. Programming tools


[a]. Language translators
A translator inputs and then converts a source program into an object or target
program. The source program is written in a source language while object program
belongs to an object language. Examples of language translators are assemblers,
compilers and interpreters.
[i]. Assemblers: These are programs used to translate an assembly language program
into machine language program.
[ii]. Compilers: A compiler is a program that can read a program in one language
(the source language) and translate it into an equivalent program in another
language - the target language. It goes through the entire program and then
translates the entire program into machine codes. An important role of the
compiler is to report any errors in the source program that it detects during the
translation process. The time of conversion from source program into object
program is called compile time. The object program is executed at run time.

Compilation process.
[iii]. Interpreter: An interpreter is a program which translates statements of a
program into a machine code. It processes an internal form of the source program

Prepared By Dorothy Mutua 24


and data at the same time (at run time). No object program is generated. An
interpreter usually gives better error diagnostics than a compiler, because it
executes the source program statement by statement.

Interpretive process.

[b]. Editors
These are programs used to enter and modify program in text form. Text editors
format the spacing between words for legibility. They are ideal for structured
languages. Examples Notepad and Wordpad for windows. Unix / Linux require ed, vi
and emacs.
[c].Loaders
These are programs which load machine codes of a program into the system memory.
This program brings the executable file residing in the disk into the memory and
starts it running.
[d]. Linkers
A program which links functions to the libraries for high level languages. It also
combines modules into a program for execution. It searches the program to find
library routines used by the program e.g. printf(). It then determines the memory
locations that code from each module will occupy and relocates its instructions by
adjusting absolute references. It finally resolves references among the files.
[e]. Debuggers
Programs which aid in tracing and debugging a program during its execution.
Program language translation process

4.9. Revision questions.

Prepared By Dorothy Mutua 25


[a]. Explain why you might want to write a program in a machine independent
language instead of a machine dependent language.
[b]. Explain the role of each of the following translator programs.
[i]. Compiler
[ii]. Assembler
[c].Using specific examples describe programming languages under the following
generations.
[i]. First generation
[ii]. Second generation
[iii]. Third generation
[iv]. Fourth generation
[v]. Fifth generation
[d]. Discuss the following programming paradigms:
[i]. Imperative paradigm
[ii]. Logical paradigm
[iii]. Functional paradigm
[iv]. Object oriented paradigm
4.10. Summary
In this lesson we have discussed programming languages: their characteristics and
features and classified them into different categories based on abstraction,
application, implementation, paradigms e.t.c. Finally we looked at various
programming tools: language translators, editors, debuggers,loaders, linkers e.t.c.
4.11. Suggested reading
[1].An introduction to programming by Wu Thomas, Norman and Theodore: McGrill
(1997).
[2]. C programming language by Brian W. Kernighan, Dennis Ritchie, 2nd ed:
prentice hall(2003).
[3]. C how to program by H.M. Deitel and P.J.Deitel, 3rd ed: Prentice hall(2001).

Lesson 5: Writing and compiling a program

5.1. Introduction
In our last lesson we discussed about programming languages and programming tools. In
this lesson, you will be introduced to programming using c. The programming process
begins with the creation of a text file which contains the statements of the program in a
programming language. (This source file is a text file, usually ASCII, which can be
produced with a text editor, such as Windows notepad, or in an Integrated Design
Environment.) This source file is then processed by a special program called a compiler.
Each programming language has its own compiler, and the compiler must be matched to
the hardware and operating system that the new program will run on.
5.2. Objective of the lesson
By the end of this lesson the learner will be able to:
▪ Describe the procedure of writing, compiling and building a program in c.
▪ Describe the general structure of a c program.
▪ Describe program errors.
5.3. Lesson outline

Prepared By Dorothy Mutua 26


This lesson is structured as follows;
5.1. Introduction
5.2. Lesson objectives
5.3. Lesson outline
5.4. Types of c files
5.5. Preprocessors
5.6. Steps for writing and compiling c program
5.7. Program structure
5.8. Testing vs debugging
5.9. Types of errors
5.10. Revision questions
5.11. Summary
5.12. Suggested reading
5.4. Types of files
Writing and compiling C programs requires four kinds of files:
[i]. Source code files. These files contain function definitions, and have names
which end in .c extension.
[ii]. Header files. These files contain function declarations (function prototypes)
and various preprocessor statements. They are used to allow source code files to
access externally-defined functions. Header files end in .h extension.
[iii]. Object files. These files are produced as the output of the compiler. They consist
of function definitions in binary form, but they are not executable by themselves.
Object files often end in .obj.
[iv]. Binary executables. These are files produced as the output of a program called a
linker. The linker links together a number of object files to produce a binary file
which can be directly execute.
5.5. Preprocessors
The first step of the compile process is a special preprocessor program. The preprocessor
program reads the source file as text, and produces another text file as output. The
preprocessor makes substitutions of one character string for another, substitutes the text
of a header file for #include statements, and even expands some function calls into other
text. The substitutions can be conditional. The output of the preprocessor is a text file
which does not contain any preprocessor statements, which is ready to be processed by
the C compiler itself. Examples of preprocessors.
#define : Substitutes a preprocessor macro.
#include : Inserts a particular header from another file.
#undef: Undefines a preprocessor macro.
#ifdef: Returns true if this macro is defined.
5.6. Steps for writing and compiling c program
Developing a program in c involves four major steps:
Step 1: Writing the code
Use an editor to write the source code. Save the source code files with .c
extension .For example, myprog.c, database.c, and so on.
Step 2: Compile the source code.

Prepared By Dorothy Mutua 27


Compile the program using a compiler. If the compiler doesn't find any errors
in the program, it produces an object file. The compiler produces object files
with an .obj extension and the same name as the source code file for example,
myprog.c compiles to myprog.obj). If the compiler finds errors, it reports them.
If errors are reported return to step 1 to make corrections in the source code.
Step 3: Linking the program
Link the program using a linker. If no errors occur, the linker produces an
executable program located in a disk file with an .exe extension and the same
name as the object file for example; myprog.obj is linked to create myprog.exe.
If errors are reported return to step 1 to make corrections in the source code.
Step 4: Execute the program.
Test the program to determine whether it functions properly. If not, start
again with step 1 and make modifications and additions to the source code.

Flow chart: Writing and compiling c program

Prepared By Dorothy Mutua 28


5.7. Program structure in c
A program in c has the following components:

[a]. #include <stdio.h> : This is the first line of the program. It is a preprocessor
command which directs the compiler to include stdio.h file before actual
compilation.
[b]. main(): The main function is where program execution begins.
[c].Comment(s): Any statement enclosed by /*...*/ will be ignored by the compiler
and is put to add additional comments in the program.
[d]. {} : The opening and closing braces are used to enclose a function block in this
case main.
[e]. printf(...) : This library function available in C which prints(outputs) string on
the screen.
[f]. Scanf(…): This library function available in C which takes(input) from the user e.g.
through the keyboard.
[g]. Statement(s): It is a complete instruction that directs the computer to carry
out some
[h]. task. In c statements always end with a semicolon (except for preprocessor
directives such as #define and #include).
[i]. return 0; terminates main()function and returns the value 0 to the operating
system.
Example:

Prepared By Dorothy Mutua 29


/*Program to add two numbers and display the sum*/
#include<stdio.h>
int main()
{
int a,b,sum; /*Declare variable*/
printf(“Please enter the value of a: \n”);
scanf(“%d”,&a);
printf(“Please enter the value of b: \n”);
scanf(“%d”,&b);
sum=a+b;
printf(“The sum of %d and %d is %d. \n”,a,b,sum);
return 0;
}
5.8. Testing and debugging
Testing is a process of finding defects in the code or finding if the program does what
it is supposed to do. Debugging is the process of finding and removing a specific
bug(s)/error(s) from the program. Testing process can be manual or automated but
debugging is always manual.
Example: Debugging
The program tre.c is being compiled. During compilation an error was detected and so
the object file could not be formed. The error is in line 9 , a syntax error which is a
missing ;

Example: Testing
Even after debugging, the program must be run and different values of a and b entered
to see if it actually calculates the sum as expected.
See the output when testing
Please the enter value of a:
3
Please enter the value of b:
45

Prepared By Dorothy Mutua 30


The sum of 3 and 45 is 48.
Press any key to continue
5.9. Types of errors
In programming, an error also known as a bug is a mistake or omission that may
prevent the program from compiling and running correctly as per the expectation of
the programmer.
There are three types of errors in programming:
[i]. Runtime Errors
[ii]. Compile Errors
[iii]. Logical Errors

[a]. Runtime Errors


These are errors that occur during the execution of a program. Generally these errors
occur due to some illegal operation performed in the program. These errors may stop
program execution.
Some illegal operations that may produce runtime errors are:
● Dividing a number by zero
● Trying to open a nonexistent file
● Lack of free memory space
[b]. Compile Errors
Compile errors are those errors that occur at the time of compilation of the program.
These errors may be further classified as:
[i]. Syntax Errors
These are errors detected during compile time when the rules of the programming
language are not followed.
Example
int a, b:

The above statement in a c program will produce syntax error as the statement is
terminated with: rather than;
[ii]. Semantic Errors
These are errors reported by the compiler when the statements written in the program
are not meaningful to the compiler. Usually arise from wrongly typed expressions and
formulas.
Example
a+b=c;
In the above statement we are trying to assign value of c in the value obtained by
summation of a and b which has no meaning in a program in c. The correct statement
will be
c=a+b;
[iii]. Linker errors
These are errors reported when an executable file of the program cannot be generated.
This may due to wrong function prototyping, incorrect header files. These errors are
not easy to detect.
#include<math>

Prepared By Dorothy Mutua 31


Math file cannot be located in any directory and so the program will throw an
error.
[c].Logical Errors
These are the errors in the output of the program. The presence of logical errors leads
to undesired or incorrect output and are caused due to error in the logic applied in the
program to produce the desired output. These errors may not be detected by the
compiler and so the programmer has to check the entire coding of the program line by
line.
5.10. Revision questions
a) Explain the possible causes of the following errors in a program.
i). Syntax error
ii). Semantic error
iii). Logic error
iv). Linker error.
b) Study the c program below, identify and correct any errors noted.
#include <stdio.h>
main()
{
float x y, sum;
printf(Enter the value of x:\n");
scanf("%d",x);
printf("Enter the value of y:\n");
scanf("%d",y);
x+y=sum;
printf("The sum of x and y is: %d\n",sum);

}
c) A program errors can be syntax, logic , linker or semantic errors. Classify the
following errors.
i). An indefinite loop
ii). Misspelling keywords
iii). Dividing a number zero
iv). Using undeclared variable.
v). Misspelling function name.
d) Describe the following files as used in a c program.
i). Source code file
ii). Object file
iii). Binary executable file
iv). Header files.
[4 Marks]
e) Describe the process of writing and compiling a c program. [4
Marks]
f) Discuss the following program errors, give an example in each case.
i). Logical error
ii). Run time error

Prepared By Dorothy Mutua 32


iii). Compile error.
[6 Marks]
g) Briefly explain the following files which were observed when compiling a
program in c.
i). hello.c
ii). hello.obj or hello.o
iii). hello.exe
[3 Marks]
h) When compiling a program in c, Susan, a SEM II Engineering student in PIU
observed an error thrown by the compiler as follows:
nice.c(8) : error C2143: syntax error : missing ';' before ':'

Identify and explain all the information provided in this error message. [4
Mark]
5.11. Summary
In this lesson we have discussed how we can write, compile, debug, run and test a c
program.
We have also describe important files in c. Finally we have identified and discussed
common program errors.
5.12. Suggested reading
[1].An introduction to programming by Wu Thomas, Norman and Theodore: McGrill
(1997).
[2]. C programming language by Brian W. Kernighan, Dennis Ritchie, 2nd ed:
prentice hall(2003).
[3]. C how to program by H.M. Deitel and P.J.Deitel, 3rd ed: Prentice hall(2001).

Lesson 6: Variables and data types

6.1. Introduction
In our last lesson we discussed how to write, compile, build and debug a program in c.
We also discussed the general structure of a c program. In this lesson you will learn
about the character sets and keywords used in c as well as data types, variables,
constants, qualifiers, statements and expressions in c.
6.2. Lesson objectives
By the end of this lesson, you will be expected to:
▪ Identify various characters used in c program

Prepared By Dorothy Mutua 33


▪ Declare and use variables appropriately
▪ Describe various basic data types in c
▪ Describe various qualifiers used to modify data types
▪ Define and use a constants in a program
▪ Describe types of statements and expressions in c
6.3. Lesson outline
This lesson is organized as follows:
6.1. Introduction
6.2. Lesson objectives
6.3. Lesson outline
6.4. Character sets
6.5. Keywords
6.6. Variables
6.7. Data types
6.8. Qualifiers
6.9. Constants
6.10. Statements
6.11. Expressions
6.12. Revision questions
6.13. Summary
6.14. Suggested reading
6.4. Character set
This consists of a set of alphabets, letters, white spaces and some special characters
that are valid in C language.
i). Alphabets:
Uppercase: A B C .................................................................................................. X Y
Z
Lowercase: a b c .................................................................................................... x y z
ii). Digits:
0123456 89
iii). Special Characters:
, < . ( ; $ : % [] # ? ‘ & { “ ^ ! / * | - ~ +
> ) }
iv). White space Characters:
White space refers to spaces, horizontal tabs, vertical tabs, and blank lines in your
source code.
6.5. Keywords:
These are the reserved words used in programming. Each keyword has fixed meaning
that cannot be changed by user. C programming is case sensitive and all keywords
must be written in lowercase.
Auto Double int Struct
Break Else long Switch
Case Enum register Typedef
Char Extern return Union
Continu For signed Void
e

Prepared By Dorothy Mutua 34


Do If static While
Default Goto sizeof Volatile
Const Float short unsigned
6.6. Variables
A variable is named memory location in computer memory used to store data. Each
variable should be given a unique name called identifier. Variable names are symbolic
representation of a memory location.
Examples of valid variable names
pay, age, gender etc.
Rules for writing a variable name in c
[i]. A variable can be composed of letters, digits and underscore '_' .
[ii]. The first character of variable should be a letter.
[iii]. Variable names must be meaningful, easy to remember and work with.
[iv]. The variable names should not match a reserved keyword.
Variable declarations
Variable declaration is a statement that tells the compiler the variables name, and
what data type it is. Each variable has a specific type, which determines:
[i]. The size and layout of the variable's memory;
[ii]. The range of values that can be stored within that memory;
[iii]. The set of operations that can be applied to the variable.
The variables must be declared before they are used. A declaration specifies a type, and
contains a list of one or more variables:
Syntax
Type variable list;
The type must be a valid C data type including char, int, float, double, or any user
defined data type etc. The variable_list may consist of one or more identifier names
separated by commas. Examples:
int x,y,z;
float a,b;
char e;

Initialization of variables
Variables can be initialized (assigned an initial value) in their declaration. The
initializer consists of an equal sign followed by a constant expression as follows:
Syntax
Type variable name= value;
Variables can be initialized in two ways:
[i]. Declare and initialize the variable(s).
int x=8;
char d=’a’;
[ii]. Declare and initialize the variable(s) in separate statements.
int x;
char d;
d=’A’
x=8;

Prepared By Dorothy Mutua 35


Variable scope
A scope is a region of the program. There are three places where variables can be
declared:
▪ Inside a function or a block e.g. local variables,
▪ In the definition of function parameters e.g. formal parameters.
▪ Outside of all functions e.g. global variables.
[i]. Local Variables:
These are variables that are declared inside a function or block. They can be used only
by statements that are inside that function or block of code. Local variables are not
known to functions outside their own.
Examples
#include <stdio.h>
using namespace std;
void main ()
{
int a, b, c; //local variables declared
// actual initialization
a = 10;
b = 20;
c = a + b;
printf(“%d”, c);
}
[ii]. Global Variables:
These are variables defined outside of all the functions, usually on top of the program.
The global variables will hold their value throughout the lifetime of the program.
A global variable can be accessed by any function. A global variable is thus available for
use throughout the entire program after its declaration.
Example
#include <stdio.h>
int a,b,c; //global variable declaration
a=1;
b=2;
int main ()
{
c = a + b;
printf(“The value of c is %d\n”,c);
return 0;
}
A program can have same name for local and global variables but value of local
variable inside a function will take preference.
For example:
#include <stdio.h>
int a = 20; //declare and initialize global variable
int main ()
{
int a = 10; // Local variable declaration and initialization:
printf(“The value of a %d\n”,a);
return 0;

Prepared By Dorothy Mutua 36


}

Initializing Local and Global Variables:


When a local variable is defined, it is not initialized by the system, you must initialize
it yourself. Global variables are initialized automatically by the system when you
define them as follows:
Data Type Initializ
er
int 0
char '\0'
float 0
double 0
pointer NULL
It is a good programming practice to initialize variables properly otherwise, sometime
program would produce unexpected result.
6.7. Data Types
Data types are the keywords, which are used for assigning a type to a variable. The
type of a variable determines how much space it occupies in storage and how the bit
pattern stored is interpreted. A variable has four characteristics.
Characteristic Description
Identifier The name of the variable used to reference data in program code
Type The data type of the variable
Value The data value assigned to the memory location
Address The address assigned to a variable, which points to a memory cell location.
In c data types can be classified into two broad categories:
i). Basic Data Types
▪ Integer types
▪ Floating Type
▪ Char type
ii). Derived Data Types
▪ Arrays
▪ Pointers
▪ Structures
▪ Enumeration
[a]. Integer Types
An integer is a whole number that can be positive, negative, or zero.
Example
int x,y; //Declaration of integer type
x=7; //Initialization of integer type
The table below gives detail about standard integer types with its storage sizes and
value ranges:
Type Storage size Value range
Int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767

Prepared By Dorothy Mutua 37


unsigned 2 bytes 0 to 65,535
short
Long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
Following is an example to get the size of int type on any machine:
#include <stdio.h>
int main()
{
printf("Storage size for int : %d \n", sizeof(int));
return 0;
}

[b]. Floating-Point Types

A float-point is used to represent real numbers. That is numbers that can consist of
the integer part and decimal part. The double data type is used to define big floating
point numbers. It reserves twice the storage for the number.
Example
float x, y; //Declaration of float type
y=3.45; //Initialization of float variable

Following table gives detail about standard float-point types with storage sizes and
value ranges and their precision:
Type Storage Value range Precision
size
Float 4 byte 1.2E-38 to 3.4E+38 6 decimal
places
Double 8 byte 2.3E-308 to 15 decimal
1.7E+308 places
long 10 byte 3.4E-4932 to 19 decimal
doub 1.1E+4932 places
le

[c].Char data type


Used to represent data of character type. The keyword char is used to declare character
type variables. The character data type consists of ASCII characters. Each character is
given a specific value.
char a,b,d;
a=’A’;
6.8. Qualifiers
This is a keyword used to alter the meaning of base data types to yield a new data type.
[i]. Size qualifiers:
Size qualifiers alter the size of basic data type. The keywords long and short.
long int i;
The size of int is either 2 bytes or 4 bytes but, when long keyword is used, that variable
will be either 4 bytes of 8 bytes.
[ii]. Sign qualifiers:

Prepared By Dorothy Mutua 38


Determine whether a variable can hold positive value, negative value or both values.
Keywords signed and unsigned are used for sign qualifiers.
unsigned int a;
Unsigned variable can hold zero and positive values only.
It is not necessary to define variable using keyword signed because; a variable is signed by
default. Sign qualifiers can be applied to only int and char data types.
[iii]. Constant qualifiers
Constant qualifiers can be declared with keyword const. An object declared by const
cannot be modified.
const int p=20;
The value of p cannot be changed in the program.
[iv]. Volatile qualifiers:
A variable should be declared volatile whenever its value can be changed by some external
sources outside program. Keyword volatile is used to indicate volatile variable.
6.9. Constants
A constant is a data storage location used by a program. Unlike a variable, the value
stored in a constant can’t be changed during program execution. The constants refer to
fixed values that the program may not alter during its execution. C has two types of
constants, each with its own specific uses:
a) Literal Constants
b) Symbolic Constants
Literal constants: A literal constant is a value that is typed directly into the source code
wherever it is needed. Literal constants can be of any of the basic data types like:
[i]. integer constant
[ii]. a floating constant,
[iii]. a character constant
[iv]. a string literal
[v]. enumeration constants.
[a]. Integer literals
An integer literal can be a decimal (base10), octal (base 8), or hexadecimal(base 16)
constant.
[i]. Decimal digits: 0 1 2 3 4 5 6 7 8 9
[ii]. Octal digits: 0 1 2 3 4 5 6 7
[iii]. Hexadecimal digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.
Examples:
[i]. Decimal constants: 0, -4, 12 etc
[ii]. Octal constants: 021, 077, 033 etc
[iii]. Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
[b]. Floating-point literals
A floating-point literal has an integer part, a decimal point, a fractional part, and
an exponent part.
For example:
[i]. -2.0
[ii]. 0.0000234
[iii]. -0.22E-5
NB: E-5 represents 10-5. Thus, -0.22E-5 = -0.0000022.

Prepared By Dorothy Mutua 39


[c].Character constants
Character literals are enclosed in single quotes e.g., 'x' and can be stored in a simple
variable of char type. A character literal can be a plain character (e.g., 'x').
Examples of character constants:
[i]. Escape sequence: Usually preceded by backslash character(\).
[ii]. Conversion format specifiers: Usually preceded by %d.
Escape sequence characters
Escape Character Meaning
Sequences
\a Alert Produces audible or visible alert
\b Backspace Moves the cursor back one position
\f Form feed Moves the cursor to the first position of the
next page
\n Newline Moves the cursor to the first position of the
next line
\r Return Moves the cursor to the first position of the
current line
\t Horizontal tab Moves the cursor to the next horizontal tabular
position
\v Vertical tab Moves the cursor to the next vertical tabular
position
\\ Backslash Produces a backslash
\' Single quotation mark Produces a single quote
\" Double quotation Produces double quote
mark
\? Question mark Produces question mark
\0 Null character Produces a null character
Conversion format specifiers
Conversion Output
specification
%c Character
%s String of characters
%d Decimal integer
%f Floating point number in decimal notation
%u Unsigned decimal integer
%i Signed integer
String literals
String literals or constants are enclosed in double quotes "". A string contains
characters that are similar to character literals: plain characters, escape sequences,
and universal characters. You can break a long lines into multiple lines using string
literals and separating them using whitespaces.
"Cross, " "co" "ountry"
Enumeration constants
Keyword enum is used to declare enumeration types. For example:
enum days { monday, tuesday, wednesday, Thursday, Friday,
Saturday,sunday};

Prepared By Dorothy Mutua 40


Here, the variable name is days. Monday, tuesday, wednesday,
Thursday,Friday,Saturday and sunday are the enumeration constants having value 0,
1, 2,3,4,5 and 6 respectively by default. You should use enum types any time you need
to represent a fixed set of constants. That includes natural enum types such as the
planets in our solar system and data sets where you know all possible values at
compile time—for example, the choices on a menu, command line flags, and so on.
[a]. Symbolic constant:
This is a constant that is represented by a name (symbol) in the program. Like a literal
constant, a symbolic constant can’t change. Whenever the constant’s value is needed
in the program, then use its name as you would use a variable name. The actual value
of the symbolic constant needs to be entered only once, when it is first defined.
Symbolic constants have two significant advantages over literal constants:
▪ Using symbolic constant, the code is clearer.
▪ When changing the value of the constant you do not have to change every
occurrence in the code you only change it at the declaration area.

Defining symbolic constants


There are two simple ways in to define symbolic constants:
[i]. Using #define preprocessor.
[ii]. Using const keyword.

The #define Preprocessor


Following is the form to use #define preprocessor to define a constant:
#define identifier value
Following example explains it in detail:
#include <stdio.h>
#define PI 3.13 //notice no assignment operator and semicolon
#define RADIUS 5
#define NEWLINE '\n'
int main()
{
float area;
area = PI * RADIUS*RADIUS;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}

The const Keyword


You can use const prefix to declare constants with a specific type as follows:
const type variable = value;
#include <stdio.h>
int main()
{
const float PI= 3.142;
const float RADIUS = 7.0;
const char NEWLINE = '\n';

Prepared By Dorothy Mutua 41


float area;
area = PI * RADIUS*RADIUS;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
NB: It is a good programming practice to define constants in CAPITALS.
6.10. A statement:
It is a complete instruction that directs the computer to carry out some task. In a c
program, statements always end with a semicolon (except for preprocessor
directives such as #define and #include). Some statements may be null. A null
statement is one that doesn’t perform any action. It can be created by placing a
semicolon by itself on a line. A compound statement, also called a block, is a group of
two or more statements enclosed in braces {}.
6.11. Expressions
An expression is anything that evaluates to a numeric value. When an expression
contains multiple operators, the evaluation of the expression depends on operator
precedence.
a=b+c+e*g; //Expressions
[i]. Lvalue : An expression that is an lvalue may appear as either the left-hand or
right-hand side of an assignment.
[ii]. Rvalue : An expression that is an rvalue may appear on the right- but not
left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment.
Numeric literals are rvalues and so may not be assigned and cannot appear on the
left-hand side. Following is a valid statement:
6.12. Revision questions
a) Write appropriate c statements for:
i). Decrementing a variable by 1
ii). Setting up a constant PAYRATE as 1000.00 using define preprocessor.
iii). Test if age is below 18 or above 65
iv). Printing on the screen the number of bytes occupied by a double f
v). Print five blank lines, then print the message “its over”
b) Give reasons why the following identifier names are invalid.
i). 98mark
ii). First name
iii). #sum
iv). Char
c) Describe the four basic data types in c while giving space occupied in memory by
each.
d) Describe two ways of using constants in an expression.
e) Differentiate between local and global variable.
f) Differentiate between rvalue and lvalue expressions.
6.13. Summary
In this lesson you have learnt about character sets and keywords used in c as well as
data types, variables, constants, qualifiers, statements and expressions in c.

Prepared By Dorothy Mutua 42


6.14. Suggested reading
[1].An introduction to programming by Wu Thomas, Norman and Theodore: McGrill
(1997).
[2]. C programming language by Brian W. Kernighan, Dennis Ritchie, 2nd ed:
prentice hall(2003).
[3]. C how to program by H.M. Deitel and P.J.Deitel, 3rd ed: Prentice hall(2001).
[4]. http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
[1].Ditel and P.J.Deitel, 3rd ed: Prentice hall(2001).

Prepared By Dorothy Mutua 43

You might also like