0% found this document useful (0 votes)
104 views106 pages

Introduction To Computer Programming (1) 1

for IT student who want to become better programers

Uploaded by

Bruno Kakira
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views106 pages

Introduction To Computer Programming (1) 1

for IT student who want to become better programers

Uploaded by

Bruno Kakira
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 106

UNIVERSITY OF DAR ES SALAAM

COMPUTING CENTRE

Diploma in Computing and Information Technology

CTT 05104: INTRODUCTION TO COMPUTER PROGRAMMING


PAGE 2 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

© 2016 University of Dar es Salam 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 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 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 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 Computing
Centre. Whilst every effort is made to eradicate typing or technical
mistakes, we apologise for any errors you may detect. University
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 of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 3 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Introduction ............................................................................................................................ 6
COURSE DESCRIPTION ....................................................................................................................................6
COURSE OBJECTIVES ......................................................................................................................................6
DELIVERY METHODOLOGY ...............................................................................................................................6
Chapter 1: Programming - Overview ............................................................................... 7
1.1 WHAT IS COMPUTER PROGRAM? ..............................................................................................................7
1.2 WHAT IS COMPUTER PROGRAMMING? .....................................................................................................8
1.3 WHAT COMPUTER PROGRAM CAN DO? ....................................................................................................9
1.4 WHO IS COMPUTER PROGRAMMER? ........................................................................................................9
1.5 WHAT IS ALGORITHM? ...............................................................................................................................9
1.5.1 Flow Chart ......................................................................................................................................10
1.5.2 Pseudo code ..................................................................................................................................12
1.6 BASIC PROGRAMMING LANGUAGE ELEMENTS ........................................................................................13
EXERCISES .....................................................................................................................................................14
Chapter 2: Programming Environment & Basic Syntax ........................................... 15
2.1 TEXT EDITOR ...........................................................................................................................................16
2.2 COMPILER ................................................................................................................................................17
2.3 INTERPRETER ...........................................................................................................................................18
2.4 BASIC PROGRAMMING SYNTAX ...............................................................................................................19
2.4.1 Program Entry Point ......................................................................................................................19
2.4.2 Functions ........................................................................................................................................19
2.4.3 Comments ......................................................................................................................................20
2.4.4 Whitespaces ...................................................................................................................................20
2.4.5 Syntax Error ...................................................................................................................................23
2.4.6 Runtime Error .................................................................................................................................23
EXERCISES .....................................................................................................................................................25
Chapter 3: Data Types, Variables, Keywords & Constants ..................................... 26
3.1 DATA TYPES.............................................................................................................................................26
3.1.1 C & Java Data Types ....................................................................................................................27
3.1.2 PHP Data Types ............................................................................................................................28
3.2 VARIABLES ...............................................................................................................................................28
3.2.1 Creating variables .........................................................................................................................29
3.2.2 Store values in variables ..............................................................................................................30
3.2.3 Access stored values in variables ...............................................................................................31
3.2.4 Variables in Java ...........................................................................................................................32
3.2.5 Variables in PHP ...........................................................................................................................32
3.3 KEYWORDS ..............................................................................................................................................33
3.3.1 C programming reserved keywords ............................................................................................34
3.3.2 Java programming reserved keywords ......................................................................................34
3.3.3 PHP programming reserved keywords ......................................................................................35
3.4 CONSTANTS .............................................................................................................................................36
3.4.1 Defining Constants ........................................................................................................................36
EXERCISES .....................................................................................................................................................36
Chapter 4: Operators ......................................................................................................... 37
4.1 ARITHMETIC OPERATORS ........................................................................................................................37
4.2 RELATIONAL OPERATORS........................................................................................................................38
4.3 LOGICAL OPERATORS ..............................................................................................................................40
4.4 OPERATORS IN JAVA ...............................................................................................................................41

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 4 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

4.5 OPERATORS IN PHP ................................................................................................................................42


EXERCISES .....................................................................................................................................................43
Chapter 5: Decision Making & Loops............................................................................ 44
5.1 DECISION MAKING ....................................................................................................................................44
5.1.1 if statement .....................................................................................................................................45
5.1.2 if...else statement ..........................................................................................................................46
5.1.3 if...elseif...else statement ..............................................................................................................47
5.1.4 The switch statement ....................................................................................................................49
5.2 DECISIONS IN JAVA ..................................................................................................................................51
5.3 DECISIONS IN PHP ..................................................................................................................................51
5.4 LOOPS ......................................................................................................................................................52
5.4.1 The while Loop ..............................................................................................................................53
5.4.2 The do...while Loop .......................................................................................................................55
5.4.3 The For Loop..................................................................................................................................57
5.4.4 The break statement .....................................................................................................................59
5.4.5 The continue statement ................................................................................................................60
5.5 LOOPS IN JAVA .........................................................................................................................................61
5.6 LOOPS IN PHP .........................................................................................................................................62
EXERCISES .....................................................................................................................................................62
Chapter 6: Numbers & Characters ................................................................................. 63
6.1 NUMBERS IN PROGRAMMING ...................................................................................................................63
6.1.1 Math Operations on Numbers .....................................................................................................64
6.2 NUMBERS IN JAVA....................................................................................................................................65
6.3 NUMBERS IN PHP ....................................................................................................................................66
6.4 CHARACTERS IN PROGRAMMING .............................................................................................................67
6.4.1 Escape Sequences: ......................................................................................................................68
6.5 CHARACTERS IN JAVA..............................................................................................................................70
6.6 CHARACTERS IN PHP ..............................................................................................................................70
EXERCISES .....................................................................................................................................................71
Chapter 7: Arrays................................................................................................................ 72
7.1 INTRODUCTION .........................................................................................................................................72
7.2 CREATE ARRAYS .....................................................................................................................................73
7.3 INITIALIZING ARRAYS ...............................................................................................................................73
7.4 ACCESSING ARRAY ELEMENTS ...............................................................................................................74
7.5 ARRAYS IN JAVA ......................................................................................................................................75
7.6 ARRAYS PHP ...........................................................................................................................................76
EXERCISES .....................................................................................................................................................77
Chapter 8: Strings .............................................................................................................. 78
8.1 INTRODUCTION .........................................................................................................................................78
8.2 BASIC STRING CONCEPTS .......................................................................................................................80
8.3 STRINGS IN JAVA .....................................................................................................................................81
8.4 STRINGS IN PHP......................................................................................................................................81
EXERCISES .....................................................................................................................................................82
Chapter 9: Functions ......................................................................................................... 83
9.1 DEFINITION ...............................................................................................................................................83
9.2 CREATING A FUNCTION: ..........................................................................................................................84
9.3 CALLING A FUNCTION: .............................................................................................................................85
9.4 FUNCTION ARGUMENTS ...........................................................................................................................87
9.5 FUNCTIONS IN JAVA .................................................................................................................................89

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 5 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

9.6 FUNCTIONS IN PHP .................................................................................................................................90


EXERCISES .....................................................................................................................................................91
Chapter 10: File I/O ............................................................................................................. 92
10.1 COMPUTER FILES ..................................................................................................................................92
10.2 FILE INPUT/OUTPUT...............................................................................................................................92
10.3 FILE OPERATION MODES.......................................................................................................................92
10.4 OPENING FILES ......................................................................................................................................93
10.5 CLOSING A FILE .....................................................................................................................................94
10.6 WRITING A FILE......................................................................................................................................94
10.7 READING A FILE .....................................................................................................................................95
10.8 FILE I/O IN JAVA ....................................................................................................................................96
10.9 FILE I/O IN PHP .....................................................................................................................................97
EXERCISES .....................................................................................................................................................98
Chapter 11: Object Oriented Programming Concepts.............................................. 99
11.1 INTRODUCTION.......................................................................................................................................99
11.2 BASIC FEATURES OF OOP ..................................................................................................................100
11.2.1 Class ...........................................................................................................................................100
11.2.2 Object ..........................................................................................................................................101
11.2.3 Inheritance..................................................................................................................................101
11.2.4 Encapsulation ............................................................................................................................102
11.2.5 Abstraction .................................................................................................................................102
11.2.6 Polymorphism ............................................................................................................................103
11.3 ADVANTAGES OF OOP ........................................................................................................................103
EXERCISES ...................................................................................................................................................103
References.......................................................................................................................... 104
C - Environment Setup............................................................................................. 105

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 6 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Introduction
Course Description
The course introduces students to the concepts and techniques for the
art of writing computer programs. It will teach students the simple and
practical approach of creating computer programs while learning
computer programming.
.

Course Objectives
At the end of the course students should be able to
1. Identify various types of programming languages
2. Identify Variables, data types, keywords, operators, constants and
comments
3. Apply Algorithm, Flow chart, Pseudo Codes, Decisions and Loops in
developing computer program
4. Identify Program structure
5. Run simple structured program
6. Describe syntax errors, logical errors and run-time errors
7. Debug simple structured program
8. Describe Classes, Objects, Encapsulation, Inheritance, Abstraction
and Polymorphism

Delivery Methodology
The course will be delivered in form of lecturers, Tutorials in the
classroom and in the Computer laboratory 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

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 7 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Chapter 1: Programming - Overview

1.1 What is Computer Program?


A computer program is a sequence of instructions written using a
Computer Programming Language to perform a specified task by the
computer

I assume, you did not understand what I have written about which I
have used in the above definition:

 Sequence of instructions

 Computer Programming Language

To understand these terms, consider a situation when someone asks


you about how to go to a nearby Bus Station. What exactly do you do
to tell him the way to go to Bus Station?

You will use Human Language to tell the way to go to Bus Station
something as follows:

First go straight, after half kilometer, take left from the red light and
then drive around one kilometer and you will find Bus Station at the
right.

Here, you have used English Language to give several steps to be taken
to reach to Bus Station. If they will be followed in the following
sequence, then you will reach Bus Station:

1. Go straight
2. Drive half kilometer
3. Take left
4. Drive around one kilometer
5. Search for Bus Station at your right side

Now, try to map the situation with computer program. Above sequence
of instructions is actually a Human Program written in English
Language, which instructs on how to reach to Bus Station from a
given starting point. This same sequence could have been given in
Spanish Language, Hindi Language, Arabic or any other human

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 8 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

language provided someone, who is asking about the way, knows about
such languages.

Now, let's go back and try to understand about a computer program,


which is a sequence of instructions written in a Computer Language to
perform a specified task by the computer. Following is a simple program
written in PHP programming Language:

<?php  Print "Hello, World!" ; ?> 

Above computer program instructs computer to print "Hello, World!" on


computer screen.

 A computer program is also called computer software, which can


range from two lines to millions of lines of instructions.

 Computer program instructions are also called program source code


and computer programming is also called program coding.

 A computer machine without a computer program is just a dump box


and thus computer program brings a computer machine to live state.

Like human has several languages to communicate their message,


computer scientists have developed several computer-programming
languages to provide instructions to the computer (i.e., to write
computer programs). We will see and use several computer
programming languages in subsequent chapters of this manual.

1.2 What is Computer Programming?


If you understood what computer program is, then I will say the act of
writing computer programs is called computer programming.

As I mentioned earlier, there are many programming languages, which


can be used to write computer programs and following are few of them:

 Java
 C
 C++
 Python
 PHP
 Perl
 Ruby

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 9 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

1.3 What Computer Program can do?


Today computer programs are being used in almost every field,
household, agriculture, medical, entertainment, defense, communication,
etc. Following are few applications of computer programs:
 MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc.,
are example of computer programs.
 Computer programs are being used to develop graphics and special
effects in movie making.
 Computer programs are being used to perform Ultrasounds, X-Rays,
and other medical examinations.
 Computer programs are being used in our mobile phones for SMS,
Chat, and voice communication.

1.4 Who is Computer Programmer?


If you understood what computer program is and what is computer
programming, then simply apply common sense to understand who
computer programmer is?

Someone, who can write computer programs or in other words,


someone who can do computer programming is called Computer
Programmer

Based on computer programming language expertise, we can name


computer programmers as follows:
 C Programmer
 C++ Programmer
 Java Programmer
 Python Programmer
 PHP Programmer
 Perl Programmer
 Ruby Programmer

1.5 What is Algorithm?


From programming point of view, an algorithm is a step-by-step
procedure to resolve any problem. An algorithm is an effective method
expressed as a finite set of well-defined instructions.

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 10 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Thus, a computer programmer lists down all the steps required to


resolve a problem before jumping to write actual code. Following is a
simple example of an algorithm to find out a largest number from a
given list of numbers:

1. Get a list of numbers L1, L2, L3....LN


2. Assume L1 is the largest, Largest = L1
3. Take next number Li from the list and do the following
4. If Largest is less than Li
5. Largest = Li
6. If Li is last number from the list then
7. Print value stored in Largest and come out
8. Else repeat same process starting from step 3

Above algorithm has been written in very crude way just because to
make it clear to beginners, otherwise there two standardized ways of
writing computer algorithm which are Flow chart and Pseudo code

1.5.1 Flow Chart


