Introduction To Computer Programming (1) 1
Introduction To Computer Programming (1) 1
COMPUTING CENTRE
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
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
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
I assume, you did not understand what I have written about which I
have used in the above definition:
Sequence of instructions
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.
<?php Print "Hello, World!" ; ?>
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
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
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
Different flow chart symbols have different meanings. The most common
flow chart symbols are:
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
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
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'
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
Example 4
SET total to zero
REPEAT
READ Temperature
IF Temperature > Freezing THEN
INCREMENT total
END IF
UNTIL Temperature < zero
Print total
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.
However, this manual has been designed to give you an idea about the
following most popular programming languages:
C Programming
Java Programming
PHP Programming
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
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.
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
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:
#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.
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
2.4.3 Comments
The C program can have statements enclosed inside /*.....*/. Such
statements are called 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.
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
#include <stdio.h>
main()
{
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
}
#include <stdio.h>\n
\n
main()\n
{
\n
\t/* printf() function to write Hello, World! */ \n
\tprintf(\t"Hello, World!"\t);\n
\n
}\n
#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
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!" );
}
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:
$./demo
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.
#include <stdio.h>
main()
{
printf("Hello, World!")
}
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 (==).
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.
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
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
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
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:
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
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.
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.
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.
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.
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
#include <stdio.h>
main()
{
int a;
int 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.
#include <stdio.h>
main()
{
int a;
int b;
a = 10;
b = 20;
}
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
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
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.
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
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
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);
}
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
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.
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.
2+3
P(x) = x4 + 7x3 - 5x + 9.
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);
}
Value of c = 30
Value of c = -10
Value of c = 200
Value of c = 2
Value of c = 0
A = 20
B = 10
(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:
#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");
}
}
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
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:
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
You can try to execute the following program to see the output, which
must be identical to the result generated by the above example.
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
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");
}
}
Student is average
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
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.
if(boolean_expression)
{
/* Statement(s) will execute if the boolean expression is true */
}
else
{
/* Statement(s) will execute if the boolean expression is false */
}
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
#include <stdio.h>
main()
{
int x = 45;
if( x > 95)
{
printf( "Student is brilliant\n");
}
else
{
printf( "Student is not brilliant\n");
}
}
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");
}
}
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
switch(expression){
case ONE :
statement(s);
break;
case TWO:
statement(s);
break;
......
default :
statement(s);
}
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
#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
Two
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.
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");
}
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.
While (condition)
{
/*....while loop body ....*/
}
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
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;
}
}
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:
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.
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);
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 );
}
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
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 −
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.
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.
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).
break;
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);
}
continue;
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);
}
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 62 INTRODUCTION TO COMPUTER PROGRAMMING MANUAL
<?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!
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:
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.
#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
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
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));
}
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.
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
s: 10
i: 1000
l: 1000000
f: 230.470001
d: 30949.374000
$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
char ch = 'a';
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:
#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);
}
ch1: a
ch2: 1
ch3: $
ch4: +
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';
char ch = '\1';
#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);
}
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
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.
ch1: a
ch2: 1
ch3: $
ch4: +
Java also supports escape sequence in very similar way you have used
them in C programming.
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?
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.
int number[10];
If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write:
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:
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
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.
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
<?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;
}
?>
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:
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
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);
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
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.
You can try to execute the following program to see the output:
String = Hello
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
PHP does not support a character type; these are treated as strings of
length one.
Exercises
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:
#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
When the above code is compiled and executed, it produces the following
result:
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.
#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:
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 −
Local variables can be used only by statements that are inside that
function; they are not known to functions outside their own.
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;
}
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.
#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
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;
return 0;
}
Let us put the above code in a single C file, compile and execute it, to
produce the following result −
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.
$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 ;
?>
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
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.
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.
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.
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:
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.
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:
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
When the above code is compiled and executed, it reads the file created
in previous section and produces the following result:
1 : This
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.
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
<?php
// Create a new file
if(!file_exists ("tmp/php.txt"))
touch("tmp/php.txt");
}
//Close opened file
fclose($fp);
?>
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
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
(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.1 Class
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
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
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
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
4. Michael Vine, 2007. C Programming for the Absolute Beginner 2nd Edition,
Cengage Learning PTR; ISBN-10: 1598634801, ISBN-13: 978-
1598634808
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
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 −
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++.
Installation on Windows
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.
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