UNIVERSITY OF DAR ES SALAAM
COMPUTING CENTRE
Certificate in Computing and Information
Technology
CTT 04209: PROGRAMMING CONCEPTS
PAGE 2 PROGRAMMING CONCEPTS MANUAL
© 2016 University of Dares Salaam Computing Centre
University Road
P.O Box 35062
Dar es Salaam
Tanzania
Tel: +255 (022) 2410645
Fax: +255 (022) 2410690
Email:
[email protected]Internet: http://www.ucc.co.tz
All trademarks acknowledged. E&OE.
© University of Dar es salaam computing centre. No part of this document may
be copied without written permission from University Computing Centre unless
produced under the terms of a courseware site license agreement with
University Computing Centre.
While all reasonable precautions have been taken in the preparation of this
document, including both technical and non-technical proofing. University of Dar
es salaam computing centre and all staff assume no responsibility for any errors
or omissions. No warranties are made, expressed or implied with regard to these
notes. University of Dar es salaam computing centre shall not be responsible for
any direct, incidental or consequential damages arising from the use of any
material contained in this document. If you find any errors in these training
modules, please inform University of Dar es salaam computing centre. Whilst
every effort is made to eradicate typing or technical mistakes, we apologise for
any errors you may detect. University of Dar es salaam computing centre
manuals are updated on a regular basis, so your feedback is both valued by us
and will help us to maintain the highest possible standards.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 3 PROGRAMMING CONCEPTS MANUAL
Table of Contents .............................................................................................................. Page
Course Introduction ............................................................................................................. 5
COURSE DESCRIPTION ...................................................................................................................................... 5
COURSE OBJECTIVES ........................................................................................................................................ 5
DELIVERY METHODOLOGY ................................................................................................................................. 5
Chapter 1: Understanding Computer Programs ......................................................... 6
1.1 TERMINOLOGIES .......................................................................................................................................... 6
1.2 VARIOUS PROGRAMS .................................................................................................................................. 8
1.3 PROGRAMMING LANGUAGES ....................................................................................................................... 9
1.3.1 Formal Language .............................................................................................................................. 9
1.3.2 Programming Language ................................................................................................................... 9
1.3.3 Levels of Programming Language .................................................................................................. 9
1.3.4 Categories of Programming Language ........................................................................................ 11
1.4 TRANSLATING COMPUTER PROGRAMS ..................................................................................................... 13
1.4.1 Interpreter ......................................................................................................................................... 13
1.4.2 Compiling .......................................................................................................................................... 13
1.5 SOURCE CODE EDITORS ........................................................................................................................... 14
1.6 GOOD COMPUTER PROGRAMS ................................................................................................................. 14
Review questions ................................................................................................................ 17
Chapter 2: Solving Problems Using Computers ........................................................ 18
2.1 W HY USING COMPUTERS TO SOLVE PROBLEMS? ..................................................................................... 18
2.2 STEPS FOR SOLVING PROBLEMS USING COMPUTERS ............................................................................... 18
2.2.1 Problem Definition ........................................................................................................................... 18
2.2.2 Solution Planning ............................................................................................................................ 19
2.2.3 Solution Implementation ................................................................................................................. 19
2.2.4 Solution Testing ............................................................................................................................... 19
2.2.5 Solution Documentation ................................................................................................................. 20
2.3 THINGS TO CONSIDER ................................................................................................................................ 20
Review questions ................................................................................................................ 22
Chapter 3: Computer Algorithms.................................................................................... 23
3.1 W HAT ARE ALGORITHMS?......................................................................................................................... 23
3.2 SCENARIALS FOR COMPUTER PROGRAMS ............................................................................................... 23
3.3 IMPORTANCE OF USING ALGORITHMS....................................................................................................... 23
3.4 PSEUDO-CODE ........................................................................................................................................... 24
3.5 FLOWCHARTS ............................................................................................................................................ 25
3.5.1 Why Programmers use flowcharts? .............................................................................................. 25
3.5.2 Flowchart Standard Symbols ......................................................................................................... 26
3.6 BUILDING FLOWCHARTS ............................................................................................................................ 28
3.6.1 Flowchart - Sequential Structure ................................................................................................... 28
3.6.2 Flowchart - Selection Structure ..................................................................................................... 28
3.6.3 Flowchart - Loop Structure............................................................................................................. 29
3.7 ADVANTAGES AND DISADVANTAGES OF USING FLOWCHARTS ................................................................. 30
3.7.1 Advantages of Flowcharts .............................................................................................................. 30
3.7.2 Disadvantages of Flowcharts ........................................................................................................ 30
3.8 GOOD PRACTICE WHEN DEALING WITH FLOWCHARTS ............................................................................. 30
Rievew questions ................................................................................................................ 31
Chapter 4: Programming Elements and Approaches ............................................... 32
4.1 BASIC PROGRAMMING ELEMENTS ............................................................................................................ 32
4.1.1 Keyword ............................................................................................................................................ 32
4.1.2 Statement ......................................................................................................................................... 32
4.1.3 Variable ............................................................................................................................................. 32
4.1.4 Constant ........................................................................................................................................... 32
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 4 PROGRAMMING CONCEPTS MANUAL
4.1.5 Expression ........................................................................................................................................ 33
4.1.6 Comments ........................................................................................................................................ 33
4.1.7 Assignment....................................................................................................................................... 33
4.2 LIST OF OPERATORS ................................................................................................................................. 34
4.3 PROGRAMMING APPROACHES .................................................................................................................. 34
4.3.1 Procedural Program ........................................................................................................................ 34
4.3.2 Object Oriented Program ............................................................................................................... 35
Review questions ................................................................................................................ 36
Chapter 5: Program Debugging ...................................................................................... 37
5.1 SYNTAX ...................................................................................................................................................... 37
5.2 ERRORS ..................................................................................................................................................... 37
5.2.1 Syntax Errors ................................................................................................................................ 37
5.2.2 Logical Errors ................................................................................................................................ 38
5.2.3 Run-Time Errors ........................................................................................................................... 38
5.4 GOOD PROGRAMMING PRACTICE ............................................................................................................. 38
Review questions ................................................................................................................ 39
Chapter 6: Programming with PHP ................................................................................ 40
6.1 W HAT IS PHP ............................................................................................................................................ 40
6.2 DEALING WITH W AMPSERVER ................................................................................................................... 40
6.2.1 Installing and Testing Wampserver .............................................................................................. 40
6.3 CREATING A PROGRAM WITH PHP ........................................................................................................... 42
6.3.1 PHP Tags and Facts ....................................................................................................................... 42
6.3.2 Statement ......................................................................................................................................... 42
6.3.3 Output Functions ............................................................................................................................. 42
6.3.4 Comments ........................................................................................................................................ 43
6.3.5 Variables ........................................................................................................................................... 43
6.3.5 Output Variables .............................................................................................................................. 44
6.4 W ORKING WITH OPERATORS .................................................................................................................... 44
6.4.1 Arithmetic Operators ....................................................................................................................... 45
6.4.2 Assignment Operators .................................................................................................................... 45
6.4.3 Comparison Operators ................................................................................................................... 45
6.4.4 Increment / Decrement Operators ................................................................................................ 46
6.4.5 Logical Operators ............................................................................................................................ 46
6.4.6 String Operators .............................................................................................................................. 46
6.4.7 Array Operators ............................................................................................................................... 46
6.5 W ORKING WITH DECISION STATEMENTS IN PHP ..................................................................................... 47
6.5.1 IF Statement..................................................................................................................................... 47
6.5.2 IF...ELSE Statement ....................................................................................................................... 47
6.5.3 IF...ELSEIF...Statement ................................................................................................................. 48
6.5.4 SWITCH CASE Statement............................................................................................................. 48
6.6 W ORKING WITH LOOPS IN PHP................................................................................................................. 49
6.6.1 while loop .......................................................................................................................................... 50
6.6.2 do...while loop .................................................................................................................................. 50
6.6.3 for loop .............................................................................................................................................. 51
6.7 DEALING WITH FUNCTIONS IN PHP ........................................................................................................... 52
6.7.1 Create a User Defined Function in PHP ...................................................................................... 52
6.7.2 Function with Arguments ................................................................................................................ 52
6.7.3 Functions - Returning values ....................................................................................................... 53
6.7.4 Variables Scope .............................................................................................................................. 54
Review questions ................................................................................................................ 55
References
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 5 PROGRAMMING CONCEPTS MANUAL
Course Introduction
Course Description
The course introduces students to basic concepts of computer
programming. Students will learn how computer programs are made off,
why computer programs are created, best practices to apply while
programming. In this course, students will also learn how algorithms help
in developing computer programs. Students will be exposed to the main
steps for developing a computer program and will learn how to debug a
computer program. Students will also get introduction to hands on skills
in programming with PHP.
Course Objectives
At the end of the course students should be able to
1. Understand different computer programs.
2. Understand various types of programming languages
3. Use algorithm tools to solve computer based problems
4. Understand computer program structures
5. Understand different ways of developing program
6. Understand computer programming errors and how to deal with
them
7. Use PHP in creating simple program
8. Understand how to configure web servers like Wamp and Xampp
Delivery Methodology
The course will be delivered in form of lecturers in the classroom and in
the Computer lab accordingly. Exercise with real life nature will be
provided during and at the end of the class. The manual is also designed
such that one can follow the course at own time and pace. However,
instructors' consultation will be required from time to time.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 6 PROGRAMMING CONCEPTS MANUAL
Chapter 1: Understanding Computer Programs
Today, most people don't need to know how a computer works. Most
people can simply turn on a computer or a mobile phone and point at
some little graphical object on the display, click a button or swipe a finger
or two, and the computer does something. An example would be to get
Form Four National Examination Results from the net and display it. How
to interact with a computer program is all the average person needs to
know.
But, since you are going to learn how to write computer programs, you
need to know a little bit about how a computer works. Your job will be to
instruct the computer to do things.
1.1 Terminologies
Before we get started with understanding computer programs, we must
be familiar with some common and frequently used terms that will be
appearing more often throughout this manual. However, there are many
scholars whom have written a lot about computer programming,
therefore, definitions of any term can be found varying BUT key points
will always show up to be the same in every single definition. Here are
some of the terms you should be able to understand.
Computer Program
A computer program is a collection of instructions that performs a specific
task when executed by a computer.
In other ways we can say that computer program is an organized list of
instructions that, when executed, causes the computer to behave in a
predetermined manner
Computer Programming
Computer programming involves developing lists of instructions that,
when executed, causes the computer to behave in a predetermined
manner.
You should know that the stuff that these instructions manipulate are
different types of objects, e.g., numbers, words, images, sounds, etc...
Creating a computer program can be like composing music, like designing
a house, like creating lots of stuff. It has been argued that in its current
state it is an art, not engineering.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 7 PROGRAMMING CONCEPTS MANUAL
Source Code
Source code is the language or string of words, numbers, letters and
symbols that a computer programmer uses to develop computer
programs.
In simple ways we can say that source code is a set of program
instructions in their original form.
Since we know that there are many programming languages used to write
computer programs, therefore, even the source codes may vary from one
language to another BUT both might be producing the same output. For
example: keenly observe the table below that shows two different source
codes.
Source Code in Java Source Code in PHP
public class myProgram{ <?php
public static void main(String [ ]args){ echo "Hello World!";
System.out.println("Hello World!"); ?>
}
}
When compiled the output will be: When run on a browser, out put is
Hello World Hello World
From the table above, you might have learned that, there is a significant
difference between the two source codes but still the output for both is
the same.
Setup File
The Setup file may be a compressed package containing the entire
application or the file may simply launch a routine to install several
supplemental files.
For example, a small application may have all files enclosed in the Setup
file. Launching the setup file simply extracts the necessary files and
installs them to the appropriate place on the computer. For larger
applications, launching the Setup file may start a routine that calls several
other files from an installation CD, DVD or the file system.
For Windows based program, setup file has an extension of .exe, For Mac
the setup file has an extension of .dmg while for Android programs the
setup file has an extension of .apk
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 8 PROGRAMMING CONCEPTS MANUAL
1.2 Various Programs
An important reason to consider learning about how to program a
computer is that the concepts underlying this will be valuable to you,
regardless of whether or not you go on to make a career out of it. One
thing that you will learn quickly is that a computer is very dumb, but
obedient. It does exactly what you tell it to do, which is not necessarily
what you wanted. Programming will help you learn the importance of
clarity of expression. Today, computing programs are found in a number
of objects performing various tasks.
Programs on Computers
Programs that are running on computers can either be large or small
depending on the primary purpose for such program. However, not any
programs can run on any computer. Operating system the computer is
running on determines the programs that can run on that said machine.
Other factors include size or RAM, manufacturer, processor speed, size of
hard disk and other attached devices.
Programs on Mobile Phones
Today you might have observed that mobile phones come in different
size, shapes, capacity and make. All phones run on a certain operating
system. For example Samsung runs on Android, iPhone runs on iOS,
Nokia runs on Windows. Therefore, when developers are bringing some
wonderful programs like Kupatana in the market they have to think on
the platform that their applications will run on.
The pie chat above shows the domination of mobile OS in the market in
the year 2014. The chat shows that Android have dominated the market
at 47.1%. This can be due to its devices being sold at an affordable price,
and they are found in many various manufacturers like Techno, Huaweii,
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 9 PROGRAMMING CONCEPTS MANUAL
and many more. on the other hand, iOS has a significant market
domination as well.
Programs on Vehicles
Computer programs are also found in a number of motor vehicles today.
These programs in motor vehicles are used for different purposes, for
example checking the fuel level, security alerts, and direction guidance.
Programs on Home Appliances
In our homes you will be shocked to know that you have being
surrounded by appliances that use computer program. For example,
CCTV camera, TV, LUKU and others. Programs of this type are embedded
on an appliance.
1.3 Programming Languages
The description of a programming language is usually split into the two
components of syntax (form) and semantics (meaning).
1.3.1 Formal Language
The alphabet of a formal language is a set of symbols on which this
language is built. Some of the symbols in an alphabet may have a special
meaning. The formation rules specify which strings of symbols count as
well-formed. The well-formed strings of symbols are also called words,
expressions, formulas, or terms.
An example of a formal language is Kiswahili.
1.3.2 Programming Language
A programming language is a formal constructed language designed to
communicate instructions to a machine, particularly a computer.
Programming languages can be used to create programs to control the
behavior of a machine or to express algorithms.
1.3.3 Levels of Programming Language
There are basically two levels of computer programming languages; Low
Level and High Level.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 10 PROGRAMMING CONCEPTS MANUAL
Low Level Programming Language
In computers, a low-level programming language is a programming
language that provides little or no abstraction from a computer's
instruction set architecture—commands or functions in the language map
closely to processor instructions. Generally this refers to either machine
code or assembly language, to be discussed in section 1.3.4 below.
Low-level languages are useful because written in them can be crafted to
run very fast and with a very small memory footprint. However, they are
considered more difficult to utilize because they require a deeper
knowledge of machine language.
Languages such as C and C++ are considered "lower-level" — they
provide a minimal amount of abstraction at the smallest possible cost to
performance and efficiency. These abstractions, such as classes, lambda
functions and macros, allow programmers to use complex functionality
without writing overly complex code. For this reason, lower-level
languages are used in projects where abstractions are necessary to keep
code highly readable and maintainable, but where maximum
performance is still paramount. Many operating systems and high-frame
rate computer games are a good example of this.
Advantages and Disadvantages of Low Level Languages
Here are some advantages of Low level Languages:
1. It consists of binary digits and some symbols.
2. It depends on machine.
3. Machine language directly executes on computer.
4. No need of language translator for machine language.
5. Program written in low level language is called object code.
Here are some disadvantages of Low Level Languages:
1. It is not easy to understand.
2. It is difficult to modify.
High Level Programming Languages
The high level languages are close to human languages. It is easy to
understand by Human but difficult for Computer to understand. Computer
needs some mechanism to understand it. A high-level programming
language has strong abstraction from the details of the computer. In
comparison to low-level programming languages, it may use natural
language elements, be easier to use, or may automate (or even hide
entirely) significant areas of computing systems (e.g. memory
management), making the process of developing a program simpler and
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 11 PROGRAMMING CONCEPTS MANUAL
more understandable relative to a lower-level language. The amount of
abstraction provided defines how "high-level" a programming language is.
High-level language is not limited by the computer, designed for a specific
job, and is easier to understand. It is more like human language and less
like machine language. However, for a computer to understand and run a
program created with a high-level language, it must be compiled into
machine language.
The first high-level languages were introduced in the 1950's. Today, there
are many high-level languages in use, including BASIC, C, C++, COBOL,
FORTRAN, Java, Pascal, Perl, PHP, Python, Ruby, and Visual Basic.
Advantages and disadvantages of High Level Languages
Here are some of advantages of high level languages:
1. It is close to human being
2. It is easy to understand
3. It consists of English language like structure
4. It does not depend upon machine
5. It is easy to modify
Here are some disadvantages of high level languages:
1. It need language translator to translate into program in to machine
language.
2. It does not execute directly on computer.
1.3.4 Categories of Programming Language
Computer programming language, any of various languages for
expressing a set of detailed instructions for a digital computer. Such
instructions can be executed directly when they are in the computer
manufacturer-specific numerical form known as machine language, after
a simple substitution process when expressed in a corresponding
assembly language, or after translation from some “higher-level”
language. Although there are over 2,000 computer languages, relatively
few are widely used.
Machine and assembly languages are “low-level,” requiring a
programmer to manage explicitly all of a computer’s idiosyncratic
features of data storage and operation. In contrast, high-level languages
shield a programmer from worrying about such considerations and
provide a notation that is more easily written and read by programmers.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 12 PROGRAMMING CONCEPTS MANUAL
Machine Language
A Machine Language is the only language that is directly understood by
the computer. It does not need any translator program. We also call it
machine code and it is written as strings of 1's (one) and 0’s (zero).
When this sequence of codes is fed to the computer, it recognizes the
codes and converts it in to electrical signals needed to run it. For
example, a program instruction may look like this:
1011000111101
It is not an easy language for you to learn because of its difficult to
understand. It is efficient for the computer but very inefficient for
programmers. It is considered to the first generation language. It is also
difficult to debug the program written in this language.
Advantage Machine Language:
The only advantage is that program of machine language run very fast
because no translation program is required for the CPU.
Disadvantages Machine Language:
1. It is very difficult to program in machine language. The programmer
has to know details of hardware to write program.
2. The programmer has to remember a lot of codes to write a program
which results in program errors.
3. It is difficult to debug the program.
Assembly Language
It is the first step to improve the programming structure. You should
know that computer can handle numbers and letter. Therefore some
combination of letters can be used to substitute for number of machine
codes.
The set of symbols and letters forms the Assembly Language and a
translator program is required to translate the Assembly Language to
machine language. This translator program is called `Assembler'. It is
considered to be a second-generation language.
Advantages Assembly Language:
1. The symbolic programming of Assembly Language is easier to
understand and saves a lot of time and effort of the programmer.
2. It is easier to correct errors and modify program instructions.
3. Assembly Language has the same efficiency of execution as the
machine level language. Because this is one-to-one translator
between assembly language program and its corresponding
machine language program.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 13 PROGRAMMING CONCEPTS MANUAL
Disadvantage Assembly Language:
One of the major disadvantages is that assembly language is machine
dependent. A program written for one computer might not run in other
computers with different hardware configuration
1.4 Translating Computer Programs
A translator is a computer program that performs the translation of a
program written in a given programming language into a functionally
equivalent program in a different computer language, without losing the
functional or logical structure of the original code (the "essence" of each
program).
1.4.1 Interpreter
An interpreter is a computer program that reads program code line by
line and does what it says. In this case when there are changes in the
application source code the output will as well be affected accordingly.
1.4.2 Compiling
A compiler is a computer program that reads program code whole at
once and does what it says. In this case the application code is first
translated into object code which is then executed to produce the output.
Therefore, when there are changes in the application source code the
output will not be affected unless the program is compiled again.
Objects Code - this is a compiled source code.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 14 PROGRAMMING CONCEPTS MANUAL
The main differences between interpreter and compiler are:
No Compiler Interpreter
1 Compiler Takes Entire program as input Interpreter Takes Single instruction as input.
2 Intermediate Object Code is Generated No Intermediate Object Code is Generated
3 Conditional Control Statements are Conditional Control Statements are
Executes faster Executes slower
4 Memory Requirement is More (Since Memory Requirement is Less
Object Code is Generated)
5 Program need not be compiled every time Every time higher level program is converted
into lower level program
6 Errors are displayed after entire program is Errors are displayed for every
checked instruction interpreted (if any)
7 Programming language like C, C++ uses Programming language like PHP, Python, Ruby
compilers. use interpreters.
1.5 Source Code Editors
A source code editor is a text editor program designed specifically for
editing source code of computer programs by programmers. It may be a
standalone application or it may be built into an integrated development
environment (IDE) or web browser.
It is good to know that source code editors have features specifically
designed to simplify and speed up input of source code, such as syntax
highlighting, indentation, autocomplete and bracket matching
functionality. These editors also provide a convenient way to run a
compiler, interpreter, debugger, or other program relevant for the
software development process.
So, while many text editors can be used to edit source code, if they don't
enhance, automate or ease the editing of code, they are not source code
editors, but simply text editors that can also be used to edit source code.
Examples of Source Code Editors include Notepad++, Eclipse, Net Beans,
Sublime, JCreator, Dreamweaver, etc.
1.6 Good Computer Programs
As we all know that every computer requires appropriate instruction set
(programs) to perform the required task. The quality of the processing
depends upon the given instructions. If the instructions are improper or
incorrect, then it is obvious that the result will be superfluous. Therefore,
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 15 PROGRAMMING CONCEPTS MANUAL
proper and correct instructions should be provided to the computer so
that it can provide the desired output. In addition, a program should be
written in such a manner that it is easier to understand the underlying
logic.
A good computer program should have following characteristics:
Portability:
Portability refers to the ability of an application to run on different
platforms (operating systems) with or without minimal changes. Due to
rapid development in the hardware and the software, nowadays platform
change is a common phenomenon. Hence, if a program is developed for
a particular platform, then the life span of the program is severely
affected.
Readability:
The program should be written in such a way that it makes other
programmers or users to follow the logic of the program without much
effort. If a program is written structurally, it helps the programmers to
understand their own program in a better way. Even if some
computational efficiency needs to be sacrificed for better readability, it is
advisable to use a more user-friendly approach, unless the processing of
an application is of utmost importance.
Efficiency:
Every program requires certain processing time and memory to process
the instructions and data. As the processing power and memory are the
most precious resources of a computer, a program should be laid out in
such a manner that it utilizes the least amount of memory and
processing time.
Structural:
To develop a program, the task must be broken down into a number of
subtasks. These subtasks are developed independently, and each
subtask is able to perform the assigned job without the help of any other
subtask. If a program is developed structurally, it becomes more
readable, and the testing and documentation process also gets easier.
Flexibility:
A program should be flexible enough to handle most of the changes
without having to rewrite the entire program. Most of the programs are
developed for a certain period and they require modifications from time
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 16 PROGRAMMING CONCEPTS MANUAL
to time. For example, in case of payroll management, as the time
progresses, some employees may leave the company while some others
may join. Hence, the payroll application should be flexible enough to
incorporate all the changes without having to reconstruct the entire
application.
Generality:
Apart from flexibility, the program should also be general. Generality
means that if a program is developed for a particular task, then it should
also be used for all similar tasks of the same domain. For example, if a
program is developed for a particular organization, then it should suit all
the other similar organizations.
Documentation:
Documentation is one of the most important components of an
application development. Even if a program is developed following the
best programming practices, it will be rendered useless if the end user is
not able to fully utilize the functionality of the application. A well-
documented application is also useful for other programmers because
even in the absence of the author, they can understand it.
Correctness:
This is "the degree with which software adheres to its specified
requirements". Well designed software should meet all the stated
requirements. While it might seem obvious that software should be
correct, but sometimes this characteristic is one of the hardest to assess.
Because of the tremendous complexity of software products, it is
impossible to perform exhaustive execution-based testing to insure that
no errors will occur when the software is run.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 17 PROGRAMMING CONCEPTS MANUAL
Review questions
1.What is Programming?
2.Differentiate manchine language and assembly language
3.Discuss the attribute of good programming
4.Distinguish between source code and computer programming?
5.Briefly describe characteristics of high level language and low level language
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 18 PROGRAMMING CONCEPTS MANUAL
Chapter 2: Solving Problems Using Computers
2.1 Why using computers to solve problems?
Computers were originally used in order to solve mathematical equations;
however, now they are used to streamline communication, analyze data,
store information, play games and find information through the Internet.
The Internet is a large part of computing and through this, fast and cheap
communication and advertising throughout the world enables businesses
to save money.
There are many types of computers that are designed to help in different
tasks, for offices there are desktop PCs, for those people who travel a
laptop PC can keep them working wherever they go. Smartphones,
handheld personal digital assistants and tablets can be used to input or
display information without the need for power adapters or bulky
hardware.
2.2 Steps for solving problems using computers
2.2.1 Problem Definition
Suppose that, as a programmer, you are contacted because your services
are needed. You meet with users from the client organization to analyze
the problem, or you meet with a systems analyst who outlines the
project. Specifically, the task of defining the problem consists of
identifying what it is you know (input-given data), and what it is you want
to obtain (output-the result). Eventually, you produce a written
agreement that, among other things, specifies the kind of input,
processing, and output required.
There are a number of ways that one can you to define a problem, among
such ways is Problem Definition Table - PDT - which divides a problem
into three main parts as shown herein.
Known Facts User Requirements Necessary Processing
State what is known about
State what should the user do
the problem Explains stapes to be taken to
accomplish what user wants
Shows what the user wants it
Stipulates additional info done
done
required
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 19 PROGRAMMING CONCEPTS MANUAL
2.2.2 Solution Planning
Two common ways of planning the solution to a problem are to draw a
flowchart and to write pseudo code, or possibly both. Essentially, a
flowchart is a pictorial representation of a step-by-step solution to a
problem. It consists of arrows representing the direction the program
takes and boxes and other symbols representing actions. It is a map of
what your program is going to do and how it is going to do it. The
American National Standards Institute (ANSI) has developed a standard
set of flowchart symbols.
Pseudo code is an English-like nonstandard language that lets you state
your solution with more precision than you can in plain English but with
less precision than is required when using a formal programming
language. Pseudo code permits you to focus on the program logic without
having to be concerned just yet about the precise syntax of a particular
programming language. However, pseudo code is not executable on the
computer. We will illustrate these later in Chapter 3.
2.2.3 Solution Implementation
As the programmer, your next step is to code the program-that is, to
express your solution in a programming language. You will translate the
logic from the flowchart or pseudo code-or some other tool-to a
programming language. As we have already noted, a programming
language is a set of rules that provides a way of instructing the computer
what operations to perform. There are many programming languages:
BASIC, COBOL, Pascal, FORTRAN, and C are some examples. You may
find yourself working with one or more of these. We will discuss the
different types of languages in detail later in this chapter.
2.2.4 Solution Testing
Some experts insist that a well-designed program can be written correctly
the first time. In fact, they assert that there are mathematical ways to
prove that a program is correct. However, the imperfections of the world
are still with us, so most programmers get used to the idea that their
newly written programs probably have a few errors. This is a bit
discouraging at first, since programmers tend to be precise, careful,
detail-oriented people who take pride in their work. Still, there are many
opportunities to introduce mistakes into programs, and you, just as those
who have gone before you, will probably find several of them.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 20 PROGRAMMING CONCEPTS MANUAL
Desk-checking. This phase, similar to proofreading, is sometimes
avoided by the programmer who is looking for a shortcut and is eager to
run the program on the computer once it is written.
Translating. A translator is a program that (1) checks the syntax of your
program to make sure the programming language was used correctly,
giving you all the syntax-error messages, called diagnostics, and (2) then
translates your program into a form the computer can understand.
Debugging. A term used extensively in programming, debugging means
detecting, locating, and correcting bugs (mistakes), usually by running
the program.
2.2.5 Solution Documentation
Documenting is an ongoing, necessary process, although, as many
programmers are, you may be eager to pursue more exciting computer-
centered activities. Documentation is a written detailed description of the
programming cycle and specific facts about the program. Typical program
documentation materials include the origin and nature of the problem, a
brief narrative description of the program, logic tools such as flowcharts
and pseudo code, data-record descriptions, program listings, and testing
results.
Comments in the program itself are also considered an essential part of
documentation. Many programmers document as they code. In a broader
sense, program documentation can be part of the documentation for an
entire system.
2.3 Things to consider
An important point before we proceed: You will not be a programmer
when you finish reading this module. Programming proficiency takes
practice and training beyond the scope of this module. However, you will
become acquainted with how programmers develop solutions to a variety
of problems.
In general, the programmer's job is to convert problem solutions into
instructions for the computer. That is, the programmer prepares the
instructions of a computer program and runs those instructions on the
computer, tests the program to see if it is working properly, and makes
corrections to the program. The programmer also writes a report on the
program. These activities are all done for the purpose of helping a user fill
a need, such as paying employees, billing customers, or admitting
students to college.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 21 PROGRAMMING CONCEPTS MANUAL
The programming activities just described could be done, perhaps, as solo
activities, but a programmer typically interacts with a variety of people.
For example, if a program is part of a system of several programs, the
programmer coordinates with other programmers to make sure that the
programs fit together well.
If you were a programmer, you might also have coordination meetings
with users, managers, systems analysts, and with peers who evaluate
your work-just as you evaluate theirs.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 22 PROGRAMMING CONCEPTS MANUAL
Review questions
1. Differentiate between local and global variable
2. Explain the steps followed on solving computer problems
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 23 PROGRAMMING CONCEPTS MANUAL
Chapter 3: Computer Algorithms
3.1 What Are Algorithms?
An algorithm is a well-defined procedure that allows a computer to solve
a problem. Another way to describe an algorithm is a sequence of
unambiguous instructions. The use of the term 'unambiguous' indicates
that there is no room for subjective interpretation. Every time you ask
your computer to carry out the same algorithm, it will do it in exactly the
same manner with the exact same result.
Therefore, algorithm is a procedure of solving a problem in terms of the
actions to be executed and the order in which those actions are to be
executed.
3.2 Scenarials for Computer Programs
Computer programs can be built basing on either one or combination of
the following scenarials.
3.2.1 Sequential Structure
This is a series of processes that follow a certain order.
3.2.2 Decisional Structure
This is a structure that processes are executed depending on a
given condition that have alternatives.
3.2.3 Looping Structure
This is a structure that shows the execution of processes being
repeated at a number of times.
Parts of the Loop
There are three main parts of the loop
(a) Initial - this is a point (value) at which the loop starts
(b) Limit Test - this is a point (value) where the loop stops
(c) Interval - this is a value between two adjacent instances
3.3 Importance of Using Algorithms
There are two main reasons we use an algorithm: correctness and
efficiency. By far the most important reason to analyze an algorithm is to
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 24 PROGRAMMING CONCEPTS MANUAL
make sure it will correctly solve your problem. If our algorithm doesn't
work, nothing else matters. So we must analyze it to prove that it will
always work as expected.
We must also look at the efficiency of our algorithm. If it solves our
problem.
NOTE: Keywords
For looping and selection, The keywords that are to be used include Do
While...EndDo; Do Until...Enddo; Case...EndCase; If...Endif; Call ... with
(parameters); Call; Return ....; Return; When; Always use scope
terminators for loops and iteration.
As verbs, use the words Generate, Compute, Process, etc. Words such as
set, reset, increment, compute, calculate, add, sum, multiply, ... print,
display, input, output, edit, test , etc. with careful indentation tend to
foster desirable pseudocode.
3.4 Pseudo-code
Pseudocode is a simple way of writing programming code in English.
Pseudocode is not actual programming language. It uses short phrases to
write code for programs before you actually create it in a specific
language. Once you know what the program is about and how it will
function, then you can use pseudocode to create statements to achieve
the required results for your program.
Pseudocode is an artificial and informal language that helps programmers
develop algorithms. Pseudocode is a "text-based" detail (algorithmic)
design tool. Do not include data declarations in your pseudocode.
Example: Sequential Structure
Create a pseudo-code for a program to accept and add 2 numbers
together and then display the result.
Solution:
Start Program
Enter two numbers, A, B
Add the numbers together
Print Sum
End Program
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 25 PROGRAMMING CONCEPTS MANUAL
Example: Decision Structure
Develop a pseudo-code for a computer program that accept a grade.
When the grade is greater than or equal to 60, the progam should print
passed, otherwise failed.
Solution:
Start Program
If student's grade is greater than or equal to 60
Print "passed"
else
Print "failed"
End Program
Example: Looping Structure
Write a pseudo-code for a computer program that will print all numbers
from 1 to 10 at an interval of 1.
Solution:
Start Program
Set number to zero
While grade number is less than or equal to ten
Print number
Add 1 to number
End while
End Program
3.5 Flowcharts
A flowchart is a graphical representation of a computer program. This
algorithmic tool contains shapes and symbols.
3.5.1 Why Programmers use flowcharts?
Every programmer is interested to use flowcharts because flowcharts:
help to plan an oorganize facts on a piece of paper
help in outlining problems, logic and solutions
help in composing a comprehensive documentation
help in designing solution in a systematic way.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 26 PROGRAMMING CONCEPTS MANUAL
3.5.2 Flowchart Standard Symbols
(a) Terminal Symbols
It is an oval shaped
It is used to show the starting or ending of the program.
Sometimes is used to show a point of interruption, for
example halt or delay.
Single line flows in (to show the starting) or out (to show the
stoping).
Start
Stop
(b) Preparation Symbol
It is hexagon shaped
It is used to show the initialization of objects or variables
It has one line flows in and one line flows out.
Pi = 3.14
g = 9.8
(c) Input/ Output Symbols
It is parallelogram shaped symbol
It is used whenever information is being entered into the
program or displayed from the program.
The symbol has one line in and one line out.
Input show
radius, height area, volume
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 27 PROGRAMMING CONCEPTS MANUAL
(d) Process Symbol
It is a ractangle shaped symbol
It is used anytime when data is being manipulated, more
often with arithmetic operations like adding,
multiplicating...etc.
The process symbol has one line in and one line out.
area = Pi * r * r
(e) Connector Symbol
This symbol is presented by a small circle.
It is used to connected remote flowchart portions on the same
page.
Multiple lines can come in and one out.
(f) Flow Symbol
It is presented by a line; either an arrow or blunt.
It shows the flow of the system from one port of the code to
another.
(g) Decision Symbol
It is represented by a diamond shape
It is used to show two possible alternatives
It has one line in and TWO lines out
The out going lines are labeled as TRUE or FALSE, YES or NO,
1 or 0, HIGH or LOW
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 28 PROGRAMMING CONCEPTS MANUAL
N is Y
x>y
3.6 Building Flowcharts
Building flowchart depends on the nature of the computer program to be
developed. As we discussed in Section 3.2, we shall cover how to build
flowcharts basing on the scenario of the computer program.
3.6.1 Flowchart - Sequential Structure
Example:
Develop a flowchart for a computer program that will accept test 1, test 2
and Assignment as T1, T2 and Asmt respectively. The program should
calculate and display the sum of the three entities.
Solution:
Start
Enter T1, T2, Asmt
Sum = T1 + T2 + Asmt
Show Sum
Stop
3.6.2 Flowchart - Selection Structure
Example:
Develop a flowchart for a computer program that will accept test1 and
test2 as T1 and T2 respectively. The program should compare and display
the test with a higher score than the other.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 29 PROGRAMMING CONCEPTS MANUAL
Start
Enter T1, T2
No Yes
is
T1 > T2
Show T2 Show T1
Stop
3.6.3 Flowchart - Loop Structure
Example:
Develop a flowchart for a computer program that will display all numbers
from 1 to 10 at an interval of 3.
Start
x=1
Show x
x=x+3
No is
x > 10
Yes
Stop
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 30 PROGRAMMING CONCEPTS MANUAL
3.7 Advantages and Disadvantages of using Flowcharts
3.7.1 Advantages of Flowcharts
Here are some of the advantages of using flowcharts when creating
computer programs
a) Communication Flowcharts are better way of communicating the
logic of a system.
b) Proper documentation Program flowcharts serve as
a good program documentation, which is
needed for various purposes.
c) Efficient Coding: The flowcharts act as
a guide or blueprint during the systems analysis and program
development phase.
d) Proper Debugging: The flowchart helps in
locating and correcting errors (Also called debugging)
e) Efficient Program Maintenance: The maintenance of operating
program becomes easy with the help of flowchart
3.7.2 Disadvantages of Flowcharts
Here are some of the disadvantages of using flowcharts when creating
computer programs
a) Complexity of the computer program
b) Needs knowledge to construct and understand
c) Hard to reproduce when it comes to a huge program
3.8 Good Practice when Dealing with Flowcharts
There are few things you can do to make your flowchart universally
accepted. And there are some things that you can do to make it visually
pleasing to others as well. Using standard symbols will make it
understandable for a wide audience.
However it is important to remember that the idea is to give out
information in a easy to understand manner. It is perfectly acceptable to
use an alternative image instead of the document symbol as long as the
audience understands it. Keeping the arrow flow to one side, using same
size symbols, naming the decision blocks, processes, arrows etc are few
things you can do to make it better.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 31 PROGRAMMING CONCEPTS MANUAL
Rievew questions
1.Why Study Algorithms?
2. Draw a flowchart to find the largest of three numbers A, B, and C
3. Draw a flowchart to find the sum of the first 50 natural numbers.
4.With example explain the difference between pseudocode and flowchart
5.What are the advantages of using flowchart ?
6.Draw a flow chart to compute the area of the starting withR=0.5 up to
R=4.5,then display out each radius and the corresponding area of the circle.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 32 PROGRAMMING CONCEPTS MANUAL
Chapter 4: Programming Elements and
Approaches
4.1 Basic Programming Elements
As we have seen in the previous sections that progrmming languages may
differ in some aspects such as structure. However, all these computer
programming languages have some common elements. These elements
include but not limited to:
4.1.1 Keyword
Keywords are predefined, reserved identifiers that have special meanings
to the compiler. They cannot be used as identifiers in your program.
Example in Java Example in PHP
int age; $age;
4.1.2 Statement
A statement is a single line of code that performs a specific task within a
program code. In some programming language like PHP, C, C++ and Java
a statement is terminated by a semicolon - (;)
Example in C++ Example in PHP
int area = 3.14 * r * r; $area = 3.14 * $r * $r;
4.1.3 Variable
A variable is a memory location that stores data with change in value.
Example in VB Exmple in PHP
Dim age As Integer $age;
4.1.4 Constant
A constant is a memory location that stores data with NO change in value.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 33 PROGRAMMING CONCEPTS MANUAL
4.1.5 Expression
An expression is a collection of operands and operators. Operands can be
numbers or variables; operators are such as addition, subtraction, etc.
When writing an expression the syntax below should be followed:
expressionValue = expressionEquation
Example in PHP: $area = 3.14 * $r * $r;
4.1.6 Comments
A comment is a line or group of lines in a program code that describes
what the code does.
Types of Comments
i. Single line of Comment
Example in PHP: //comments here
ii. Block Comment
Example in PHP: /*comments here
even here
also here
*/
4.1.7 Assignment
An assignment is a symbol that assigns a value to a variable.
Example in PHP: $age = 23;
Therefore, the sign that is used to assign a value to a variable an equal
sign (=).
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 34 PROGRAMMING CONCEPTS MANUAL
4.2 List of Operators
Example in x=10, y=4
No Operator Function
PHP
1 + Addition x+y 12
2 - Subtraction x-y 6
3 * Multiplication x*y 40
4 / Division x/y 2.5
5 = Assigniment x=y 4
6 > Greater than x>y True
7 < Less than x<y False
8 >= Greater than or equal to x >= y True
9 <= Less than or equal to x <= y False
10 != Not equal to x != y True
11 % Reminder of x%y 2
4.3 Programming Approaches
There are several alternative approaches to the programming. Two of the
most important approaches are procedural programming and object-
oriented programming. We are going to learn about the differences
between these two approaches in this section.
We now know that programming is a creative process carried out by
programmers to instruct a computer on how to do a task. A program is a
set of instructions that tells a computer what to do in order to come up
with a solution to a particular problem. There are a number of alternative
approaches to the programming process, referred to as programming
paradigms. Different paradigms represent fundamentally different
approaches to building solutions to specific types of problems using
programming. Most programming languages fall under one paradigm, but
some languages have elements of multiple paradigms. Two of the most
important programming paradigms are the procedural paradigm and the
object-oriented paradigm. Let's look at each of these in a bit more detail.
4.3.1 Procedural Program
Procedural programming uses a list of instructions to tell the computer
what to do step-by-step. Procedural programming relies on procedures,
also known as routines or subroutines. A procedure contains a series of
computational steps to be carried out. Procedural programming is also
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 35 PROGRAMMING CONCEPTS MANUAL
referred to as imperative programming or traditional programming.
Procedural programming languages are also known as top-down
languages.
Procedural programming is intuitive in the sense that it is very similar to
how you would expect a program to work. If you want a computer to do
something, you should provide step-by-step instructions on how to do it.
It is, therefore, no surprise that most of the early programming languages
are all procedural. Examples of procedural languages include Fortran,
COBOL and C, which have been around since the 1960s and 70s.
4.3.2 Object Oriented Program
Object-oriented programming, or OOP, is an approach to problem-solving
where all computations are carried out using objects. An object is a
component of a program that knows how to perform certain actions and
how to interact with other elements of the program. Objects are the basic
units of object-oriented programming. A simple example of an object
would be a person. Logically, you would expect a person to have a name.
This would be considered a property of the person. You would also expect
a person to be able to do something, such as walking. This would be
considered a method of the person.
A method in object-oriented programming is like a procedure in
procedural programming. The key difference here is that the method is
part of an object. In object-oriented programming, you organize your
code by creating objects, and then you can give those objects properties
and you can make them do certain things.
A key aspect of object-oriented programming is the use of classes. A class
is a blueprint of an object. You can think of a class as a concept, and the
object as the embodiment of that concept. So let's say you want to use a
person in your program. You want to be able to describe the person and
have the person do something. A class called 'person' would provide a
blueprint for what a person looks like and what a person can do.
Examples of object-oriented languages include C#, Java, Perl and Python.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 36 PROGRAMMING CONCEPTS MANUAL
Review questions
1.Explain the difference between object oriented program and procedural
program approach
2.With example describe the programming approach
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 37 PROGRAMMING CONCEPTS MANUAL
Chapter 5: Program Debugging
We have now seen how a computer program can be created from
algorithms like flowcharts to a fully functional program. Therefore, all
programs have to deal with errors. Errors are unexpected conditions that
are not part of the normal operation of a program. Errors or mistakes in a
program are often referred to as bugs. They are almost always the fault
of the programmer. The process of finding and eliminating errors is called
debugging.
5.1 Syntax
When you create a variable, Visual Basic assigns a default value to it. The
actual default value depends on the variable's data type, as shown in
Table 5.1.
5.2 Errors
Errors can be classified into three major groups:
1. Syntax errors
2. Runtime errors
3. Logic errors
5.2.1 Syntax Errors
Syntax errors represent grammar errors in the use of the programming
language.
Common examples are:
Misspelled variable and function names
Missing semicolons
Unmatched parentheses, square brackets, and curly braces
Using a variable that has not been declared
Incorrect format in selection and loop statements
Syntax errors are the easiest to find and fix. Over the years, compiler
developers have worked hard to make compilers smarter so that they can
catch errors at compile time that might otherwise turn out to be runtime
errors.
Examples:
Simple statement not terminated by semicolon
Using a variable before it is declared
Missing closing parenthesis, ) , in the print or echo statement
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 38 PROGRAMMING CONCEPTS MANUAL
5.2.2 Logical Errors
Logic errors occur when a programmer implements the algorithm for
solving a problem incorrectly. A statement with logical error may produce
unexpected and wrong results in the program. Common examples are:
Multiplying when you should be dividing
Adding when you should be subtracting
Opening and using data from the wrong file
Displaying the wrong message
Logic errors are the hardest to find and fix because:
The compiler does not detect these errors
There is no indication of error when the program is executed.
The program may produce correct results for some input data and
wrong results for other input data.
Logic errors can only be detected by examining the program thoroughly.
This is usually done by using a debugger.
5.2.3 Run-Time Errors
A type of error that occurs during the execution of a program is known as
run-time error. Runtime errors may crash your program when you run it.
Runtime errors occur when a program with no syntax errors directs the
computer to execute an illegal operation. Common examples are:
Trying to divide by a variable that contains a value of zero
Trying to open a file that does not exist
There is no way for the compiler to know about these kinds of errors
when the program is compiled. Runtime errors are commonly due to
wrong input from the user. Runtime errors are usually more difficult to
find and fix than syntax errors.
5.4 Good Programming Practice
Code readability is a universal subject in the world of computer
programming. It's one of the first things we learn as developers. This part
will list the most important best practices when writing readable code.
1. Commenting and Documentation
2. Consistence Indentation
3. Code Grouping
4. Consistence Naming Scheme
5. Reduce the Risk of Logical Errors
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 39 PROGRAMMING CONCEPTS MANUAL
Review questions
1.With example describe the how semantic error occurred
2.what are difference between syntax error and logical error with example
3.from the following code identify and state the error which you observe
#include <iostream>
int main)
{
int a;
int b,
int sum;
sum = a + b;
cout << "The sum of " << a < " and " << b << " is " << addition << "\n";
reeturn 0;
}
4. Use the above code to rewrite the program using PHP programming
language.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 40 PROGRAMMING CONCEPTS MANUAL
Chapter 6: Programming with PHP
6.1 What is PHP
PHP is probably the most popular scripting language on the web. It is
used to enhance web pages. With PHP, you can do things like create
username and password login pages, check details from a form, create
forums, picture galleries, surveys, and a whole lot more. If you've come
across a web page that ends in PHP, then the author has written some
programming code to liven up the plain, old HTML.
The most popular explanation of just what PHP stands for is "Hypertext
Pre-processor". But that would make it HPP, surely? An alternative
explanation is that the initials come from the earliest version of the
program, which was called Personal Home Page Tools. At least you get
the letters "PHP" in the right order!
You'll also need to have a server, to test your scripts. Install Wampp or
Xampp on your PC.
6.2 Dealing with Wampserver
6.2.1 Installing and Testing Wampserver
Steps
1. Download a setup file for wampserver from online source.
2. Install your wamppserver
3. If the installation went well, you should have an new icon in the
bottom right, where the clock is:
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 41 PROGRAMMING CONCEPTS MANUAL
4. Click the icon to see the menu above.
From here, you can stop the server, exit it, view help files, and see
the configuration pages.
Click on localhost, though, and you'll see this page appear:
(Localhost just refers to the server running on your own computer.
Another way to refer to your server is by using the IP address
127.0.0.1.)
5. Saving PHP file-Whenever you create a new PHP page, you need
to save it in your WWW directory. You can see where this is by
clicking its item on the menu:
When you click on www directory, you should see an explorer
window appear. This one is from Windows Vista: (You'll probably
have only two files, index and testmysql).
6. Using notepa or notepad++, create a file and save it with an
extension .php (example test1.php)in the directory www found in
your server.
7. Launching PHP File - Suppose you have created a php script
called test1.php. To launch this script, you need to add the script
name after localhost in your browser. So type this:
http://localhost/test1.php
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 42 PROGRAMMING CONCEPTS MANUAL
6.3 Creating a Program with PHP
6.3.1 PHP Tags and Facts
Opening and Closing Tags
A PHP script can be placed anywhere in the html document.
A PHP script starts with <?php and ends with ?>
6.3.2 Statement
A PHP statement ends with a semicolon (;)
6.3.3 Output Functions
echo and print
echo and print are more or less the same. They are both used to
output data to the screen.
The differences are small: echo has no return value while print has
a return value of 1 so it can be used in expressions. echo can
take multiple parameters while print can take one argument. echo is
marginally faster than print.
Below, we have an example of a simple PHP file, with a PHP script
that uses a built-in PHP function "echo" to output the text "Hello
World!" on a web page:
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 43 PROGRAMMING CONCEPTS MANUAL
6.3.4 Comments
A comment in PHP code is a line that is not read/executed as part of the
program. Its only purpose is to be read by someone who is looking at the
code.
6.3.5 Variables
In PHP, a variable starts with the $ sign, followed by the name of the
variable:
After the execution of the statements above, the variable $txt will hold
the value Hello world!, the variable $x will hold the value 5, and the
variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around
the value.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 44 PROGRAMMING CONCEPTS MANUAL
A variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume).
Rules for PHP variables:
1. A variable starts with the $ sign, followed by the name of the
variable
2. A variable name must start with a letter or the underscore character
3. A variable name cannot start with a number
4. A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
5. Variable names are case-sensitive ($age and $AGE are two different
variables)
6.3.5 Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
The following example will output the sum of two variables:
6.4 Working with Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 45 PROGRAMMING CONCEPTS MANUAL
6.4.1 Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform
common arithmetical operations, such as addition, subtraction,
multiplication etc.
6.4.2 Assignment Operators
The PHP comparison operators are used to compare two values (number or string):
6.4.3 Comparison Operators
The PHP comparison operators are used to compare two values
(number or string):
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 46 PROGRAMMING CONCEPTS MANUAL
6.4.4 Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's
value.
6.4.5 Logical Operators
The PHP logical operators are used to combine conditional statements.
6.4.6 String Operators
PHP has two operators that are specially designed for strings.
6.4.7 Array Operators
The PHP array operators are used to compare arrays.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 47 PROGRAMMING CONCEPTS MANUAL
6.5 Working with Decision Statements in PHP
Conditional statements are used to perform different actions based on
different conditions. Very often when you write code, you want to perform
different actions for different conditions. You can use conditional
statements in your code to do this.
6.5.1 IF Statement
The if statement executes some code if one condition is true.
The example below will output "Have a good day!" if the current time (HOUR)
is less than 20:
6.5.2 IF...ELSE Statement
The if....else statement executes some code if a condition is true and another
code if that condition is false.
The example below will output "Have a good day!" if the current time is less
than 20, and "Have a good night!" otherwise:
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 48 PROGRAMMING CONCEPTS MANUAL
6.5.3 IF...ELSEIF...Statement
The if....elseif...else statement executes different codes for more than two
conditions.
The example below will output "Have a good morning!" if the current time is
less than 10, and "Have a good day!" if the current time is less than 20.
Otherwise it will output "Have a good night!":
6.5.4 SWITCH CASE Statement
The switch statement is used to perform different actions based on different
conditions.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 49 PROGRAMMING CONCEPTS MANUAL
This is how it works: First we have a single expression n (most often a
variable), that is evaluated once. The value of the expression is then
compared with the values for each case in the structure. If there is a match,
the block of code associated with that case is executed. Use break to prevent
the code from running into the next case automatically. The default statement
is used if no match is found.
6.6 Working with Loops in PHP
PHP while loops execute a block of code while the specified condition is
true. Often when you write code, you want the same block of code to run
over and over again in a row. Instead of adding several almost equal
code-lines in a script, we can use loops to perform a task like this.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 50 PROGRAMMING CONCEPTS MANUAL
In PHP, we have the following looping statements:
1. while - loops through a block of code as long as the specified
condition is true
2. do...while - loops through a block of code once, and then repeats
the loop as long as the specified condition is true
3. for - loops through a block of code a specified number of times
4. foreach - loops through a block of code for each element in an
array
Any loop has three main parts:
> initial point where the loop starts
> condition where the loop stops
> interval range between two adjucent occurrences
6.6.1 while loop
The while loop executes a block of code as long as the specified condition is true.
The condition is tested first before the execution of the code
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop
will continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will
increase by 1 each time the loop runs ($x++):
6.6.2 do...while loop
The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 51 PROGRAMMING CONCEPTS MANUAL
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will
write some output, and then increment the variable $x with 1. Then the condition is
checked (is $x less than, or equal to 5?), and the loop will continue to run as long as
$x is less than, or equal to 5:
6.6.3 for loop
PHP for loops execute a block of code a specified number of times. The for loop is
used when you know in advance how many times the script should run.
Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE,
the loop continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value
The example below displays the numbers from 0 to 10:
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 52 PROGRAMMING CONCEPTS MANUAL
6.7 Dealing with Functions in PHP
The real power of PHP comes from its functions; it has more than 1000
built-in functions.
Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a
program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.
6.7.1 Create a User Defined Function in PHP
A user defined function declaration starts with the word "function":
A function name can start with a letter or underscore (not a
number). Give the function a name that reflects what the function
does!
In the example below, we create a function named "writeMsg()".
The opening curly brace ( { ) indicates the beginning of the function
code and the closing curly brace ( } ) indicates the end of the
function. The function outputs "Hello world!". To call the function,
just write its name:
6.7.2 Function with Arguments
Information can be passed to functions through arguments. An
argument is just like a variable.
Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just
separate them with a comma.
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 53 PROGRAMMING CONCEPTS MANUAL
The following example has a function with one argument ($fname).
When the familyName() function is called, we also pass along a
name (e.g. Jani), and the name is used inside the function, which
outputs several different first names, but an equal last name:
The following example has a function with two arguments ($fname
and $year):
6.7.3 Functions - Returning values
To let a function return a value, use the return statement:
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 54 PROGRAMMING CONCEPTS MANUAL
6.7.4 Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable
can be referenced /used.
PHP has three different variable scopes:
local
global
A variable declared outside a function has a GLOBAL SCOPE and can
only be accessed outside a function:
A variable declared within a function has a LOCAL SCOPE and can
only be accessed within that function
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 55 PROGRAMMING CONCEPTS MANUAL
Review questions
1. Explain the different types of errors in PHP
2. What is PHP?
3. Why PHP also called scripting language?
4. What is the difference between echo and print function?
5. Write a program to show the joining of two string in php
6. Repeat question 5 using other language C++ and Java
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 56 PROGRAMMING CONCEPTS MANUAL
References
1. Building a PHP Intranet Problem Design Solution by Wrox Author
Team.WROX P.. Paperback- 31 December, 2004.
2. Beginning PHP4 Programming by John Blank, et al .Wrox Press
Ltd. Paperback- 30 October, 2000
3. PHP Pocket Reference by Rasmus Lerdorf.O'Reilly UK. Paperback-
22 November, 2002
4. http://www.makeuseof.com/tag/6-free-sites-to-learn-about-programming-
in-php/
5. http://www.d.umn.edu/itss/training/online/webdesign/php.html
University Computing Centre One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645