A flowchart is a visual representation of the sequence of steps and
decisions needed to perform a process. Each step in the sequence is
noted within a diagram shape. Steps are linked by connecting lines and
directional arrows. This allows anyone to view the flowchart and logically
follow the process from beginning to end.

Different flow chart symbols have different meanings. The most common
flow chart symbols are:

Shape Name Description


Flow line connectors show the direction that the
Flow Line
process flows.
Represented as ovals, or rounded (fillet)
rectangles. They usually contain the word "Start"
Terminal
or "End", or another phrase signaling the start or
end of a process.
Represented as a diamond (rhombus) showing
where a decision is necessary, commonly a
Decision Yes/No question or True/False test. The
conditional symbol is peculiar in that it has two
arrows coming out of it, usually from the bottom
point and right point, one corresponding to Yes

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 11 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Shape Name Description


or True, and another corresponding to No or
False. (The arrows should always be labeled.)
Represented as a parallelogram. Involves
receiving data and displaying processed data.
Input/Output
Can only move from input to output and not vice
versa. Examples: Get X from the user; display X.
Represented as rectangles. This shape is used to
Process show that something is performed. Examples:
"Add 1 to X",
Represented as a hexagon. May also be called
initialization. Shows operations which have no
Preparation
effect other than preparing a value for a
subsequent conditional or decision step.

Example
Draw a flowchart for computing factorial N (N!) Where N! = 1?2?3?....N .
The figure below shows the required flow chart

Start

Read N

M=1
F=1

F = F*M

N
is M=N? M = M+1

Y
Display F

Stop

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 12 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

1.5.2 Pseudo code

Pseudocode is an artificial and informal language that helps


programmers to develop algorithms. Pseudocode is a "text-based" detail
(algorithmic) design tool.

The rules of Pseudocode are reasonably straightforward. All statements


showing "dependency" are to be indented. These include while, do, for,
if, switch. Examples below will illustrate this notion.

Example 1
If student's grade is greater than or equal to 60  
Print "passed"  
else  
Print "failed"

Example 2
Set total to zero  
Set grade counter to one  
While grade counter is less than or equal to ten  
Input the next grade 
Add the grade into the total  
Set the class average to the total divided by ten  
Print the class average.  

Example 3
Initialize total to zero  
Initialize counter to zero  
Input the first grade  
while the user has not as yet entered the sentinel  
add this grade into the running total  
add one to the grade counter  
input the next grade (possibly the sentinel) 
if the counter is not equal to zero  
set the average to the total divided by the counter 
print the average  
else  
print 'no grades were entered'  

There is no strict set of standard notations for pseudocode, but some of


the most widely recognised are:
 INPUT/GET/READ – indicates a user will be inputting something

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 13 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

 OUTPUT/DISPLAY/PRINT – indicates that an output will appear


on the screen
 SET/INITIALIZE - indicates that a value is initialized for control
 WHILE – a loop (iteration that has a condition at the beginning)
 FOR – a counting loop (iteration)
 REPEAT – UNTIL – a loop (iteration) that has a condition at the
end
 IF – THEN – ELSE – a decision (selection) in which a choice is
made
For process the words increment, compute, calculate, add, sum, multiply
etc are used. Any instructions that occur inside a selection or iteration
are usually indented

Example 4

SET total to zero  
REPEAT  
  READ Temperature  
      IF Temperature > Freezing THEN  
    INCREMENT total  
    END IF 
UNTIL Temperature < zero  
Print total 
 

1.6 Basic Programming Language Elements


I assume you are well aware of English Language, which is a well-known
Human Interface Language. English has a predefined grammar, which
needs to be followed to write English statements in a correct way.
Likewise, most of the Human Interface Languages (Hindi, English,
Spanish, French, etc.) are made of several elements like verbs, nouns,
adjectives, adverbs, propositions, and conjunctions, etc.

Similar to Human Interface Languages, Computer Programming


Languages are also made of several elements. I will take you through
the basics of those elements and put some effort to make you
comfortable to use them in various programming languages. These basic
elements are:
 Programming Environment & Syntax
 Data Types, Variables, Keywords & Constants

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 14 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

 Basic Operators
 Decision Making & Loops
 Numbers & Characters
 Arrays
 Strings
 Functions
 File I/O

This manual will explain all these elements in subsequent chapters with
examples using different programming languages. First it will try to
explain meaning of all these terms in general and then shows how these
terms can be used in different programming language.

I believe if you understood above-mentioned elements related to any


programming language, then you are almost ready to write big enough
programs in that programming language.

However, this manual has been designed to give you an idea about the
following most popular programming languages:
 C Programming
 Java Programming
 PHP Programming

Major part of the manual has been explained by taking C as


programming language and then tries to show how similar concepts work
in Java and PHP. So after going through this manual, you will find
yourself familiar with these popular programming languages.

Exercises
1. What is computer programming?
2. What is Algorithm and how can you implement it?
3. Ask user for a number, ask user for another number, multiply the two
numbers, and print result. What do you call this set of instructions?
4. Create a flow chart for solving linear equation y = x-2 using positive
integer values of x from 5 to 10

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 15 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Chapter 2: Programming Environment & Basic


Syntax
Though Environment Setup is not an element of any Programming
Language, it is the first thing we need to start before working with any
Programming Language.

When we are saying Environment Setup, it simply means we need to


have a base on top of which we can do our programming. Thus, we need
to have required software setup, i.e., installation on our PC which will be
used to write our Computer Program, Compile and Execute it. For
example, if you need to browse Internet, then you need the following
setup on your machine:

 A working Internet Connection to connect to the Internet.

 Web Browser like Internet Explorer, Chrome, or Safari, etc.

If you are a PC user, then you will recognize following screen shot, which
I have taken from Internet Explorer while browsing www.ucc.co.tz.

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 16 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Similar way, you will need following setup to start with programming
using any programming language.
 A text editor to create computer program.
 A compiler to compile program into binary format.
 An interpreter to execute program directly.

If you are new to the computer, you yourself will not be able to set up
either of this Software. So, I suggest you take help from any technical
person around you to set up programming environment on your machine
from where you can start. But for you, this is important to understand
what these items are.

2.1 Text Editor


This is Software, which will be used to write your computer program. Your
Windows machine must have a Notepad, which can be used to type your
program. You can launch it by following these steps:

Start Icon → All Programs → Accessories → Notepad → Mouse Click on


Notepad

This will launch Notepad with the following window:

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 17 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

You can use this software to type your computer program and save it in a
file at any location. You can download and install other good editors like
Notepad++, which is freely available.

If you are Mac user, then you will have TextEdit or you can install some
other commercial editor like BBEdit, etc., to start with.

2.2 Compiler
You write your computer program using your favorite programming
language and save it in a text file called program file. What is next?
Let's try to get a little more detail on how computer understands a
program written by you using a programming language. Actually,
computer cannot understand your program directly given in the text
format, so we need to convert this program in a binary format, which can
be understood by the computer.
The conversion from text program to binary file is done by software called
Compiler and this process of conversion from text formatted program to
binary format file is called program compilation. Finally, you can execute
binary file to perform the programmed task.
We are not going into detail of different constituents of a compiler and
different phases of compilation.
Following flow diagram gives an illustration of the process:

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 18 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

So, if you are going to write your program in any such language, which
needs compilation like C, C++, Java and Pascal, etc., then you will need
to install their compilers before you start programming in such languages.

2.3 Interpreter
We just discussed about Compiler and Compilation Process. This is
required in case you are going to write your program in a programming
language, which needs compilation into binary format before its
execution. Few examples of such programming languages are C, C++,
and Java.

There are programming languages like Python, PHP and Perl, which do
not need any compilation into binary format, rather an interpreter can be
used to read such program line by line and execute it directly without any
further conversion.

So, if you are going to write your program in any such language, which
does not need compilation like PHP, Python, Perl, and Ruby, etc., then
you will need to install their interpreters before you start programming in
such languages.

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 19 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

2.4 Basic Programming Syntax

Let’s start with little coding, which will make you computer
program to write Hello, World! On your screen. Let’s see how it can be
written in various programming languages:

Hello World Program in C

#include <stdio.h>
main()
{
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
}

This little Hello World program will help us in understanding various basic
concepts related to C Programming.

2.4.1 Program Entry Point


For now just forget about #include <stdio.h> statement, but keep a
note that you have to put this statement at the top of a C program.

So, every C program starts with main(), which is called main function and
then it is followed by a left curly brace. Rest of the program instruction is
written in between and finally a right curly brace ends the program.

The coding part inside these two curly braces is called program body.
The left curly brace can be in the same line as main(){ or in the next line
like it has been mentioned in the above program.

2.4.2 Functions
Functions are small units of programs and they are used to carry out a
specific task. For example, above program makes use of two functions (a)
main() and (b) printf(). Here, function main() provides the entry point
for the program execution and another function printf() is being used to
print an information on computer screen.

You can write your own functions which we will see in separate chapter,
but C programming itself provides various built-in functions like main(),
printf(), etc., which we can use in our programs based on our need.

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 20 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Few programming languages use word sub-routine instead of function


but their functionality is more or less same.

2.4.3 Comments
The C program can have statements enclosed inside /*.....*/. Such
statements are called comments.

In computer programming, a comment is a programmer-readable


annotation in the source code of a computer program. They are added
with the purpose of making the source code easier to understand, and
are generally ignored by compilers and interpreters.

Comments are generally formatted as either block comments (also called


prologue comments or stream comments) or line comments (also called
inline comments).

Block comments delimit a region of source code which may span multiple
lines. This region is specified with a start delimiter and an end delimiter.

Line comments start with a comment delimiter and continue until the end
of the line, or in some cases, start at a specific column (character line
offset) in the source code, and continue until the end of the line.

Some programming languages employ both block and line comments with
different comment delimiters. For example, C has block comments
delimited by /* and */ that can span multiple lines and line comments
delimited by //. Other languages support only one type of comment.

2.4.4 Whitespaces
When we write a program using any programming language, we use
various printable characters to prepare programming statements. These
printable characters are a, b, c,......z, A, B, C,.....Z, 1, 2, 3,...... 0, !,
@, #, $, %, ^, &, *, (, ), -, _, +, =, \, |, {, }, [, ], :, ;, <, >, ?, /, \,
~. `. ", '. Hope I'm not missing any printable characters from your
keyboard.

Apart from these characters, there are some characters which we use
very frequently but they are invisible in your program and these
characters are spaces, tabs (\t), new lines(\n). These characters are
called whitespaces.

These three important whitespace characters are common in all the


programming languages and they remain invisible in your text document

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 21 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

having your program:

Whitespace Explanation Representation

New Line This will be used to create a new line. \n


Tab This will be used to create a tab. \t
Space This will be used to create a space. empty space

A line containing only whitespace, possibly with a comment, is known as


a blank line, and a C compiler totally ignores it. Whitespace is the term
used in C to describe blanks, tabs, newline characters and comments.
So you can write printf("Hello, World!" ); as follows. Here all the
created spaces around "Hello, World!" are useless and the compiler will
ignore them at the time of compilation.

#include <stdio.h>
main()
{
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
}

Assuming, I make all these whitespace characters visible, then your


above program will look like something below and you will not be able to
compile it:

#include <stdio.h>\n
\n
main()\n
{
\n
\t/* printf() function to write Hello, World! */ \n
\tprintf(\t"Hello, World!"\t);\n
\n
}\n

Every individual statement in C Program, must be ended with a


semicolon ; For example, if you want to write "Hello, World!" twice, then
it will be written as follows:

#include <stdio.h>
main()
{
/* printf() function to write Hello, World! */

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 22 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

printf( "Hello, World!\n" );


printf( "Hello, World!" );
}

This program will produce the following result:

Hello, World!
Hello, World!

Here, I'm using new line character \n in first printf() function to create a
new line. Let us see what happens if I do not use this new line character:

#include <stdio.h>
main()
{
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
printf( "Hello, World!" );
}

This program will produce following result:

Hello, World! Hello, World!

I'm skipping explanation about identifiers and keywords and will take
them in next few chapters.

Let's try to understand how the above C program to print “Hello, World!”
works. First of all, the above program is converted into a binary format
using C compiler. So let’s put this code in test.c file and compile it as
follows:

$gcc test.c -o demo

If there is any grammatical error (Syntax errors in computer


terminologies), then we fix it before converting it into binary format. If
everything goes fine then it produces binary file called demo. Finally we
execute produced binary demo as follows:

$./demo

This produces following result:

Hello, World!

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 23 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Here, when we execute binary demo.out file, what computer does is, it
enters inside the program starting from main() and encounters a printf()
statements. Keep a note about line inside /*....*/ is a comment so it is
filtered at the time of compilation. So printf() function instructs computer
to print the given line at the computer screen. Finally it encounters a right
curly brace which indicates the end of main() function and exit of the
program.

2.4.5 Syntax Error

If you do not follow rules defined by the programming language then at


the time of compilation you will get syntax error and program will not be
compiled. From syntax point of view, even a single dot or comma or
single semicolon matters and you should take care of such small syntax
as well. Following is Hello, World! program but here I'm not using
semicolon, let's try to compile following program:

#include <stdio.h>
main()
{
printf("Hello, World!")
}

This program will produce following result:

main.c: In function 'main':


main.c:7:1: error: expected ';' before '}' token
}
^
So bottom-line is that if you are not following proper syntax defined by
the programming language in your program then you will get similar type
of syntax errors and before trying next compilation you will need to fix
them and then proceed.

2.4.6 Runtime Error

A runtime error is a program error that occurs while the program is


running.

There are many different types of runtime errors. One example is a logic
error, which produces the wrong output.

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 24 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Many different types of programming mistakes can cause logic errors. For
example, assigning a value to the wrong variable may cause a series of
unexpected program errors. Multiplying two numbers instead of adding
them together may also produce unwanted results. Even small typos that
do not produce syntax errors may cause logic errors. In the PHP code
example below, the if statement may cause a logic error since the single
equal sign (=) should be a double equal sign (==).

Incorrect: if ($i=1) { ... }

Correct: if ($i==1) { ... }

In PHP, "==" means "is equal to," while "=" means "becomes."
Therefore, the incorrect if statement always returns TRUE, since assigning
1 to the variable $i returns a TRUE value. In the correct code, the if
statement only returns TRUE if $i is equal to 1. However, since the syntax
of the incorrect code is acceptable, it will not produce a syntax error and
the code will compile successfully.

A program crash is the most noticeable type of runtime error, since the
program unexpectedly quits while running. Crashes can be caused by
infinity loop, dividing by zero, referencing missing files, calling invalid
functions, or not handling certain input correctly.

Runtime errors are commonly referred to as "bugs," and are often found
during the debugging process, before the software is released. When
runtime errors are found after a program has been distributed to the
public, developers often release patches, or small updates, designed to fix
the errors.

Hello World Program in Java


Following is the equivalent program written in Java. This program will also
produce same result Hello, World!.

public class HelloWorld


{
public static void main(String []args)
{
/* println() function to write Hello, World! */
System.out.println("Hello, World!");
}
}

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 25 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Hello World Program in PHP

Following is the equivalent program written in PHP. This program will also
produce same result Hello, World!.

<?php
/* print function to write Hello, World! */
Echo "Hello, World!";
?>

Hope you noted that for C and Java examples, first we are compiling
programs and then executing produced binaries but in PHP program we
are directly executing it. As explained in previous section, PHP is an
interpreted language and it does not need intermediate step called
compilation.

Exercises

1. What is the software called that translates code into something


meaningful the computer can understand?
2. Mention common text editors which can be used as programming
environment
3. Differentiate between compilers and interpreters
4. List down the advantages of comment in programming
5. Describe the causes of syntax error and logical error

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 26 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Chapter 3: Data Types, Variables, Keywords &


Constants
3.1 Data Types
Data types are very important concept available in almost all the
programming languages. As its name indicates, a data type represents a
type of the data which you can process using your computer program. It
can be numeric, alphanumeric, decimal, etc.

Apart from Computer Programming, let's take a nursery class problem to


add two whole numbers 10 & 20, which we can do simply as follows:

10 + 20

Let's take another problem where we want to add two decimal numbers
10.50 & 20.50, which will be written as follows:

10.50 + 20.50

Above two examples are straight forward now let's take one example
where we want to record student information in a notebook. Here is
following important information, which we can record:

Name:
Class:
Section:
Age:
Sex:

Now, let's put one student record as per the given requirement:

Name: Zara Ali


Class: 6th
Section: J
Age: 13
Sex: F

First example dealt whole numbers and second example added two
numbers with decimals where as third example is dealing with a mix of
different data. Let's put it as follows:
 Student name "Zara Ali" is a sequence of characters which is also called
a string.

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 27 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

 Student class "6th" has been represented by a mix of whole number


and a string of two characters. Such a mix is called alphanumeric.
 Student section has been represented by single character which is 'J'.
 Student age has been represented by whole number which is 13.
 Student sex has been represented by a single character which is 'F'.

This way we realized that in our day-2-day life we deal with different
types of data like strings, characters, whole numbers which is also called
integers, decimal numbers which is also called floating point numbers.

Similar way when we write our computer program to process different


types of data, we need to specify its type clearly otherwise computer
does not understand how different operations can be performed on that
given data. Different programming languages use different keywords to
specify different data types. For example C and Java programming
languages use int to specify integer data whereas char specifies a
character data type.

Subsequent chapters will show you how to use different data types in
different situations. For now let's check the important data types
available in C, Java and PHP programming languages and what are the
keywords we will use to specify those data types.

3.1.1 C & Java Data Types


Programming languages C and Java support almost same set of data
types, though Java supports additional data types. For now, we are
taking few common data types supported by both the programming
languages:

Value range which can be represented by this


Type Keyword data type

Character char -128 to 127 or 0 to 255

Number int -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647

Small Number short -32,768 to 32,767

Long Number long -2,147,483,648 to 2,147,483,647

Decimal
Number float 1.2E-38 to 3.4E+38 till 6 decimal places

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 28 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

These data types are called primitive data types and you can use these
data types to build more complex data types, which are called user-
defined data type, for example a string will be a sequence of characters.

3.1.2 PHP Data Types

PHP has eight data types but this programming language does not make
use of any keyword to specify a particular data type rather PHP is
intelligent enough to understand given data type automatically.
 String.
 Integer.
 Float (floating point numbers - also called double)
 Boolean.
 Array.
 Object.
 NULL.
 Resource.

Here, string represents a sequence of characters with a length of 1 or


more characters. An integer data type is a non-decimal number between
-2,147,483,648 and 2,147,483,647. A float (floating point number) is a
number with a decimal point or a number in exponential form. A Boolean
represents two possible states: TRUE or FALSE and are often used in
conditional testing. An array stores multiple values in one single variable
while object is a data type which stores data and information on how to
process that data. Object, NULL and Resource are advanced data types in
PHP and will not be covered in this manual

3.2 Variables
This section will teach you another most important concept of
computer programming which is called variables. Actually, variables
are the names you give to computer memory locations which are used to
store values in a computer program.

For example, assume you want to store two values 10 and 20 in your
program and at later stage you want to use these two values. Let's see
how you will do it, here are the following three simple steps:
 Create variables with appropriate names.
 Store your values in those two variables.
 Retrieve and use stored values from the variables.

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 29 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

3.2.1 Creating variables


Creating variables are also called declaring variables in any programming
language. Different programming languages have different ways of
creating variables inside your program. For example, C programming
language has the following simple way of creating variables:

#include <stdio.h>
main()
{
int a;
int b;
}

Above program creates two variables, i.e., reserves two memory


locations with names a and b. We created these variables using int
keyword to specify variable data type which means we want to store
integer values in these two variables. Similar way, you can create
variables to store long, float, char or any other data type. For
example:

/* variable to store long value */


long a;

/* variable to store float value */


float b;

You can create variables of similar type by putting them in a single line
but separated by comma as follows:

#include <stdio.h>
main()
{
int x, b;
}
Following are few important points to remember about variables:
 A variable name can hold a single type of value. For example, if
variable x has been defined as int type, then it can store only integer.
 Most programming languages require a variable creation, i.e.,
declaration before its usage in your program. You can not use a
variable name in your program without creating it, though
programming language like PHP and Python allows you to use a
variable name without creating it.

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 30 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

 You can use a variable name only once inside your program. For
example, if a variable x has been defined to store an integer value,
then you can not define x again to store any other type of value.
 There are programming languages like Python, PHP, Perl, etc., which do
not want you to specify data type at the time of creating variables. So
you can store integer, float or long without specifying their data type.
 You can give any name to a variable like age, sex, salary, year1990
or anything else you like to give, but most of the programming
languages allow using only limited characters in their variables names.
For now, I will suggest to use only a....z, A....Z, 0....9 in your variable
names and start their names using alphabets only instead of digit.
 Almost none of the programming languages allow starting their variable
names with a digit, so1990year will not be a valid variable name
where as year1990 or ye1990ar are valid variable names.

Every programming language provides more rules related to variables


and you will learn them when you will go in further detail of that
programming language. But for now above rules are enough to proceed
and let's see next section, which will teach you how to store values in
defined variables.

3.2.2 Store values in variables


You have seen how we created variables in previous section. Now, let's
store some values in those variables:

#include <stdio.h>
main()
{
int a;
int b;
a = 10;
b = 20;
}

Above program has two additional statements where we are storing 10 in


variable a and 20 is being stored in variable b. Almost all the
programming languages have similar way of storing values in variable
where we keep variable name in the left hand side of an equal sign = and
whatever value we want to store in the variable, we keep that value in
the right hand side.

Now, we have completed two steps, first we created two variables and

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 31 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

then we stored required values in those variables. Now variable a has


value 10 and variable b has value 20. In other words we can say, when
above program is executed, the memory location named a will hold 10
and memory location b will hold 20.

3.2.3 Access stored values in variables


If we do not make use of stored values in the variables then there is no
point in creating variables and storing values in them. We know that
above program has two variables a and b and they store values 10 and
20, respectively. So let's try to print the values stored in these two
variables. Following is a C program, which prints the values stored in
variables:
#include <stdio.h>
main()
{
int a;
int b;
a = 10;
b = 20;
printf( "Value of a = %d\n", a );
printf( "Value of b = %d\n", b );
}

When above program is executed, it produces the following result:

Value of a = 10
Value of b = 20

You must have seen printf() function in previous chapters where we had
used it to print "Hello, World!". This time, we are using it to print the
values of variables. We are making use of %d, which will be replaced
with the values of given variable in printf() statements. We can print both
values using a single printf() statement as follows:
#include <stdio.h>
main()
{
int a, b;
a = 10;
b = 20;
printf( "Value of a = %d and value of b = %d\n", a, b );
}

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 32 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

When above program is executed, it produces the following result:

Value of a = 10 and value of b = 20

If you want to use float variable in C programming, then you will have to
use %f instead of %d, and if you want to print a character value, then
you will have to use %c. Similar way, different data types can be printed
using different % and characters.

3.2.4 Variables in Java


Following is the equivalent program written in Java programming
language. This program will create two variables a and b and very similar
to C programming, then we assign 10 and 20 in these variables and
finally print the values of the two variables in two ways:

public class DemoJava


{
public static void main(String []args)
{
int a;
int b;
a = 10;
b = 20;
System.out.println("Value of a = " + a);
System.out.println("Value of b = " + b);
System.out.println("Value of a = " + a + " and value of b = " + b);
}
}

3.2.5 Variables in PHP

Following is the equivalent program written in PHP. This program will


create two variables a and b and at the same time assign 10 and 20 in
those variables.

PHP does not want you to specify data type at the time of variable
creation and there is also no need of creating variable in advance before
using it. In PHP, a variable starts with the $ sign, followed by the name of
the variable

<?php
$a = 10 ;
$b = 20;

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 33 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

echo "Value of a = ". $a. “< br />”;


echo "Value of b = ". $b. “< br />”;
echo "Value of a = ". $a. " and value of b = ". $b;
?>

Though you can use the following syntax in C and Java programming to
declare variables and assign values at the same time:

#include <stdio.h>
main()
{
int a = 10;
int b = 20;
printf( "Value of a = %d and value of b = %d\n", a, b );
}

3.3 Keywords
So far, you have covered two important concepts called variables and
their data types. You have seen how we have used int, long and float
keywords to specify different data types. You also have seen how we
named our variables to store different values.
Though this section is not required separately because reserved
keywords are part of basic programming syntax but I kept it separate
to explain it right after data types and variables to make it easy to
understand.
Like int, long, and float, there are many other keywords supported by C
programming language which we will use for different purpose. Different
programming languages provide different set of reserved keywords, but
there is one important and common rule in all the programming
languages that we cannot use a reserved keyword to name our variables,
which means we cannot name our variable like int or float rather these
keywords, can only be used to specify a variable data type.

For example, if you will try to use any reserved keyword for the purpose
of variable name, then you will get syntax error, as follows:

#include <stdio.h>
main()
{
int float;
float = 10;

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 34 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

printf( "Value of float = %d\n", float);


}

When you compile above program, it produces the following error:

main.c: In function 'main':


main.c:5:8: error: two or more data types in declaration
specifiers int float;
......

But now let's give proper name to our integer variable, then above
program should compile and execute successfully:

#include <stdio.h>
main()
{
int count;
count = 10;
printf( "Value of count = %d\n", count);
}

3.3.1 C programming reserved keywords


Here is a table having almost all the keywords supported by C
Programming language:
auto else long switch
break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double

3.3.2 Java programming reserved keywords


Here is a table having almost all the keywords supported by Java
Programming language:
abstract assert boolean break
byte case catch char

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 35 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

class const continue default


do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while

3.3.3 PHP programming reserved keywords

abstract and array() as break


case catch class clone const
continue declare default die() do
echo else elseif empty() enddeclare
endfor endforeach endif endswitch endwhile
eval() exit() extends final for
foreach function global if implements
include include_once instanceof interface isset()
list() new or print private
protected public require require_once return
static switch throw try unset()
use var while xor

I know you cannot memorize all these keywords, but I listed them down
for your reference purpose and to explain the concept of reserved
keywords. So just be careful while giving a name to your variable, you
should not use any reserved keyword for that programming language.

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 36 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

3.4 Constants
Constants refer to fixed values that the program may not alter during its
execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a
floating constant, a character constant, or a string literal. There are
enumeration constants as well.
Constants are treated just like regular variables except that their values
cannot be modified after their definition.

3.4.1 Defining Constants


Many programming language use const keyword to declare constants with a
specific type as follows −
const type variable = value;
The following example explains it in detail in C programming Language−
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following
result: -
value of area : 50
Note that it is a good programming practice to define constants in CAPITALS.

Exercises
1. What is a variable?
2. What is the difference between a variable and a constant?
3. How can you create constant in any programming language
4. What is the data type?
5. Describe the importance of keywords in any programming language

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 37 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Chapter 4: Operators
An operator in a programming language is a symbol that tells the
compiler or interpreter to perform specific mathematical, relational or
logical operation and produce final result. This chapter will take you
through important arithmetic and relational operators available in C, Java
and PHP programming languages.

4.1 Arithmetic Operators


Computer programs are widely used for mathematical calculations. We
can write a computer program which can do simple calculation like
adding two numbers (2 + 3) and we can also write a program, which
can solve a complex equation like P(x) = x4 + 7x3 - 5x + 9. If you have
been even a poor student, you must be aware that in first expression 2
and 3 are operands and + is an operator. Similar concept exists in
Computer Programming.

Here we took following two mathematics examples:

2+3
P(x) = x4 + 7x3 - 5x + 9.

These two statements are called arithmetic expressions in a


programming language and plus, minus used in these expressions are
called arithmetic operators and values used in these expressions like 2,
3 and x, etc., are called operands. In their simplest form such
expressions produce numerical results.

Similar way, a programming language provides various arithmetic


operators. Following table lists down few of the important arithmetic
operators available in C programming language. Assume variable A
holds 10 and variable B holds 20, then:

Operator Description Example

+ Adds two operands A + B will give 30


- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
% This gives remainder of an integer division B % A will give 0

Following is a simple example of C Programming to understand above

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 38 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

mathematical operators:

#include <stdio.h>
main()
{
int a, b, c;
a = 10;
b = 20;
c = a + b;
printf( "Value of c = %d\n", c);
c = a - b;
printf( "Value of c = %d\n", c);
c = a * b;
printf( "Value of c = %d\n", c);
c = b / a;
printf( "Value of c = %d\n", c);
c = b % a;
printf( "Value of c = %d\n", c);
}

When above program is executed, it produces the following result:

Value of c = 30
Value of c = -10
Value of c = 200
Value of c = 2
Value of c = 0

4.2 Relational Operators


Consider a situation where we create two variables and assign them some
values as follows:

A = 20
B = 10

Here, it is obvious that variable A is greater than B in values. But how


do we write this in a computer programming language? So, we need
help of some symbols to write this kind of expressions which are called
relational expressions. If we make use of C programming language, then
it will be written as follows:

(A > B)

Here, we used a symbol > and it is called relational operator and in their

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 39 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

simplest form they produce Boolean results which means result will be
either true or false. Similar way, a programming language provides
various relational operators. Following table lists down few of the
important relational operators available in C programming language.
Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example

Checks if the values of two operands are equal or not, (A == B)


==
if yes then condition becomes true. is not true.

Checks if the values of two operands are equal or not, (A != B)


!=
if values are not equal then condition becomes true. is true.
Checks if the value of left operand is greater than the (A > B)
> value of right operand, if yes then condition becomes
true. is not true.

Checks if the value of left operand is less than the (A < B)


< value of right operand, if yes then condition becomes
true. is true.

Checks if the value of left operand is greater than or (A >= B)


>= equal to the value of right operand, if yes then
condition becomes true. is not true.

Checks if the value of left operand is less than or equal (A <= B)


<= to the value of right operand, if yes then condition
becomes true. is true.

Here, I'm going to show you one example of C Programming which


makes use of if conditional statement. Although this statement will
be discussed later in a separate chapter, but in short we use if
statement to check a condition and if condition is true then body of if
statement is executed otherwise body of if statement is skipped

#include <stdio.h>
main()
{
int a, b;
a = 10;
b = 20;
/* Here we check whether a is equal to 10 or not */
if(a == 10)

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 40 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

{
/* if a is equal to 10 then this body will be executed */
printf( "a is equal to 10\n");
}
/* Here we check whether b is equal to 10 or not */
if( b == 10 )
{
/* if b is equal to 10 then this body will be executed */
printf( "b is equal to 10\n");
}
/* Here we check if a is less b than or not */
if( a < b )
{
/* if a is less than b then this body will be executed */
printf( "a is less than b\n");
}
/* Here we check whether a and b are not equal */
if( a != b )
{
/* if a is not equal to b then this body will be executed */
printf( "a is not equal to b\n");
}
}

When above program is executed, it produces the following result:

a is equal to 10 a is less than b


a is not equal to b

4.3 Logical Operators


Logical operators are very important in any programming language and
they help us in taking decision based on certain conditions. Suppose we
want to combine the result of two conditions, then logical AND and OR
logical operators help us in giving final result.

Following table shows all the logical operators supported by C language.


Assume variable A holds 1 and variable B holds 0, then:

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 41 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Operator Description Example

Called Logical AND operator. If both the operands are (A && B)


&&
non-zero, then condition becomes true. is false.

Called Logical OR Operator. If any of the two operands (A || B)


||
is non-zero, then condition becomes true. is true.

Called Logical NOT Operator. Use to reverses the logical !(A && B)
! state of its operand. If a condition is true then Logical
NOT operator will make false. is true.

Try the following example to understand all the logical operators available
in C programming language:
#include <stdio.h>
main()
{
int a = 1;
int b = 0;
if ( a && b )
{
printf("This will never print because condition is false\n" );
}
if ( a || b )
{
printf("This will be printed print because condition is true\n" );
}
if ( !(a && b) )
{
printf("This will be printed print because condition is true\n" );
}
}

When you compile and execute the above program, it produces the
following result:

This will be printed print because condition is true


This will be printed print because condition is true

4.4 Operators in Java


Following is the equivalent program written in Java programming
language. C programming and Java programming languages provide

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 42 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

almost identical set of operators and conditional statements. This


program will create two variables a and b and very similar to C
programming, then we assign 10 and 20 in these variables and finally
we will use different arithmetic and relation operators:

You can try to execute the following program to see the output, which
must be identical to the result generated by the above example.

public class DemoJava


{
public static void main(String []args)
{
int a, b, c;
a = 10;
b = 20;
c = a + b;
System.out.println("Value of c = " + c );
c = a - b;
System.out.println("Value of c = " + c );
c = a * b;
System.out.println("Value of c = " + c );
c = b / a;
System.out.println("Value of c = " + c );
c = b % a;
System.out.println("Value of c = " + c );
if( a == 10 )
{
System.out.println("a is equal to 10" );
}
}
}

4.5 Operators in PHP


Following is the equivalent program written in PHP. This program will
create two variables a and b and same time assign 10 and 20 in those
variables. Fortunately, again C programming and PHP programming
languages provide almost identical set of operators. This program will
create two variables a and b and very similar to C programming, then we
assign 10 and 20 in these variables and finally we will use different
arithmetic and relation operators.

You can try to execute following program to see the output, which must
be identical to the result generated by the above example.

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 43 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

<?php
$a = 10;
$b = 20;
$c = $a + $b;
print "Value of c = ". $c. “<br />”;
$c = $a - $b;
print "Value of c = ". $c. “<br />”;
$c = $a * $b;
print "Value of c = ". $c. “<br />”;
$c = $a / $b;
print "Value of c = ". $c. “<br />”;
$c = $a % $b;
print "Value of c = ". $c. “<br />”;
if($a == 10 ) {
print "a is equal to 10";
}
?>

Exercises
1. What is the operand?
2. Relational operators are used in which situations
3. Describe the importance of logical operators in any programming
Languages
4. Using arithmetic operator “%” what will be displayed by the
following program
#include <stdio.h>
main()
{
int a, b, c;
a = 19;
b = 7;
c = a%b;

printf("Value of c = %d\n", c)
}

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 44 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Chapter 5: Decision Making & Loops


5.1 Decision making
Decision making is critical to computer programming. There will be many
situations when you will be given two or more options and you will have
to select an option based on the given conditions. For example, we want
to print a remark about a student based on secured marks and following
is the situation:

1. Assume given marks are x for a student


2. If given marks are more than 95 then
3. Student is brilliant
4. If given marks are less than 30 then
5. Student is poor
6. If given marks are less than 95 and more than 30 then
7. Student is average

Now, question is how to write programming code to handle such


situation. Almost all the programming languages provide conditional i.e.,
decision making statements which work based on the following flow
diagram:

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 45 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

This manual will give you basic idea on various forms of if statements
and an introduction of switch statement available in most of
programming languages.

5.1.1 if statement
if statement execute a body of statement when condition is true. It has
the following syntax: -

if (boolean_expression) {
/* Statement(s) will execute when boolean expression is true */
}
Let's write a C program with the help of if conditional statements to
convert above given situation into programming code:

#include <stdio.h>
main()
{
int x = 45;
if( x > 95)
{
printf( "Student is brilliant\n");
}
if( x < 30)
{
printf( "Student is poor\n");
}
if(x<95 && x>30)
{
printf( "Student is average\n");
}
}

When above program is executed, it produces the following result:

Student is average

The above program makes use of if conditional statements. Here, first


if statement checks whether given condition i.e., variable x is greater
than 95 or not and if it finds condition is true, then the conditional body is
entered to execute given statements. Here we have only one printf()
statement to print a remark about the student.

The second if statement works in similar way. Finally, third if statement is

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 46 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

executed, here we have following two conditions:

 First condition is x > 95


 Second condition is x < 30

Computer evaluates both the given conditions and then overall result is
combined with the help of binary operator &&. If final result is true then
conditional statement will be executed, otherwise no statement will be
executed.

5.1.2 if...else statement


An if statement can be followed by an optional else statement, which
executes when the boolean expression is false. The syntax of an if...else
statement in C programming language is:

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

Above syntax can be represented in the form of a flow diagram as shown


below:

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 47 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

An if...else statement is useful when we have to take a decision out of


two options. For example, if student secures more marks than 95, then
student is brilliant otherwise not brilliant, such situation can be coded as
follows:

#include <stdio.h>
main()
{
int x = 45;
if( x > 95)
{
printf( "Student is brilliant\n");
}
else
{
printf( "Student is not brilliant\n");
}
}

When above program is executed, it produces the following result:

Student is not brilliant

5.1.3 if...elseif...else statement


An if statement can be followed by an optional else if...else statement,
which is very useful to test various conditions using single if...else if
statement.

When using if, else if, else statements, there are few points to keep in
mind:
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the
else.
 Once an else if succeeds, none of the remaining else if's or else's will
be tested.
The syntax of an if...else if...else statement in C programming language
is:

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 48 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* Executes when the none of the above condition is true */
}

Now with the help of if...elseif...else statement, very first program can
be coded as follows:

#include <stdio.h>
main()
{
int x = 45;
if( x > 95)
{
printf( "Student is brilliant\n");
}
else if( x < 30)
{
printf( "Student is poor\n");
}
else if( x < 95 && x > 30 )
{
printf( "Student is average\n");
}
}

When above program is executed, it produces the following result:

Student is average

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 49 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

5.1.4 The switch statement


A switch statement is an alternative of if statements which allows a
variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each
switch case. This has following syntax:

switch(expression){
case ONE :
statement(s);
break;
case TWO:
statement(s);
break;
......
default :
statement(s);
}

The expression used in a switch statement must give an integer value,


which will be compared for equality with different cases given. Wherever,
expression value matches with case value, the body of that case will be
executed and finally switch will be terminated using break statement. If
break statement is not provided, then computer continues executing
other statements available below to the matched case. If none of the
cases matches, then default case body is executed.

Above syntax can be represented in the form of a flow diagram as shown


below:

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 50 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Now, let's consider another example where we want to write equivalent


English word for the given number. Then, it can be coded as follows:

#include <stdio.h>
main()
{
int x = 2;
switch(x){
case 1 :
printf("One\n");
break;
case 2 :
printf("Two\n");
break;
case 3 :
printf("Three\n");
break;
case 4 :
printf("Four\n");
break;
default :

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 51 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

printf( "None of the above...\n");


}
}

When above program is executed, it produces the following result:

Two

5.2 Decisions in Java


Following is the equivalent program written in Java programming
language. Java programming language also provides if, if...else,
if...elseif...else and switch statements.

You can try to execute the following program to see the output, which
must be identical to the result generated by the above C example.

public class DemoJava


{
public static void main(String []args)
{
int x = 45;
if( x > 95)
{
System.out.println( "Student is brilliant");
}
else if( x < 30)
{
System.out.println( "Student is poor");
}
else if( x < 95 && x > 30 )
{
System.out.println( "Student is average");
}
}
}

5.3 Decisions in PHP


Following is the equivalent program written in PHP. PHP provides if,
if...else, if... elseif...else and switch statements.

You can try to execute following program to see the output:

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 52 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

<?php
$x = 45;
if ($x>95)
echo " Student is brilliant";
elseif ($x<30)
echo " Student is poor";
else
echo " Student is average";
?>
When above program is executed, it produces the following result:

Student is average

5.4 Loops
Let’s consider a situation when you want to write Hello, World! five
times. Here is a simple C program to do the same:

#include <stdio.h>
main()
{
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
}

When above program is executed, it produces the following result:


Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

It was simple, but again let's consider another situation when you want
to write Hello, World! thousand times, what you will do in such
situation? Are we going to write printf() statement thousand times? No,
not at all. Almost all the programming languages provide a concept
called loop, which helps in executing one or more statements up to
desired number of times. All high-level programming languages provide
various forms of loops, which can be used to execute one or more

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 53 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

statements repeatedly.

To conclude, a loop statement allows us to execute a statement or group


of statements multiple times and following is the general form of a loop
statement in most of the programming languages:

This manual has been designed to present programming basic concepts


to non-programmers, so let's discuss about three important loops
available in C programming language.

5.4.1 The while Loop


A while loop available in C Programming language has following syntax:

While (condition)
{
/*....while loop body ....*/
}

Above syntax can be represented in the form of a flow diagram as shown


below:

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 54 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

There are following important points to note about a while loop:


 A while loop starts with a keyword while followed by a condition
enclosed in ( ).
 Further to while() statement you will have body of the loop enclosed in
curly braces {...}.
 A while loop body can have one or more lines of source code to be
executed repeatedly.
 If while loop body has just one line, then its optional to use curly
braces {...}.
 A while loop keeps executing its body as long as given condition is
true. As soon as condition becomes false, the program terminate the
loop and continue executing next statement after while loop body.
 A condition is usually a relational statement, which is evaluated to
either true or false values.

Let's write above C program with the help of a while loop and later we
will discuss how this loop works:

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 55 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

#include <stdio.h>
main()
{
int i = 0;
while ( i < 5 )
{
printf( "Hello, World!\n");
i = i + 1;
}
}

When above program is executed, it produces the following result:

Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

Above program makes use of while loop, which is being used to execute
a set of programming statements enclosed within {....}. Here, computer
first checks whether given condition, i.e., variable "i" is less than 5 or not
and if it finds condition is true then the loop body is entered to execute
given statements. Here, we have the following two statements in the loop
body:

 First statement is printf() function, which prints Hello World!


 Second statement is i = i + 1, which is used to increase the value of
variable i

After executing all the statements given in the loop body, computer goes
back to while(i<5) and given condition, (i<5), is checked again, and the
loop is executed again if condition is true. This process repeats as long as
the given condition remains true which means variable "i" has a value
less than 5.

5.4.2 The do...while Loop


If you have noted while loop, it checks given condition before it executes
given statements of the code. C programming provides another form of
loop, which is called do...while loop and allows to execute a loop body
before checking given condition. This has following syntax:

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 56 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

do
{
/*....do...while loop body ....*/
} while (condition);

Above syntax can be represented in the form of a flow diagram as shown


below:

Writing the above example using do...while loop, the Hello, World will
produce the same result:

#include <stdio.h>
main()
{
int i = 0;
do
{
printf( "Hello, World!\n");
i = i + 1;
}while ( i < 5 );
}

When above program is executed, it produces the following result:

Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 57 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

5.4.3 The For Loop

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

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

for ( init; condition; increment ) {


statement(s);
}
Here is the flow of control in a 'for' loop −

 The init step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to
put a statement here, as long as a semicolon appears.

 Next, the condition is evaluated. If it is true, the body of the loop is


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

 After the body of the 'for' loop executes, the flow of control jumps back
up to the increment statement. This statement allows you to update
any loop control variables. This statement can be left blank, as long as a
semicolon appears after the condition.

 The condition is now evaluated again. If it is true, the loop executes and
the process repeats itself (body of loop, then increment step, and then
again condition). After the condition becomes false, the 'for' loop
terminates.

Above syntax can be represented in the form of a flow diagram as shown


below:

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 58 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Here the above example is wriiten using For loop and it will produce the
same results
 
#include <stdio.h>
main () {
int i;
/* for loop execution */
for(i=0; i<5; i=i+1) {
printf( "Hello, World!\n");
}
}
When the above code is compiled and executed, it produces the following
result −

Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 59 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

Note that, the variable update section is the easiest way for a For loop to
handle changing of the variable. It is possible to do things like i++,
i=i+1, or even i=random(5).

5.4.4 The break statement


When the break statement is encountered inside a loop, the loop is
immediately terminated and program control resumes at the next
statement following the loop. The syntax for a break statement in C is as
follows:

break;

A break statement can be represented in the form of a flow diagram as


shown below:

Following is a variant of the above program, but it will come out after
printing Hello World! only three times:

#include <stdio.h>
main()
{
int i = 0;
do
{
printf("Hello, World!\n");
i = i + 1;
if(i==3 )

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 60 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

{
break;
}
}while(i<5);
}

When above program is executed, it produces the following result:


Hello, World!
Hello, World!
Hello, World!

5.4.5 The continue statement


The continue statement in C programming language works somewhat
like the break statement. Instead of forcing termination, however,
continue forces the next iteration of the loop to take place, skipping any
code in between. The syntax for a continue statement in C is as follows:

continue;

A continue statement can be represented in the form of a flow diagram


as shown below:

Following is a variant of the above program but it will skip printing when
variable has a value equal to 3:

#include <stdio.h>
main()
{

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 61 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

int i = 0;
do
{
if(i==3)
{
i=i+1;
continue;
}
printf("Hello, World!\n");
i = i + 1;
}while (i< 5);
}

When above program is executed, it produces the following result:

Hello, World!
Hello, World!
Hello, World!
Hello, World!

5.5 Loops in Java


Following is the equivalent program written in Java programming
language. Java programming language also provides while, do...while
and For loops. Following program will be used to print Hello, World! five
times as we did in case of C Programming:
You can try to execute following program to see the output, which must
be identical to the result generated by the above example.
public class DemoJava
{
public static void main(String []args)
{
int i = 0;
while ( i < 5 )
{
System.out.println("Hello, World!");
i = i + 1;
}
}
}

The break and continue statements in Java programming work very


similar way as in C programming.

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
PAGE 62 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL

5.6 Loops in PHP


Following is the equivalent program written in PHP. PHP also provides
while, do...while and For loops. Following program will be used to print
Hello, World! five times as we did in case of C Programming.

You can try to execute following program to see the output.

<?php
$i = 0;
while ($i < 5) {
print "Hello, World!" ;
$i = $i + 1 ;
}
?>
When above program is executed, it produces the following result:

Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

The break and continue statements in PHP programming work very


similar way as they work in C programming.

Exercises
1. Describe the syntax of if--else conditional statement
2. What are the valid places for the keyword break to appear
3. Does a break is required by default case in switch statement?
4. Which control loop is recommended if you have to execute set of
statements for fixed number of times?
5. What is an infinite loop?
6. What will be the output of the following program
#include<stdio.h> 
main()  

   for(1;2;3) 
   printf("Hello"); 

 University of Dar es Salaam Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz.
022 2410645
Chapter 6: Numbers & Characters
6.1 Numbers in Programming
Every programming language provides support for manipulating different
types of numbers like simple whole integer, floating point number. The
programming languages like C, Java and PHP categorize these numbers
in several categories based on their nature.

Let's go back and check data types chapter, where we listed down core
data types related to numbers:

Value range which can be represented by this


Type Keyword data type

Character char -128 to 127 or 0 to 255

Number int -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647

Small Number short -32,768 to 32,767

Long Number long -2,147,483,648 to 2,147,483,647

Decimal
Number float 1.2E-38 to 3.4E+38 till 6 decimal places

These data types are called primitive data types and you can use these
data types to build more data types, which are called user-defined data
type.

We have seen various mathematical and logical operations on numbers


during a discussion on operators. So we know how to add numbers,
subtract numbers, divide numbers, etc.

First let's see how to print various types of numbers available in C


programming language:

#include <stdio.h>
main()
{
short s;
int i;
long l;
float f;
double d;
s= 10;
i = 1000;
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 64 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

l = 1000000;
f = 230.47;
d = 30949.374;
printf( "s: %d\n", s);
printf( "i: %d\n", i);
printf( "l: %ld\n", l);
printf( "f: %.3f\n", f);
printf( "d: %.3f\n", d);
}

Rest of the coding is very obvious but we used %.3f to print float and
double, which indicates number of digits after decimal to be printed.
When above program is executed, it produces the following result:

s: 10
i: 1000
l: 1000000
f: 230.470
d: 30949.374

6.1.1 Math Operations on Numbers


Following table lists down various useful built-in mathematical functions
available in C programming language which can be used for various
important mathematical calculations.

For example, if you want to calculate square root of a number for


example, 2304, then you have built-in function available to calculate
square root for this number.
SN Function & Purpose
1 double cos(double); This function takes an angle (as a double) and returns
the cosine.
2 double sin(double); This function takes an angle (as a double) and returns
the sine.
3 double tan(double); This function takes an angle (as a double) and returns
the tangent.
4 double log(double); This function takes a number and returns the natural
log of that number.
5 double pow(double, double); The first is a number you wish to raise and
the second is the power you wish to raise it to.
6 double hypot(double, double); If you pass this function the length of two
sides of a right triangle, it will return you the length of the hypotenuse.
7 double sqrt(double); You pass this function a number and it gives you this
square root.
8 int abs(int); This function returns the absolute value of an integer that is
passed to it.
9 double fabs(double); This function returns the absolute value of any
decimal number passed to it.

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 65 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

SN Function & Purpose


10 double floor(double); Finds the integer which is less than or equal to the
argument passed to it.

To utilize these functions, you need to include the math header file
<math.h> header file in your program in similar way you have included
stdio.h:

#include <stdio.h>
#include <math.h>
main()
{
short s;
int i;
long l;
float f;
double d;
s= 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 2.374;
printf( "sin(s): %f\n", sin(s));
printf( "abs(i): %f\n", abs(i));
printf( "floor(f): %f\n", floor(f));
printf( "sqrt(f): %f\n", sqrt(f));
printf( "pow(d, 2): %f\n", pow(d, 2));
}

When above program is executed, it produces the following result:

sin(s): -0.544021
abs(i): -0.544021
floor(f): 230.000000
sqrt(f): 15.181238
pow(d, 2): 5.635876

Other than above usage, you will use numbers in loop counting, flag
representation, true or false values in C programming.

6.2 Numbers in Java


Following is the equivalent program written in Java programming
language. Java programming language also provides almost all numeric
data types available in C programming.

You can try to execute the following program to see the output, which is

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 66 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

identical to the result generated by the above C example.

public class DemoJava


{
public static void main(String []args)
{
short s;
int i;
long l;
float f;
double d;
s = 10;
i = 1000;
l = 1000000L;
f = 230.47f;
d = 30949.374;
System.out.format( "s: %d\n", s);
System.out.format( "i: %d\n", i);
System.out.format( "l: %d\n", l);
System.out.format( "f: %f\n", f);
System.out.format( "d: %f\n", d);
}
}

When above program is executed, it produces the following result:

s: 10
i: 1000
l: 1000000
f: 230.470001
d: 30949.374000

Java also provides a full range of built-in functions for mathematical


calculation and you can use them in very similar way you have used
them in C programming.

6.3 Numbers in PHP


PHP is little different from C and Java and categorize numbers in
integers and doubles.

Following is the equivalent program written in PHP:


<?php
$s = 10;
$i = 1000;
$l = 1000000 ;
$f = 230.47;
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 67 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

$d = 30949.374;
print "s: ". $s. “ <br />” ;
print "i: ",. $i. “ <br />” ;
print "l: ", .$l. “ <br />” ;
print "f: ",. $f. “ <br />” ;
print "d: ",. $d. “ <br />” ;
?>
When above program is executed, it produces the following result:

s: 10
i: 1000
I: 1000000
f: 230.47
d: 30949.374

PHP also provides a full range of built-in functions for mathematical


calculation and you can use them in very similar way you have used them
in C programming.

6.4 Characters in Programming


It was easy to learn about numbers in computer because we are playing
with numbers from childhood. Numbers are simple 1, 2, 3.....10.20,
300.345, etc.

It's even further easy to learn about characters in computer


programming because you are playing with characters even before you
started playing with numbers. Yes these are simple alphabets like a, b, c,
d....A, B, C, D, .....but with an exception that in computer programming
any single digit number like 0, 1, 2,....and special characters like $, %,
+, -.... etc., are also treated as characters and to assign them in a
character type variable you simply need to put them inside a single
quotes. For example, following statement defines a character type
variable ch and we assign a value 'a' to it:

char ch = 'a';

Here, ch is a variable of character type which can hold a character of the


implementation's character set and 'a' is called character literal or a
character constant. Not only a, b, c,....but when any number like 1, 2,
3.... or any special character like !, @, #, #, $,.... is kept inside a single
quotes, then they will be treated as a character literal and can be
assigned to a variable of character type, so following is a valid
statement:

char ch = '1';

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 68 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

A character data type consumes 8 bits of memory which means you can
store anything in a character whose ASCII value lies in between -127 to
127, so in total it can hold one of 256 different values. Bottom-line is
that a character data type can store any of the characters available on
your keyboard including special characters like !, @, #, #, $, %, ^, &, *,
(, ), _, +, {, }, etc.

It's worth to explain it little further that you can keep only a single
alphabet or single digit number inside single quotes and more than one
alphabets or digits are not allowed inside single quotes. So following
statements are invalid in C programming:

char ch1 = 'ab';


char ch2 = '10';

Following is a simple example, which shows how to define, assign and


print characters in C Programming language:

#include <stdio.h>
main()
{
char ch1;
char ch2;
char ch3;
char ch4;
ch1 = 'a'; ch2 = '1'; ch3 = '$'; ch4 = '+';
printf( "ch1: %c\n", ch1);
printf( "ch2: %c\n", ch2);
printf( "ch3: %c\n", ch3);
printf( "ch4: %c\n", ch4);
}

Here, we used %c to print a character data type. When above program is


executed, it produces the following result:

ch1: a
ch2: 1
ch3: $
ch4: +

6.4.1 Escape Sequences:


Many programming languages support a concept called Escape
Sequence. So when a character is preceded by a backslash (\), then it
is called an escape sequence and has special meaning to the compiler.
For example, following is a valid character and it is called new line
character:

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 69 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

char ch = '\n';

Here, character n has been preceded by a backslash (\), so now it has


special meaning which is a new line but keep in mind that backslash (\)
has special meaning with few characters only, so following will not have
any meaning in C programming and it will be assumed as an invalid
statement:

char ch = '\1';

Following table shows correct escape sequences available in C


programming language:

Escape Sequence Description

\t Inserts a tab in the text at this point.


\b Inserts a backspace in the text at this point.
\n Inserts a new line in the text at this point.
\r Inserts a carriage return in the text at this point.
\f Inserts a form feed in the text at this point.
\' Inserts a single quote character in the text at this point.
\" Inserts a double quote character in the text at this point.
\\ Inserts a backslash character in the text at this point.

Following is a simple example which shows how the compiler interprets an


escape sequence in a print statement:

#include <stdio.h>
main()
{
char ch1;
char ch2;
char ch3;
char ch4;
ch1 = '\t';
ch2 = '\n';
printf("Test for tabspace %c and a newline %c will start here", ch1, ch2);
}

When above program is executed, it produces the following result:


Test for tabspace and a newline

will start here

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 70 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

6.5 Characters in Java


Following is the equivalent program written in Java programming
language. Java programming language handles character data type in
similar way as we have seen in C programming language. Though Java
provides additional support for character manipulation which you will
know it when you will drill down this programming language

You can try to execute the following program to see the output, which
must be identical to the result generated by the above C example.

public class DemoJava


{
public static void main(String []args)
{
char ch1;
char ch2;
char ch3;
char ch4;
ch1 = 'a';
ch2 = '1';
ch3 = '$';
ch4 = '+';
System.out.format( "ch1: %c\n", ch1);
System.out.format( "ch2: %c\n", ch2);
System.out.format( "ch3: %c\n", ch3);
System.out.format( "ch4: %c\n", ch4);
}
}
When above program is executed, it produces the following result:

ch1: a
ch2: 1
ch3: $
ch4: +

Java also supports escape sequence in very similar way you have used
them in C programming.

6.6 Characters in PHP


PHP does not support any character data type but all the characters are
treated as string, which is a sequence of characters and we will study
strings in a separate chapter. But you do not need to have any special
arrangement while using a single character in PHP.
PHP also supports escape sequence in very similar way you have used
them in C programming.
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 71 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

Exercises
1. What are the primitive data types?
2. Mention the built in math function which accept decimal number and
convert it to integer number
3. Describe the importance of Escape Sequence in any programming
language
4. How characters are treated in PHP programming language?

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 72 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

Chapter 7: Arrays
7.1 Introduction
Consider a situation, where we need to store 5 integer numbers. If we use
simple variable and data type concepts, then we need 5 variables of int
data type and program will be something as follows:

#include <stdio.h>
main()
{
int number1;
int number2;
int number3;
int number4;
int number5;
number1 = 10;
number2 = 20;
number3 = 30;
number4 = 40;
number5 = 50;
printf("number1: %d\n", number1);
printf("number2: %d\n", number2);
printf("number3: %d\n", number3);
printf("number4: %d\n", number4);
printf("number5: %d\n", number5);
}

It was simple, because we had to store just 5 integer numbers. Now let's
assume we have to store 5000 integer numbers, so what is next? Are we
going to use 5000 variables?

To handle such situation, almost all the programming languages provide


a concept called the array. An array is a data structure, which can store
a fixed-size collection of elements of the same data type. An array is
used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.

So instead of declaring individual variables, such as number1, number2,


..., and number99, you just declare one array variable number of
integer type and use number1[0], number1[1], and ..., number1[99] to
represent individual variables. Here, 0, 1, 2, .....99 are index associated
with variable and they are being used to represent individual elements
available in the array.

All arrays consist of contiguous memory locations. The lowest address


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

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 73 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

element.

7.2 Create Arrays


To create an array variable in C, a programmer specifies the type of the
elements and the number of elements to be stored in that array.
Following is a simple syntax to create an array in C programming:

type arrayName [ arraySize ];

This is called a single-dimensional array. The arraySize must be an


integer constant greater than zero and type can be any valid C data type.
For example, now to declare a 10-element array called numberof type
int , use this statement:

int number[10];

Now, number is a variable array, which is sufficient to hold up to 10


integer numbers.

7.3 Initializing Arrays


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

int number[5] = {10, 20, 30, 40, 50};

The number of values between braces { } cannot be larger than the


number of elements that we declare for the array between square
brackets [ ].

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

int number[] = {10, 20, 30, 40, 50};

You will create exactly the same array as you did in the previous
example. Following is an example to assign a single element of the array:

number[4] = 50;

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 74 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

The above statement assigns element number 5th in the array with a
value of 50. All arrays have 0 as the index of their first element which is
also called base index and last index of an array will be total size of the
array minus 1. Following is the pictorial representation of the same array
we discussed above:

7.4 Accessing Array Elements


An element is accessed by indexing the array name. This is done by
placing the index of the element within square brackets after the name of
the array. For example:

int var = number[9];

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

#include <stdio.h>
int main ()
{
int number[10];
/* number is an array of 10 integers */
int i = 0;
/* Initialize elements of array n to 0 */
while( i < 10 )
{
/* Set element at location i to i + 100 */
number[ i ] = i + 100;
i = i + 1;
}
/* Output each array element's value */
i = 0;
while( i < 10 )
{
printf("number[%d] = %d\n", i, number[i] );
i = i + 1;
}
return 0;
}

When the above code is compiled and executed, it produces the following
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 75 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

result:

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

7.5 Arrays in Java


Following is the equivalent program written in Java programming
language. Java programming language also supports array, but there is a
little difference to create them in different ways using new operator
available in Java programming language.

You can try to execute the following program to see the output, which
must be identical to the result generated by the above C example.

public class DemoJava


{
public static void main(String []args)
{
int[] number = new int[10];
int i = 0;
while( i < 10 )
{
number[ i ] = i + 100;
i = i + 1;
}
i = 0;
while( i < 10 )
{
System.out.format( "number[%d] = %d\n", i, number[i] );
i = i + 1;
}
}
}

When above program is executed, it produces the following result:

number[0] = 100
number[1] = 101
number[2] = 102
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 76 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

number[3] = 103
number[4] = 104
number[5] = 105
number[6] = 106
number[7] = 107
number[8] = 108
number[9] = 109

7.6 Arrays PHP


PHP programming language also supports array, but array is created in
different ways i.e. using array () function or direct assign the value to
array variable.
Following is the equivalent program written in PHP:

<?php
/*using array function */
$number = array( 1, 2, 3, 4, 5);
/* direct assigning a value */
$i = 0;
while (i < 10) {
/*Appending elements in the array */
$numbers[$i] =$i + 100;
$i = $i + 1;
}
$i = 0;
while($i < 10) {
/*Accessing elements from the array*/
echo "number[". $i. "] = ". numbers[ $i ]. “<br />” ;
$i = $i + 1;
}
?>

When above program is executed, it produces the following result:

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

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 77 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

Exercises

1. Define an array
2. Describe the importance of array in any programming language
3. How can you access the elements of array in the array variables
4. Create the array variable which will store even integers from 5 to 15
5. What will be the position of number 12 in the above created array?

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 78 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

Chapter 8: Strings
8.1 Introduction
During our discussion about characters in computer programming, we
learnt that character data type deals with a single character and you can
assign any character from your keyboard to a character type variable.
Now, let's move a little bit ahead and consider a situation where we need
to store more than one character in a variable. We have seen that C
programming does not allow storing more than one character in a
character type variable. So following statements are invalid in C
programming and produce syntax error:

char ch1 = 'ab';


char ch2 = '10';

We also have seen how we can store more than one value of similar data
type in a variable using array concept. If recap then, here is the syntax
to store and print 5 numbers in an array of int type:

#include <stdio.h>

main()
{
int number[5] = {10, 20, 30, 40,
50}; int i = 0;

while( i < 5 )
{
printf("number[%d] = %d\n", i, number[i]
);
i = i + 1;
}
}

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

number[0] = 10
number[1] = 20
number[2] = 30
number[3] = 40
number[4] = 50

Now, let's define an array of 5 characters in the similar way as we did for
numbers and try to print them:

#include <stdio.h>
main()
{
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 79 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

char ch[5] = {'H', 'e', 'l', 'l', 'o'};


int i = 0;
while( i < 5 )
{
printf("ch[%d] = %c\n", i, ch[i] );
i = i + 1;
}
}

Here, we used %c to print character value. When the above code is


compiled and executed, it produces the following result:

ch[0] = H
ch[1] = e
ch[2] = l
ch[3] = l
ch[4] = o

If you are done with the above example, then I think you understood
about strings in C programming, because strings in C are represented
as arrays of characters. C programming simplified the assignment and
printing of strings. Let's check same example once again with simplified
syntax:

#include <stdio.h>
main()
{
char ch[5] = "Hello";
int i = 0;
/* Print as a complete string */
printf("String = %s\n", ch);

/* Print character by character */


while( i < 5 )
{
printf("ch[%d] = %c\n", i, ch[i] );
i = i + 1;
}
}

Here, we used %s to print full string value using array name ch, which is
actually beginning of the memory address holding ch variable as shown
below:

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 80 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

Though it's not visible from the above examples, but internally C
program assigns null character '\0' as the last character of every string.
This indicates the end of the string and it means if you want to store a 5
character string in an array then you must define array size of 6 as a
good practice, though C does not complain about it.

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

String = Hell
ch[0] = H
ch[1] = e
ch[2] = l
ch[3] = l
ch[4] = o

8.2 Basic String Concepts


Based on the above discussion we can conclude the following important
points to remember about strings in C programming language:

 Strings in C are represented as arrays of characters.

 We can constitute a string in C programming by assigning character


by character into an array of characters.

 We can constitute a string in C programming by assigning a complete


string enclosed in double quote.

 We can print a string character by character using array subscript or a


complete string by using array name without subscript.

 Though it's not visible from the above examples, but internally C
program assigns null character'\0' as the last character of every
string. This indicates the end of the string and it means if you want to
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 81 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

store a 5-character string in an array then you must define array size
of 6 as a good practice, though C does not complain about it.

 Most of the programming languages provide built-in functions to


manipulate strings, i.e., you can concatenate strings, you can search
from a string, you can take sub string from the string. For a detail you
can check detailed book for C or other programming languages.

8.3 Strings in Java


Though you can use character array to store strings but Java is an
advanced programming language and its designers tried to provide
additional functionality like Java provides string as a built-in data type like
any other data type. So it means you can define strings directly instead of
defining them as array of characters.

Following is the equivalent program written in Java programming


language. Java programming makes use of new operator to create string
variable as shown below in the program:

You can try to execute the following program to see the output:

public class DemoJava


{
public static void main(String []args)
{
String str = new String("Hello");
System.out.println( "String = " + str );
}
}

When above program is executed, it produces the following result:

String = Hello

8.4 Strings in PHP


Creating strings in PHP is as simple as simply assigning a string into a
PHP variable using single or double quote as shown below:

<?php $str = “Hello World”; ?>

Following is a simple program, which creates two strings and print them
using print() function:

<?php
$var1 = 'Hello World!';
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 82 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

$var2 = "PHP Programming";


print "var1 = ". $var1.”<br />;
print "var2 = ". $var2;
?>
When above program is executed, it produces the following result:

var1 = Hello World!

var2 = PHP Programming

PHP does not support a character type; these are treated as strings of
length one.

Exercises

1. What is a string length?


2. Describe how string values are treated in C and Java programming
Languages
3. Use C or Java to create string variable which can store string value of
“Day Worker”
4. Create the program which will print the word “Worker” from string
variable created above

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 83 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

Chapter 9: Functions
9.1 Definition
A function is a block of organized, reusable code that is used to perform
a single, related action. Functions provide better modularity for your
application and a high degree of code reusing. You already have seen
various functions like printf() and main(). These are called built-in
functions provided by the language itself, but we can write our own
functions as well and this manual will teach you how to write and use
those functions in C programming language.

Good thing about functions is that they are famous with several names.
Different programming languages name them differently like functions,
methods, sub-routines, procedures, etc. So when you come across any
such terminology, then just imagine about the same concept, which we
are going to discuss in this manual.

Let's start with a program where we will define two arrays of numbers
and then from each array, we will find the biggest number. As we already
have seen following are the steps to find out maximum number from a
given set of numbers:

1. Get a list of numbers L1, L2, L3....LN


2. Assume L1 is the largest, Set max = L1
3. Take next number Li from the list and do the following
4. If max is less than Li
5. Set max = Li
6. If Li is last number from the list then
7. Print value stored in max and come out

8. Else repeat same process starting from step 3

Let's translate above program in C programming language:

#include <stdio.h>
main()
{
int set1[5] = {10, 20, 30, 40, 50};
int set2[5] = {101, 201, 301, 401, 501};
int i, max;
/* Process first set of numbers available in set1[] */
max = set1[0];
i = 1;
while( i < 5 )
{

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 84 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

if( max < set1[i] )


{
max = set1[i];
}
i = i + 1;
}
printf("Max in first set = %d\n", max );
/* Now process second set of numbers available in set2[] */
max = set2[0];
i = 1;
while( i < 5 )
{
if( max < set2[i] )
{
max = set2[i];
}
i = i + 1;
}
printf("Max in second set = %d\n", max );
}

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

Max in first set = 50

Max in second set = 501

If you are clear about the above example, then it will become easy to
understand why we need a function. Here in above example, I took only
two sets of numbers set1, and set2 but consider a situation where we
have 10 or more similar sets of numbers to find out maximum numbers
from each set. In such situation, we will have to repeat same processing
10 or more times and ultimately program will become too large with
repeated code. To handle such situation, we write our functions where we
try to keep source code which will be used again and again in our
programming.

Now, let's see how to define a function in C programming language and


then subsequent section will explain how to use that function:

9.2 Creating a Function:


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

return_type function_name( parameter list )


{
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 85 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

body of the function


return [expression];
}

A function definition in C programming language consists of a function


header and a function body. Here are all the parts of a function:
 Return Type: A function may return a value. The return_type is the
data type of the value the function returns. Some functions perform the
desired operations without returning a value. In this case, the
return_type is the keyword void.
 Function Name: This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
 Parameter List: A parameter is like a placeholder. When a function is
invoked, you pass a value as a parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.
 Function Body: The function body contains a collection of statements
that define what the function does.
 Return Statement: terminates current function and returns the value
to the caller function

9.3 Calling a Function:


While creating a C function, you give a definition of what the function has
to do. To use a function, you will have to call that function to perform the
defined task.

Now, let's write above example with the help of a function:

#include <stdio.h>
int getMax(int set[] )
{
int i, max;
max = set[0];
i = 1;
while( i < 5 )
{
if(max< set[i] )
{
max = set[i];
}
i = i + 1;
}
return max;

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 86 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

}
main()
{
int set1[5] = {10, 20, 30, 40, 50};
int set2[5] = {101, 201, 301, 401, 501};
int max;
/* Process first set of numbers available in set1[] */
max = getMax(set1);
printf("Max in first set = %d\n", max );
/* Now process second set of numbers available in set2[] */
max = getMax(set2);
printf("Max in second set = %d\n", max );
}

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

Max in first set = 50


Max in second set = 501

A variable declared within the function can only be accessed within that
function. That is called the scope of variable. A scope in any
programming is a region of the program where a defined variable can
have its existence and beyond that variable it cannot be accessed. There
are three places where variables can be declared in any programming
language −

 Inside a function which is called local variables.


 Outside of all functions which is called global variables.
 In the definition of function parameters which are called formal
parameters.

Local variables can be used only by statements that are inside that
function; they are not known to functions outside their own.

A global variable can be accessed by any function. That is, a global


variable is available for use throughout your entire program after its
declaration.

The following program show how global variables are used in a program.
Here variable g is global while variables a and b are local to main()
function.

#include <stdio.h>
/* global variable declaration */
int g;

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 87 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

int main () {
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}

9.4 Function Arguments


If a function is to use arguments, it must declare variables that accept
the values of the arguments. These variables are called the formal
parameters of the function.

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

While calling a function, there are two ways in which arguments can be
passed to a function −

 Call by value: This method copies the actual value of an argument into
the formal parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.

 Call by reference: This method copies the address of an argument into


the formal parameter. Inside the function, the address is used to access
the actual argument used in the call. This means that changes made to
the parameter affect the argument.

By default, C programming uses call by value to pass arguments. In general,


it means the code within a function cannot alter the arguments used to call
the function. Consider the function swap() definition as follows.

/* function definition to swap the values */


void swap(int x, int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
Now, let us call the function swap() by passing actual values as in the
following example −

#include <stdio.h>
/* function declaration */
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 88 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

void swap(int x, int y);


int main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
Let us put the above code in a single C file, compile and execute it, it will
produce the following result −

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there are no changes in the values, though they had been
changed inside the function.
To pass a value by reference, argument pointers are passed to the functions
just like any other value. So accordingly you need to declare the function
parameters as pointer types as in the following function swap(), which
exchanges the values of the two integer variables pointed to, by their
arguments.

/* function definition to swap the values */


void swap(int *x, int *y) {

int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */

return;
}
Let us now call the function swap() by passing values by reference as in the
following example −

#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main () {
/* local variable definition */
int a = 100;
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 89 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

int b = 200;

printf("Before swap, value of a : %d\n", a );


printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values.


* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);

printf("After swap, value of a : %d\n", a );


printf("After swap, value of b : %d\n", b );

return 0;
}
Let us put the above code in a single C file, compile and execute it, to
produce the following result −

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
It shows that the change has reflected outside the function as well, unlike
call by value where the changes do not reflect outside the function.

For now, its enough for you to know about what are functions and how do
they work. If you understood this concept then you can proceed for a
detailed to drill it down further.

9.5 Functions in Java


If you are clear about functions in C programming, then it’s easy to
understand them in Java as well. Java programming names them as
methods, but the rest of the concepts remain more or less same as we
discussed in C programming.

Following is the equivalent program written in Java programming


language. You can try to execute the following program to see the output:

public class DemoJava


{
public static void main(String []args)
{
int[] set1 = {10, 20, 30, 40, 50};
int[] set2 = {101, 201, 301, 401, 501};
int max;
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 90 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

/* Process first set of numbers available in set1[] */


max = getMax(set1);
System.out.format("Max in first set = %d\n", max );
/* Now process second set of numbers available in set2[] */
max = getMax(set2);
System.out.format("Max in second set = %d\n", max );
}
public static int getMax( int set[] )
{
int i, max;
max = set[0];
i = 1;
while( i < 5 )
{
if( max < set[i] )
{
max = set[i];
}
i = i + 1;
}
return max;
}
}

When above program is executed, it produces the following result:

Max in first set = 50


Max in second set = 501

9.6 Functions in PHP


Once again, if you already understood the concept of functions in C and
Java programming, then PHP is not much different in defining and calling
functions. Following is basic syntax of defining a function in PHP:

function function_name( parameter list ){


body of the function
}

So using this syntax of function in PHP, above example can be written as


follows:
<?php
function getMax($set) {
$max = $set[0];
$i = 1;
while( $i < 5 ) {
if($max < $set[$i] ) {
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 91 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

$max = $set[$i];
$i = $i + 1;
}
}
return $max;
}
$set1 = array(10, 20, 30, 40, 50);
$set2 = arra(101, 201, 301, 401, 501);
/*Process first set of numbers available in set1[] */
$max = getMax($set1)
print "Max in first set = ". $max.”<br />”;
/*Now process second set of numbers available in set2[] */
$max = getMax($set2)
print "Max in second set = ".$max ;
?>

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

Max in first set = 50


Max in second set = 501

Exercises

1. What is a function?
2. Differentiate between user defined functions and built in functions
3. Explain the purpose of the function sprintf().
4. Describe the Function Arguments
5. What are the different ways of passing parameters to the functions?
Which to use when?

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 92 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

Chapter 10: File I/O


Though it's simple to handle file I/O in computer programming, it's really
difficult to teach what are the files and how we perform input and output
into those files. But let's start with learning what files in computer
terminology are.

10.1 Computer Files


A computer file is used to store data in digital format like plain text,
image data or any other content. Computer files can be organized inside
different directories. So, files are used to keep digital data where as
directories are used to keep files.

Computer files can be considered as the digital counterpart of paper


documents, which traditionally are kept in office. While doing
programming, you keep your source code in text files with different
extensions, for example, C programming files have .c extension, Java
programming files have .java extension and PHP programming file have
extension as .php.

10.2 File Input/Output


Usually, you create files using text editors like notepad, MS Word, MS
Excel or MS Powerpoint, etc., but many times, we need to create files
using computer program as well. We can modify existing file using a
computer program.

File input means data, which we write into a file and file output means
data, which we read from a file. Actually, input and output terms are
more related to screen input and output where we display our result on
the screen which is called output and if we provide some input to our
program from command prompt, then it's called input.

For now, it's enough to remember that writing into a file is file input and
reading something from the file is file output.

10.3 File Operation Modes


Before we start playing with any file using our program, either we need
to create a new file if it does not exist or open an already existing file. In
either case, we can open a file in the following modes:

 Read Only Mode: If you are going just to read an existing file and
you do not want to write any further content in the file, then you will
open file in read only mode. Almost, all the programming languages
provide syntax to open file in read only mode.
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 93 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

 Write Only Mode: If you are going to write into either an existing file
or newly created file but you do not want to read any written content
in the file, then you will open file in write only mode. All the
programming languages provide syntax to open file in write only
mode.

 Read & Write Mode: If you are going to read as well as write into the
same file, then you will open file in read & write mode. Almost, all the
programming languages provide syntax to open file in read & write
mode.

 Append Mode: When you open a file for writing, it allows you to start
writing your content from the beginning of the file but writing content
from the beginning in a file, which already has some content, will
overwrite already existing content. We prefer to open a file in such a
way that we should start appending content in already existing content
of the file. So in such situation, we open file in append mode. Append
mode is ultimately a write mode, which allows content to be appended
in the last of the file. Almost, all the programming languages provide
syntax to open file in append mode.

Now, following section will teach you how to open a fresh new file, how
to write content in that file and later how to read and append more
content into the same file.

10.4 Opening Files


You can use the fopen() function to create a new file or to open an
existing file, this call will initialize an object of the type FILE, which
contains all the information necessary to control the stream. Following is
the prototype, i.e., signature of this function call:

FILE *fopen( const char * filename, const char * mode );

Here, filename is string literal, which you will use to name your file and
access mode can have one of the following values:

Mode Description
r Opens an existing text file for reading purpose.
Opens a text file for writing, if it does not exist then a new file is
w created. Here, your program will start writing content from the
beginning of the file.
Opens a text file for writing in appending mode, if it does not exist
a then a new file is created. Here, your program will start appending
content in the existing file content.
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 94 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

Mode Description
r+ Opens a text file for reading and writing both.
Opens a text file for reading and writing both. It first truncate the
w+ file to zero length if it exists otherwise create the file if it does not
exist.
a+ Opens a text file for reading and writing both. It creates the file if it
does not exist. The reading will start from the beginning but writing
can only be appended.

10.5 Closing a File


To close a file, use the fclose( ) function. The prototype i.e. signature of
this function is:

int fclose( FILE *fp );

The fclose() function returns zero on success, or EOF, special


character, if there is an error in closing the file. This function actually
flushes any data still pending in the buffer to the file, closes the file, and
releases any memory used for the file. The EOF is a constant defined in
the header file stdio.h.

There are various functions provided by C standard library to read and


write a file character by character or in the form of a fixed length string.
Let us see few of them.

10.6 Writing a File


Following is the simplest function to write individual characters to a
stream:

int fputc( int c, FILE *fp );

The function fputc() writes the character value of the argument c to the
output stream referenced by fp. It returns the written character written
on success, otherwise EOF if there is an error. You can use the following
functions to write a null-terminated string to a stream:

int fputs( const char *s, FILE *fp );

The function fputs() writes the string s into the file referenced by fp. It
returns a non-negative value on success, otherwise EOF is returned in
case of any error. You can use int fprintf(FILE *fp,const char
*format, ...) function as well to write a string into a file. Try the following
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 95 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

example:

#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}

When the above code is compiled and executed, it creates a new file
test.txt in /tmp directory and writes two lines using two different
functions. Let us read this file in next section.

10.7 Reading a File


Following is the simplest function to read a text file character by
character:

int fgetc( FILE * fp );

The fgetc() function reads a character from the input file referenced by
fp. The return value is the character read, or in case of any error it
returns EOF. The following functions allow you to read a string from a
stream:

char *fgets( char *buf, int n, FILE *fp );

The functions fgets() reads up to n - 1 characters from the input stream


referenced by fp. It copies the read string into the buffer buf, appending
a null character to terminate the string.

If this function encounters a newline character '\n' or the end of the file
EOF before they have read the maximum number of characters, then it
returns only the characters read up to that point including new line
character. You can also use int fscanf(FILE *fp, const char *format,
...) function to read strings from a file but it stops reading after the first
space character encounters.

#include <stdio.h>
main()
{
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 96 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

fscanf(fp, "%s", buff);


printf("1 : %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("2: %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("3: %s\n", buff);
fclose(fp);
}

When the above code is compiled and executed, it reads the file created
in previous section and produces the following result:

1 : This

2: is testing for fprintf...

3: This is testing for fputs...

Let's see a little more detail about what happened here. First fscanf()
method read just This because after that it encountered a space, second
call is for fgets(), which reads the remaining line till it encountered end
of line. Finally, last call fgets() reads second line completely.

10.8 File I/O in Java


Java programming language provides even richer set of functions to
handle File I/O. For a complete detail, I will suggest you to check Java
books.

Here, we will see a simple Java program, which is equal to C program


explained above. This program will open a text file and will write few text
lines into that file and close the file. Finally, same file is opened and then
read that text from already created file. You can try to execute following
program to see the output:

import java.io.*;
public class DemoJava
{
public static void main(String []args) throws IOException
{
File file = new File("/tmp/java.txt");
// Create a File
file.createNewFile();
// Creates a FileWriter Object using file object
FileWriter writer = new FileWriter(file);
// Writes the content to the file

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 97 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

writer.write("This is testing for Java write...\n");


writer.write("This is second line...\n");

// Flush the memory and close the file


writer.flush();
writer.close();
// Creates a FileReader Object
FileReader reader = new FileReader(file);
char [] a = new char[100];
// Read file content in the array
reader.read(a);
System.out.println( a );
// Close the file
reader.close();
}
}

When above program is executed, it produces the following result:

This is testing for Java write...

This is second line...

10.9 File I/O in PHP


Following program shows the same functionality to create a new file, open
file, write some content into the file and finally read the same file:

<?php
// Create a new file
if(!file_exists ("tmp/php.txt"))
touch("tmp/php.txt");

// open a file in writing mode


$fp = fopen("tmp/php.txt", "w") or die("could not open a file");
//Writes the content to the file
fwrite($fp, "This is testing for php write…\n”);
fwrite($fp, “This is second line…\n”);
//Close the file
fclose($fp) ;
//Open existing file in read mode
$fp = fopen("tmp/php.txt", "r") or die("could not open a file");
//Read file content in a variable
while(!feof($fp))
{
$str = fgets( $fp, 1024 );
print "$str<br />";
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 98 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

}
//Close opened file
fclose($fp);
?>

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

This is testing for php write...

This is second line...

If you use fopen() on a file that does not exist, it will create it, given that
the file is opened for writing (w) or appending (a).

Exercises

1. Describe the importance of computer file


2. Describe the file opening mode of “w+”.
3. Name a function which can be used to close the file stream.
4. Using the fopen() function how can you open a file for reading only

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 99 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

Chapter 11: Object Oriented Programming


Concepts
11.1 Introduction
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.

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. The design method used in
procedural programming is called Top Down Design. This is where you
start with a problem (procedure) and then systematically break the
problem down into sub problems (sub procedures).
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.

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 collection of objects that have common properties and
behaviours. A class is a combination of state (data) and behaviour
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 100 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

(methods). You can think a class as prototypes from which objects are
created. So let's say you want to use a person in your program, a class
called 'person' would describe what a person looks like and what a person
can do. Examples of pure object-oriented languages include C#, Java,
Perl and Python while C++ and PHP support both paradigms.
The prime purpose of C++ programming was to add object orientation to the
C programming language, which itself is one of the most powerful
programming languages. In this chapter therefore, we will use C++ to
present features of OOP

11.2 Basic Features of OOP

11.2.1 Class

A class is basically a combination of a set of rules on which we will work in


a specific program. It contains definitions of new data types like fields or
variables, operations that we will perform on data (methods) and access
rules for that data.

When you define a class, you define a blueprint for an object. This doesn't
actually define any data, but it does define what the class name means, that
is, what an object of the class will consist of and what operations can be
performed on such an object.

In C++ a class definition starts with the keyword class followed by the class
name; and the class body, enclosed by a pair of curly braces. A class
definition must be followed either by a semicolon or a list of declarations. For
example we defined the Box data type using the keyword class as follows:

class Box 

   public: 
      double length;   // Length of a box 
      double breadth;  // Breadth of a box 
      double height;   // Height of a box 
}; 
The keyword public is access modifier which determines the scope where
attributes can be accedssed. Other access modifiers are protected and private.
Discussion of access modifiers is beyond this manual.

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 101 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

11.2.2 Object
Objects are defined as an instance of a class. Objects are built on the
model defined by the class. In most Programming Languages, an object
can be created in memory using the "new" keyword. In C++, we create
objects of a class with exactly the same sort of declaration that we
declare variables of basic types. Following statements declare two objects
of class Box:
Box Box1;      // Declare Box1 of type Box 
Box Box2;      // Declare Box2 of type Box 

Both of the objects Box1 and Box2 will have their own copy of data
members. The public data members of objects of a class can be accessed
using the direct member access operator (.) as follow: -

Box1.height = 5.0;   // assign value to height attribute in Box1 object 
Box2.height = 10.0;  // assign value to height attribute in Box2 object 
 

11.2.3 Inheritance

Inheritance is a feature by which a class acquires attributes of another


class. The class that provides its attributes is known as the base class and
the class that accepts those attributes is known as a derived class. It
allows programmers to enhance their class without reconstructing it.

One of the most useful aspects of Inheritance in object-oriented


programming is code reusability. This is a very important since this
feature helps to reduce the code size.

In most Programming Languages, inheritance is enhanced using the


“extends" keyword. To define a derived class in C++, we use a full colon
as follows

class BaseClass 

 
}; 
class DerivedClass : BaseClass 

 
}; 

Now an object of a derived class can use the accessible properties of the
base class without defining it in the derived class.

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 102 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

11.2.4 Encapsulation
Encapsulation is placing the data and the functions that work on that data
in the same place. While working with procedural languages, it is not
always clear which functions work on which variables but binds together
the data and functions that manipulate the data, and that keeps both safe
from outside interference and misuse. Data encapsulation led to the
important OOP concept of data hiding.

C++ supports the properties of encapsulation and data hiding through the
creation of classes. Data and functions can easily be hidden by using access
modifiers. For example:
class Box 

   public: 
      double getVolume(void) 
      { 
         return length * breadth * height; 
      } 
   private: 
      double length;      // Length of a box 
      double breadth;     // Breadth of a box 
      double height;      // Height of a box 
}; 
 
11.2.5 Abstraction

Data abstraction refers to, providing only essential information to the


outside word and hiding their background details ie. to represent the
needed information in program without presenting the details.

Data abstraction is a programming (and design) technique that relies on the


separation of interface and implementation.

For example, in C++ we use classes to define our own abstract data types
(ADT). You can use the cout object of class ostream to stream data to
standard output like this:

#include <iostream> 
using namespace std; 
 int main( ) 

   cout<<"Hello C++"<<endl; 

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 103 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

   return 0; 

Here, you don't need to understand how cout displays the text on the user's
screen. You need only know the public interface and the underlying
implementation of cout is free to change.

11.2.6 Polymorphism

Polymorphism means the ability to take more than one form. An


operation may exhibit different behaviours in different instances. The
behaviour depends on the data types used in the operation.

Polymorphism is the capability of a method to do different things based


on the object that it is acting upon. In other words, polymorphism allows
you define one interface and have multiple implementations.

The implementations of Polymorphism is beyond this manual

11.3 Advantages of OOP


Object-Oriented Programming has the following advantages over
conventional approaches:

 OOP provides a clear modular structure for programs which makes it


good for defining abstract data types where implementation details are
hidden and the unit has a clearly defined interface.
 OOP makes it easy to maintain and modify existing code as new objects
can be created with small differences to existing ones.
 OOP provides a good framework for code libraries where supplied
software components can be easily adapted and modified by the
programmer.

Exercises
1. Define the term programming paradigms
2. Differentiate between procedural paradigms and object oriented
paradigms
3. What are the basic concepts of OOP?
4. What is Encapsulation?
5. Differentiate between abstraction and encapsulation.
6. What is Inheritance?
.

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 104 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

References
1. Richard M, 2009. Programming A Beginner's Guide, McGraw-Hill
Osborne Media;ISBN-13: 978-0071624725

2. Matthias F, Robert B F, Matthew F, 2001. How to Design Programs: An


Introduction to Programming and Computing, The MIT Press;ISBN-
13: 978-0262062183

3. Thomas H. C, Charles E. L et al, 2009. Introduction to Algorithms, The


MIT Press;ISBN-13: 978-0262033848

4. Michael Vine, 2007. C Programming for the Absolute Beginner 2nd Edition,
Cengage Learning PTR; ISBN-10: 1598634801, ISBN-13: 978-
1598634808

5. Brian W. Kernighan, 1988. The C Programming Language 2nd Edition,


Prentice Hall; ISBN-10: 0131103628, ISBN-13: 978-0131103627

6. Timothy Budd, 2001. An Introduction to Object-Oriented


Programming 3rd Edition, Pearson; ISBN-10: 0201760312, ISBN-13:
978-0201760316

7. C Wu, 2005. An Introduction to Object-Oriented Programming With


Java, McGraw-Hill; ISBN-13: 978-0072946529

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 105 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

C - Environment Setup

If you want to set up your environment for C programming language, you


need the following two software tools available on your computer, (a) Text
Editor and (b) The C Compiler.

Text Editor

This will be used to type your program. Examples of few a editors include
Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.

The name and version of text editors can vary on different operating
systems. For example, Notepad will be used on Windows, and vim or vi can
be used on windows as well as on Linux or UNIX.

The files you create with your editor are called the source files and they
contain the program source codes. The source files for C programs are
typically named with the extension ".c".

Before starting your programming, make sure you have one text editor in
place and you have enough experience to write a computer program, save it
in a file, compile it and finally execute it.

The C Compiler

The source code written in source file is the human readable source for your
program. It needs to be "compiled", into machine language so that your CPU
can actually execute the program as per the instructions given.

The compiler compiles the source codes into final executable programs. The
most frequently used and free available compiler is the GNU C/C++ compiler,
otherwise you can have compilers either from HP or Solaris if you have the
respective operating systems.

The following section explains how to install GNU C/C++ compiler on various
OS. We keep mentioning C/C++ together because GNU gcc compiler works
for both C and C++ programming languages.

Installation on UNIX/Linux

If you are using Linux or UNIX, then check whether GCC is installed on your
system by entering the following command from the command line −
 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645
PAGE 106 DESIGN AND IMPLEMENTATION OF DATABASE-DRIVEN WEBSITES MANUAL

$ gcc -v
If you have GNU compiler installed on your machine, then it should print a
message as follows −

Using built-in specs.


Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr .......
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
If GCC is not installed, then you will have to install it yourself using the
detailed instructions available at http://gcc.gnu.org/install/

This tutorial has been written based on Linux and all the given examples
have been compiled on the Cent OS flavor of the Linux system.

Installation on Mac OS

If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode
development environment from Apple's web site and follow the simple
installation instructions. Once you have Xcode setup, you will be able to use
GNU compiler for C/C++.

Xcode is currently available at developer.apple.com/technologies/tools/.

Installation on Windows

To install GCC on Windows, you need to install MinGW. To install MinGW, go


to the MinGW homepage, www.mingw.org, and follow the link to the MinGW
download page. Download the latest version of the MinGW installation
program, which should be named MinGW-<version>.exe.

While installing Min GW, at a minimum, you must install gcc-core, gcc-g++,
binutils, and the MinGW runtime, but you may wish to install more.

Add the bin subdirectory of your MinGW installation to your PATH


environment variable, so that you can specify these tools on the command
line by their simple names.

After the installation is complete, you will be able to run gcc, g++, ar, ranlib,
dlltool, and several other GNU tools from the Windows command line.

 University Computing Centre. One stop Centre for your ICT Solutions. www.ucc.co.tz. 022 2410645

You might also like