You are on page 1of 52

ALGORITHM

INTRODUCTION
Computer hardware refers to the physical parts the computer such as monitor, keyboard, CPU, hard
disk … Software refers to the set of instructions called program that directs the hardware. Programs
are written to solve problems or carry out tasks on the computer, program is like the translation of
the various steps to solve a problem or carry out tasks called algorithm into a language that the
computer can understand. So as we are thinking of an algorithm, we must keep in mind that the
computer will only do what we instruct it to do. Therefore we must know the computer problem
solving approach.

COMPUTER PROBLEM SOLVING APPROACH


The first step in writing instructions to carry out a task with the computer is to determine what the
output should be, that is exactly what the task should produce.

The second step is to identify the data input required for obtaining the output.

The third step is to determine how to process the inputs in order to obtain the desired output. That is
to determine what formula, method, way or steps that can be used to obtain the output.

The problem solving approach should be adopted each time we are looking for the algorithm that
produces a solution of problem.

Example: A car travels 150km in 2h. How fast is the car moving?

Output: speed

Input: distance, time

Processes: Ask for the distance and time, set the speed to: distance/time, display the speed.

PRODUCTION OF AN ALGORITHEM
The process of producing an algorithm has several steps:

1. Read the problem carefully until you understand what the algorithm should do and have the
clear idea of the output.
2. Apply the problem solving approach that is determine the output, the input and processes,
methods, ways or steps to apply for solving the problem.
3. Implement the chosen processes to solve the problem while respecting the conditions, if
there is any.
4. Test the algorithm, that is try the algorithm with the exact or some randomly values to
ensure the correctness and the effectiveness of the algorithm.
Criteria for a good algorithm
An algorithm is a finite set of instructions which, if followed, accomplish a particular task. In
addition every algorithm must satisfy the following criteria:

1. input: there must be zero or more quantities which are externally supplied;
2. output: at least one quantity must be produced;
3. definiteness: each instruction must be clear and unambiguous;
4. finiteness: if we trace out the instructions of an algorithm, then for all cases the
algorithm will terminate after a finite number of steps;
5. Effectiveness: every instruction must be sufficiently basic that it can in principle be
carried out by a person using only pencil and paper. It is not enough that each
operation be definite, but it must also be feasible.

NOTATION FOR EXPRESSING ALOGORITHM

An algorithm can be expressed in a variety of notations. The common ones are: Natural
languages, pseudo codes and flowchart.

Natural language.
A natural language is a human written or spoken language used by a community. Natural
language expressions of algorithms are rarely used for complex or technical processes.
Below is an algorithm (in natural language) which collects two numbers , sum up the
numbers , finds the difference of the numbers and then displays both the sum and the
difference of the numbers.

1. Get two numbers


2. Find the sum of the numbers
3. Find the difference between the numbers
4. Display the sum
5. Display the difference

FLOWCHARTS
A flowchart is a diagrammatic or symbolic representation that illustrates the sequence of operations
to be performed to get the solution of a problem, using symbols called charts and arrows . These
charts play a vital role in the programming of the problem and are quite helpful in understanding the
logic of complicated and lengthy problems. In flowcharts, symbols are used to represent activities
while arrows to represent the direction of activity through the process. Typical examples of these
symbols include the following:
Terminal symbol, oval shape, it Indicates the starting or ending of the program, process, or interrupt
program.

Process symbol, a rectangle, it indicates any type of internal operation inside the Processor or
Memory

Input/output symbol, a parallelogram, it represents any Input / Output (I/O) operation, Indicating
that the computer is to obtain data or output results

Decision symbol, the diamond represents a decision branching point or a question that can be
answered in a binary format (Yes/No, True/False)

Connector symbol, the circle allows the flowchart to be drawn without intersecting lines or without a
reverse flow. It also indicates that the flow continues where a matching symbol (containing the same
letter) has been placed.

Predefined Process Used to invoke a subroutine or an interrupt program.


Flow Lines Shows direction of flow.

Off-page-connector, used to indicate that the flowchart continue in the next page

Example: let us use the flowchart to write an algorithm to perform the summation of two
numbers a and b , taking from the user.

start A

sum=a+b
write (a,b)

write (sum )
read (a,b)

A end

Pseudo codes
Unlike a flowchart which is a graphic-based tool, pseudo codes are text-based algorithmic
design tools. In other words, a pseudo code is a way of writing an algorithm using short
natural language statements that are similar to programming language statements. Each
statement here expresses just an action or a step that the computer has to carry out in
performing the task. With pseudo codes every algorithm must start with the keyword
“Algorithm”, following by the name you have chosen for the algorithm, and must end by the
keyword “end”, the general syntax is :

Algorithem name-of –the-algorithm

Var variable1,variable2 (as types)

Begin

statment1

statment2

statment2

end.

THE CONCEPT OF VARIABLE AND BASIC ACTIONS


THE CONCEPT OF VARIABLE

Viewed as a container of value, a variable is a memory location that the CPU uses for storing data in
the course of solving a problem. An elementary variable can only contain a single value at a given
time.

CHARACTERISTIC OF A VARIABLE

A variable is characterized by its name, type, nature, use, initial value, final value and the meaning.
These characteristics enable to clearly understand the role of each variable in the algorithm.

a) The name or the identifier


It helps to uniquely identify the variable in the algorithm. It consists of a set of alphanumeric
Rules used in naming variables:

 The first character must be a letter


 They may include letters, numbers, and underscore (_)
 You cannot use a reserved word (word needed by algorithm)

b) The type of a variable


It indicates the set in which the variable takes its values. That is the range of values that the
variable can contain. It also implicitly indicates the operations that can be performed with a
variable.
c) The nature of a variable
A variable can be constant (having a value which must never change)or changeable(variable)
d) The use of a variable
An object can be:
 An input : that is, used to store data needed to solve a problem
 An output: that is used to store a result of a problem
 An input/output : that it contains data at the beginning and the result at the end of
the algorithm
 An internal variable: that is , it contain neither a data nor the result of the problem.
This type of variable is used to facilitate the resolution of the problem.
e) The initial value.
This is the value that a variable takes for the first time in the algorithm. It can be difficult to
predict, In such case we allow the variable without an initial value.
f) The final value

This is the value that object contains at the end of its use in the algorithm.
g) The meaning of the variable.

It is advisable to indicate in a short sentence the role of each variable in the algorithm. It can
be a comment.

Simple data type


In algorithm, we distinguish various types of data as follows:
a) Integer.
An integer is an variable that takes its value in a finite subset of integers (Z). The subset
of integers generally depends on the target machine. The subset of integers is [2 31; 231-1].

Operations on the integers


The arithmetic operations defined on integers are:
 Addition (+)
 Subtraction(+)
 Multiplication(*)
 Division (div)

The relational operators applicable to integer are.

Less than (<)


Less than or equal (<=)
Greater than (>)
Greater than or equal (>=)
Different from (!=)
Equal (=)

b) Real
Real numbers take their values in a finite set of integers and decimals. The operators
allowed on real are:
 Division (/)
 All others operators above can be applied on real.
c) Characters
These are symbols used to represent words or phrases in natural languages. Each of
these symbols is represented in the computer by an 8 bits code known as ASCII
(American Standard Code for Information Interchange). We distinguish alphabetic,
numeric and special character. A constant character is written in single quote.
d) Boolean
A Boolean expression is an expression that yields two possible results (that is TRUE or
FALSE). On such object, possible logical operator like AND, OR and NOT can be
performed.

5) ELEMENTARY ACTIONS
To solve a problem using the computer, it is important to known the list of primitive
actions of the computer. A primitive action is the one that the computer can perform
without any further additional information. Generally the computer we use can perform
the following actions.
 Assign a value (constant or not) to a variable using the symbol
e.g variable name
Value
 Get the value of a variable from an input device (such as keyboard), using the
keyword Read
e.g Read (value), Read(value1, value2……)

 Display the value of a variable on an output device (like the monitor) using the
keyword Write
e.g Write (“enter the value of a ”)

AVAILABLE CONTROL STRUCTURE


SEQUENCE
This is a sequence of statements that are executed in the same order in which
they appear in the algorithm or program, as from the first to the last.
e.g
algorithm name
(declaration)
Begin
Statement1
Statement2
statement3
.
.
.
Statement n
End
CONDITIONAL BRANCHING IF

This structure chooses a single subtask from a list of one or more alternatives others according to
the prescribed condition. A condition is an expression that yields Boolean results (that is “TRUE” or
“FALSE”). The relational operators used to express condition are:

Less than (<)


Less than or equal (<=)
Greater than (>)
Greater than or equal (>=)
Different from (!=)
Equal (=)
Conditional branching can be built from simple ones using the following logical operators as “AND”,
“OR” and “NOT”. Eg if (a>b)and (a>c).
Conditional branching can be implemented using the IF statement whose syntax is as follow:
1st form.
If (condition) then
Statement

Endif.
Exercise : represent the flow chart of this syntax.
Exercise ; write an algorithm to computer and display the solution of the equation : ax+b=0.

2nd form
If (condition) then
Statement1
Else
Statement2
End if
Here the condition is evaluated, if it is true, the statement1 is executed and if it is false, statements2
is executed.
Exercise: represent the flow chart of this syntax and write the algorithm to compute the absolute
value of an integer. The write an algorithm that reads two integers and displays their maximum.
Exercise write an algorithm that request for the coefficients a, b and c of the second quadratic
equation ax2+bx+c=0 , then compute the solution of the equation.

CONDITIONAL BRANCHING SWITCH


This is the mechanism to jump into a series of statements, the exact starting point depend on the
value of an expression. The syntax is the following:
Switch (expression)
Case value1: statement1
Case value2: statement2
.
.
Case value n: statement n
Default : statement
End switch

Exercise write an algorithm that a binary digit and display it in letter. Write an algorithm that reads a
positive integer corresponding to the number of a day within the week, compute and displays the
day’s name in full.

Exercise : write an algorithm that reads the average of a student and displays the grade . the grades
are assigned as follows:
100% : excellent, greater than or equal to 90% : very good, greater than or equal to 80% : good,
greater than or equal to 60%: fairly good, greater than or equal to 50%: average, greater than or
equal to : fail.
REPETITIONS (LOOPS)
This structure allows the same sequence to be executed over and over a number of time during the
program execution. This repetition is called “looping”. A loop is an instruction or set of instructions
that is carried out repeatedly. They are typically three types of loop: the while loop, the Repeat loop
and the For loop.

THE WHILE LOOP


Syntax
While (condition) do
Statement
End while.

In this loop, the condition is evaluated, if it is true then, “statement” is executed, condition is
reevaluated and the cycle continues, until condition becomes false, which mean the end of the loop.

Exercise: draw the flowchart of the above loop. Write an algorithm which reads a positive integer n
and then compute and display the sum of the first n integers.

THE REPEAT UNTIL LOOP


SYMTAX

Repeat
Statement
Until (condition)

In this loop, the statement is executed and the condition is evaluated, if the condition is false , then
statement is executed again , and the cycle continue until the condition becomes true, it is the end of
the loop.
Exercise : draw the flowchart of this loop and write an algorithm that reads a positive integer n,
compute and displays its square root.
Write an algorithm that reads a sequence of positive values, computes and displays the sum, the
number of values, the minimum , the maximum, the average , the variance and the standard
deviation. You may indicate the end of the sequence by a negative or null value.
FOR LOOP
Syntax
For counter from start_value to stop_value
Statements
Endfor

Here , statement will be executed for a value of counter from start_value to stop_value. The for loop
is used when the number of iteration is known in advance.
Exercise draw the flowchart of the For loop and write an algorithm that read a number n, computes
and displays its factorial.
Write an algorithm that requests for a positive integer n, computes and displays the sum of its
factors.

DATA STRUCTURE
A data structure is a specialized format for organizing and storing data in the
computer. Any data structure is designed to organize data to suit a particular purpose
so that it can be access and worked with in appropriate ways. Some of the most
commonly used data structures are: arrays, records, linked lists, tree, queues, stack
and tables.
a) Arrays
An array is defined as a set of data items of the same types. The individual data in
an array are called elements, each element has a unique identifying index, which
is used to access that particular element in the set. Arrays allow us to in one
structure what we would normally put in many variables. They facilitate the
organization and search for individual elements of the storage medium. Sets of
elements such as examination marks for a class may be conveniently stored and
arranged into a sequence and referred to by indexes. Eg Mark= (10 92 25 36
14). An element may be accessed separately by stating its position in the array,
eg Mark(1) will refer to 10 in the example above. Arrays can be more than one
dimension. A one dimensional array is called vector while a two dimensional
array is called matrix.
b) String
A string is a sequence of consecutive characters that are manipulated as group.
Some few operations can be applied to string such as concatenation which adds
one string onto the end of the other, that data & type would then be datatype.
Strings are declared as packed arrays of characters, for example string_name=
array_name[1…3] OF CHAR.
c) Records
A record is collection of related data elements (called fields ) that are treated as a
single unit. Record will be easily understood if compared to arrays. Records differ
from arrays in that data, the individual data items in records may differ in type
whereas all the data items in the array have the same type. Examples of records

Candidate := record
Candidate_number: integer
Candidate_namer: String
Candidate_mark: real
Endrecord
In this example the word candidate is the record name and Candidate_number is
a record’s field.
d) Linked Lists
A finite set of entries with a certain order is known as a list. Two
common forms of list data structures are list linked list and arrays. A
linked list is a data structure consisting of a number of nodes, each
containing one element and one or more links to others nodes. Linked
list permit insertion and removal of nodes at any point of the list.
Linked list do no allow random access
e) Queue
In computer science, a queue (/ˈkjuː/ KEW) is a particular kind of
abstract data type or collection in which the entities in the collection
are kept in order and the principal (or only) operations on the
collection are the addition of entities to the back terminal position,
known as enqueue, and removal of entities from the front terminal
position, known as dequeue. This makes the queue a First-In-First-Out
(FIFO) data structure. In a FIFO data structure, the first element added
to the queue will be the first one to be removed. This is equivalent to
the requirement that once a new element is added, all elements that
were added before have to be removed before the new element can
be removed.
f) Stalk
In computer science, a stack is a particular kind of data structure or
collection in which the principal (or only) operations on the collection
are the addition of an entity to the collection, known as push and
removal of an entity, known as pop. The relation between the push
and pop operations is such that the stack is a Last-In-First-Out (LIFO)
data structure. In a LIFO data structure, the last element added to the
structure must be the first one to be removed. This is equivalent to
the requirement that, considered as a linear data structure, or more
abstractly a sequential collection, the push and pop operations occur
only at one end of the structure, referred to as the top of the stack. G)

g) Trees
In computer science, a tree is a type of data structure in which each
element is attached to one or more elements directly beneath it. The
elements of this hierarchical data structure are called nodes. The
node which at the top of the tree is called root and the node with no
children is called leaf.

h) Tables
A table is a group of records, each of which is composed of fields
common to all the other records. The main purpose of this data
structure is to improve data access by reducing search time.
i) Files
A file is made up of one or more tables.

TOP-DOWN DESIGN, BOTTOM-UP DESIGN AND STEPWISE REFINEMENT

A system consists of components, which have components of their own; indeed


a system is a hierarchy of components. The highest-level component
corresponds to the total system. To design such hierarchies there are two pos-
sible approaches: top-down and bottom-up. The top-down approach starts
from the highest-level component of the hierarchy and proceeds through to
lower levels. By contrast, a bottom-up approach starts with the lowest-level
component of the hierarchy and proceeds through progressively higher levels
to the top-level component.

A top-down design approach starts by identifying the major components of the


system, decomposing them into their lower-level components and iterating
until the desired level of detail is achieved. Top-down design methods often
result in some form of stepwise refinement. Starting from an abstract design, in
each step the design is refined to a more concrete level, until we reach a level
where no more refinement is needed and the design can be implemented
directly. The top-down approach has been promulgated by many researchers
and has been found to be extremely useful for design. Most design
methodologies are based on the top-down approach.

A top-down approach is suitable only if the specifications of the system are


clearly known and the system development is from scratch. However, if a
system is to be built from an existing system, a bottom-up approach is more
suitable, as it starts from some existing components. So, for example, if an
iterative enhancement type of process is being followed, in later iterations, the
bottom-up approach could be more suitable (in the first iteration a top-down
approach can be used).

A top-down approach (also known as stepwise design) is essentially the


breaking down of a system to gain insight into the sub-systems that make it up.
In a top-down approach an overview of the system is formulated, specifying
but not detailing any first-level subsystems. Each subsystem is then refined in
yet greater detail, sometimes in many additional subsystem levels, until the
entire specification is reduced to base elements. Once these base elements are
recognised then we can build these as computer modules. Once they are built
we can put them together, making the entire system from these individual
components.

Top-down design - in which design begins by specifying complex pieces and


then dividing them into successively smaller pieces

Example: Making Pancakes

To show you an example of Top-Down design we'll take the act of making
pancakes. Starting from the top we have the task to:

Make some pancakes

But saying that by itself isn't enough to actually make any pancakes, we need to
break the task down:

Make some pancakes

Organise Kitchen

Make Pancakes

Serve

Each of these tasks can then be broken down further:

Organise Kitchen

Clean surfaces

Get out mixing bowl, whisk, spoon, sieve

Get out plain flour, salt, eggs, full fat milk, butter

Put on apron

Make Pancakes

Sift salt and flour into bowl

Break eggs into bowl Whisk


Add water and milk

Add butter

Whisk

Cook

Serve

And each of these tasks can be broken down further, let us take a look at the
Cook:

Get pan to temperature

Pour batter in Spread batter to edges

Use plastic spatula to check bottom of pancake

When brown, flip

Use plastic spatula to check bottom of pancake

When brown finish

We can break down some of these tasks even further. So starting at a single
point, the creation of a pancake, we have broken down the task into it
individual parts

Exercise: Top-down design

Draw a top-down design tree to three level depth for making a modern First
Person Shooter

Answer :

Your answer probably won't be the same as this as the question is open to
interpretation, but hopefully it'll be similar:

Make First Person Shooter

Create graphics

Characters
Guns

Maps

Interface

Create sounds

Music

SFX

Create AI

Non-playable characters

Monsters

A bottom-up design approach starts with designing the most basic or primitive
components and proceeds to higher-level components that use these lower-
level components. Bottom-up methods work with layers of abstraction. Starting
from the very bottom, operations that provide a layer of abstraction are
implemented. The operations of this layer are then used to implement more
powerful operations and a still higher layer of abstraction, until the stage is
reached where the operations supported by the layer are those desired by the
system.

Refinement is a generic term of computer science that encompasses various


approaches for producing correct computer programs and simplifying existing
programs to enable their formal verification.

Stepwise Refinement is an old way of developing a computer program by first


describing general functions, then breaking each function down into details.
PROGRAM AND PROGRAMMING

PROGRAM
A computer program is a series of organised instructions that directs a computer to perform
tasks. Without programs, computers are useless. A program is like a guidelines. It contains a
list of variables (called ingredients) and a list of statements (called directions) that tell the
computer what to do with the variables.

PROGRAMMING
Programming is a creation of a set of commands or instructions which directs a computer in
carrying out a task.

PROGRAMMING LANGUAGE
A programming language is a set of words, symbols and codes that enables humans to
communicate with computers.

EXAMPLES PROGRAMMING LANGUAGE


Examples of programming languages are:

 BASIC (Beginner’s All Purpose Symbolic Instruction Code) ,  Pascal, C ,  Smalltalk.


ASSEMBLER
An assembler is a computer program for translating assembly language — essentially, a
mnemonic representation of machine language — into machine language. For example in
intel 80836, the assembly language for the ’no operation’ command is NOP and its machine
code representation is 10010000.

INTERPRETER
The interpreter will read each codes converts it to machine code and executes it line by line
until the end of the program. Examples of interpreter-based language are BASIC, Logo and
Smalltalk.

COMPILER
The compiler converts the source code (written program) into machine code which is a file
consisting of binary machine code that can be executed on a computer. If the compiler
encounters any errors, it records them in the program-listing file. When a user wants to run
the program, the object program is loaded into the memory of the computer and the program
instructions begin executing. A compiled code generally runs faster than programs based on
interpreted language. Several programming languages like C++, Pascal and COBOL used
compilers as their translators.

GENERATIONS OF PROGRAMMING LANGUAGE

A low-level programming language is a programming language that provides little or no


abstraction from computer’s microprocessor. A high-level programming language is a
programming language that is more abstract, easier to use, and more portable across
platforms.

LEVELS OF PROGRAMMING LANGUAGE


FIRST GENERATION OF PROGRAMMING LANGUAGE
The first generation of programming language, or 1GL, is machine language. Machine
language is a set of instructions and data that a computer's central processing unit can execute
directly. Machine language statements are written in binary code, and each statement
corresponds to one machine action. There is no need to translate the code and it will run
straight away. This may sound rather out-of-date, but there are benefits:

 Code can be fast and efficient

 Code can make use of specific processor features such as special registers

And of course drawbacks

 Code cannot be ported to other systems and has to be rewritten

 Code is difficult to edit and update

SECOND GENERATION PROGRAMMING LANGUAGE

As you can imagine, writing in 1s and 0s all day will leave you prone to mistakes. Second-
generation programming languages or 2GL are a way of describing Assembly code which you
may have already met.

By using codes resembling English programming becomes much easier. The use of these
mnemonic codes such as LDA for load and STA for store means the code is easier to read and
write. To convert an assembly code program into object code to run on a computer requires an
Assembler and each line of assembly can be replaced by the equivalent one line of object
(machine) code:

Assembly Code Object Code

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

Assembly code has similar benefits to writing in machine code, it is a one to one relationship
after all. This means that assembly code is often used when writing low level fast code for
specific hardware. Until recently machine code was used to program things such as mobile
phones, but with the speed and performance of languages such as C being very close to
Assembly, and with C's ability to talk to processor registers, Assembly's use is declining.
As you can hopefully see there are benefits to using Second-Generation Languages over First-
Generation, plus a few other things that makes Assembly great:

 Code can be fast and efficient

 Code can make use of specific processor features such as special registers

 As it is closer to plain English, it is easier to read and write when compared to machine code

And of course drawbacks

 Code cannot be ported to other systems and has to be rewritten

THIRD GENERATION PROGRAMMING LANGUAGE


Even though Assembly code is easier to read than machine code, it is still not straightforward
to perform loops and conditionals and writing large programs can be a slow process creating
a mixture of goto statements and jumps. Third-generation programming languages brought
many programmer-friendly features to code such as loops, conditionals, classes etc. This
means that one line of third generation code can produce many lines of object (machine)
code, saving a lot of time when writing programs. Third generation (High Level Languages)
codes are imperative. Imperative means that code is executed line by line, in sequence.

The third generation of programming language, 3GL, or procedural language uses a series of
English-like words, that are closer to human language, to write instructions.
High-level programming languages make complex programming simpler and easier to read,
write and maintain. Programs written in a high-level programming language must be
translated into machine language by a compiler or interpreter. PASCAL, FORTRAN, BASIC,
COBOL, C and C++ are examples of third generation programming languages.

Third generation languages can be platform independent, meaning that code written for one
system will work on another. To convert a 3rd generation program into object code requires a
Compiler or an Interpreter.

To summarize:

 Hardware independence, can be easily ported to other systems and processors

 Time saving programmer friendly, one line of 3rd gen is the equivalent of many lines of 1st
and 2nd gen
However

 Code produced might not make the best use of processor specific features unlike 1st and 2nd
gen

FOURTH GENERATION PROGRAMMING LANGUAGE

Fourth-generation languages are designed to reduce programming effort and the time it takes to
develop software, resulting in a reduction in the cost of software development. They are not always
successful in this task, sometimes resulting in inelegant and hard to maintain code. Languages have
been designed with a specific purpose in mind and this might include languages to query databases
(SQL), languages to make reports (Oracle Reports) and languages to construct user interface. An
example of 4th generation programming type is the declarative language. Declarative languages -
describe what computation should be performed and not how to perform it. Not imperative

An example of a declarative language is CSS which you might learn more about when
completing any web design unit

The fourth generation programming language or non-procedural language, often abbreviated


as 4GL, enables users to access data in a database. A very high-level programming language
is often referred to as goal-oriented programming language because it is usually limited to a
very specific application and it might use syntax that is never used in other programming
languages. SQL, NOMAD and FOCUS are examples of fourth generation programming
languages.

FIFTH GENERATION PROGRAMMING LANGUAGE


The fifth generation programming language or visual programming language, is also known
as natural language. Provides a visual or graphical interface, called a visual programming
environment, for creating source codes. Fifth generation programming allows people to
interact with computers without needing any specialised knowledge. People can talk to
computers and the voice recognition systems can convert spoken sounds into written words.
Prolog and Mercury are the best known fifth-generation languages.

OPEN PROGRAMMING LANGUAGE


The Open Programming Language (OPL) is an embedded programming language found in
portable devices that run the Symbian Operating System. For example mobile telephones and
PDAs. OPL is an interpreted language that is analogous to BASIC.

PROGRAMING APPROACHES
STRUCTURED PROGRAMMING EDUCATION

Structured programming often uses a top-down design model where developers map out the
overall program structure into separate subsections from top to bottom. In the top-down
design model, programs are drawn as rectangles. A top-down design means that the whole
program is broken down into smaller sections that are known as modules.A program may
have a module or several modules. Structured programming is beneficial for organising and
coding computer programs which employ a hierarchy of modules. This means that control is
passed downwards only through the hierarchy.

Examples of structured programming languages include Ada, Pascal and Fortran.

OBJECT-ORIENTED PROGRAMMING
The object-oriented approach refers to a special type of programming approach that combines
data with functions to create objects. In an object-oriented program, the object have
relationships with one another.
One of the earliest OOP languages is Smalltalk. Java, Python, Visual Basic and C++ are
examples of popular OOP languages.

DIFFERENCE BETWEEN STRUCTURED AND OBJECT ORIENTED PROGRAMMING


 Structured programming often uses a top-down design model.
 The object-oriented programming approach uses objects.

Programming paradigm

A programming paradigm is a fundamental style of computer programming, a way of


building the structure and elements of computer programs. Capabilities and styles of various
programming languages are defined by their supported programming paradigms; some
programming languages are designed to follow only one paradigm, while others support
multiple paradigms.
There are six main programming paradigms: imperative, declarative, functional, object-
oriented, logic and symbolic programming.

In computer science, imperative programming is a programming paradigm that describes


computation in terms of statements that change a program state. In much the same way that
imperative mood in natural languages expresses commands to take action, imperative
programs define sequences of commands for the computer to perform.

The term is used in opposition to declarative programming, which expresses what the
program should accomplish without prescribing how to do it in terms of sequences of actions
to be taken. Functional and logic programming are examples of a more declarative
approach.

Procedural programming is imperative programming in which the program is built from one
or more procedures (also known as subroutines or functions). The terms are often used as
synonyms, but the use of procedures has an impressive effect on how imperative programs
appear and how they are constructed. Heavily-procedural programming, in which state
changes are localized to procedures or restricted to explicit arguments and returns from
procedures, is known as structured programming. From the 1960s onwards, structured
programming and modular programming in general have been promoted as techniques to
improve the maintainability and overall quality of imperative programs. Object-oriented
programming extends this approach.

Procedural programming could be considered a step towards declarative programming. A


programmer can often tell, simply by looking at the names, arguments and return types of
procedures (and related comments), what a particular procedure is supposed to do, without
necessarily looking at the details of how it achieves its result. At the same time, a complete
program is still imperative since it 'fixes' the statements to be executed and their order of
execution to a large extent.

Declarative programming is a non-imperative style of programming in which programs


describe their desired results without explicitly listing commands or steps that must be
performed. Functional and logical programming languages are characterized by a declarative
programming style.

In a pure functional language, such as Haskell, all functions are without side effects, and state
changes are only represented as functions that transform the state. Although pure functional
languages are non-imperative, they often provide a facility for describing the effect of a
function as a series of steps. Other functional languages, such as Lisp, OCaml and Erlang,
support a mixture of procedural and functional programming.

In logical programming languages, programs consist of logical statements, and the program
executes by searching for proofs of the statements. As with functional programming
languages, some logical programming languages, such as Prolog, and database query
languages, such as SQL, while declarative in principle, also support a procedural style of
programming.

Many imperative programming languages (such as Fortran, BASIC and C) are abstractions of
assembly language.
In computer science, declarative programming is a programming paradigm, a style of
building the structure and elements of computer programs, that expresses the logic of a
computation without describing its control flow.[1] Many languages applying this style attempt
to minimize or eliminate side effects by describing what the program should accomplish in
terms of the problem domain, rather than describing how to go about accomplishing it as a
sequence of the programming language primitives[2] (the how is left up to the language's
implementation). This is in contrast with imperative programming, in which algorithms are
implemented in terms of explicit steps.

Declarative programming often considers programs as theories of a formal logic, and


computations as deductions in that logic space. Declarative programming may greatly
simplify writing parallel programs.[3]

Common declarative languages include those of database query languages (e.g., SQL,
XQuery), regular expressions, logic programming, functional programming, and
configuration management systems.

Declarative programming is often defined as any style of programming that is not imperative.
A number of other common definitions exist that attempt to give the term a definition other
than simply contrasting it with imperative programming. For example:

 A program that describes what computation should be performed and not how to
compute it
 Any programming language that lacks side effects (or more specifically, is
referentially transparent)

 A language with a clear correspondence to mathematical logic.[4]

These definitions overlap substantially.

In computer science, functional programming is a programming paradigm, a style of


building the structure and elements of computer programs, that treats computation as the
evaluation of mathematical functions and avoids state and mutable data. Functional
programming emphasizes functions that produce results that depend only on their inputs and
not on the program state—i.e. pure mathematical functions. It is a declarative programming
paradigm, which means programming is done with expressions. In functional code, the output
value of a function depends only on the arguments that are input to the function, so calling a
function f twice with the same value for an argument x will produce the same result f(x) both
times. Eliminating side effects, i.e. changes in state that do not depend on the function inputs,
can make it much easier to understand and predict the behavior of a program, which is one of
the key motivations for the development of functional programming.

Functional programming has its roots in lambda calculus, a formal system developed in the
1930s to investigate computability, the Entscheidungsproblem, function definition, function
application, and recursion. Many functional programming languages can be viewed as
elaborations on the lambda calculus, where computation is treated as the evaluation of
mathematical functions and avoids state and mutable data. In the other well known declarative
programming paradigm, logic programming, relations are at the base of respective languages.
[1]
In contrast, imperative programming changes state with commands in the source language,
the most simple example is the assignment. Functions do exist, not in the mathematical sense,
but the sense of subroutine. They can have side effects that may change the value of program
state. Functions without return value therefore make sense. Because of this, they lack
referential transparency, i.e. the same language expression can result in different values at
different times depending on the state of the executing program.[1]

Object-oriented programming (OOP) is a programming paradigm that represents the


concept of "objects" that have data fields (attributes that describe the object) and associated
procedures known as methods. Objects, which are usually instances of classes, are used to
interact with one another to design applications and computer programs. C++, Objective-C,
Smalltalk, Java, C#, Perl, Python, Ruby and PHP are examples of object-oriented
programming languages.

Logic programming is a programming paradigm based on formal logic. Programs written in


a logical programming language are sets of logical sentences, expressing facts and rules about
some problem domain. Together with an inference algorithm, they form a program. Major
logic programming languages include Prolog and Datalog.

A form of logical sentences commonly found in logic programming, but not exclusively, is
the Horn clause. An example is:

p(X, Y) if q(X) and r(Y)

Logical sentences can be understood purely declaratively. They can also be understood
procedurally as goal-reduction procedures: to solve p(X, Y), first solve q(X), then solve
r(Y).

The programmer can use the declarative reading of logic programs to verify their correctness.
In addition, the programmer can use the known behaviour of the program executor to develop
a procedural understanding of his program. This may be helpful when seeking better
execution speed. However, many logic-based program transformation techniques have been
developed to transform logic programs automatically and make them efficient.

In computing, symbolic programming is computer programming in which the program can


manipulate formulas and program components as data.

Through symbolic programming, complex processes can be developed that build other more
intricate processes by combining smaller units of logic or functionality. Programs can thus
effectively modify themselves, and appear to "learn", making them suited for applications
such as artificial intelligence, expert systems, natural language processing and computer
games.

Languages that support the symbolic programming paradigm include LISP and Prolog.

PASCAL PROGRAMMING

What is PASCAL PROGRAMMING?


Pascal or Pascal programming is an ordinary high-level programming language which is
widely used as a starting or as a teaching language. However, nowadays Pascal is
sometimes preferred to other languages, and could be useful to solve technical
problems. It is not necessary to learn any other easier language to start learning Pascal,
or any of that sort. It is a very easy programming language and helps you to understand
the basics of the world of programming. Also, it greatly helps you in order to start
learning the C programming language. I had different experiences, one of which I
learned Pascal, and then moved to C programming very easily. The Pascal programming
language has its structure and syntax very similar to that of the C programming
language.

A General Overview of Low-Level and High-Level Languages

There are two main categories of programming levels; these are low-level and high-level
languages. The terms 'low' and 'high' does not mean that a group of 'low-level' languages are
inferior to the 'high' ones. A low-level language consists of machine-oriented programming.
For example, machine code is the only language with which the CPU understands. The other
most-common low-level language, is the Assembly language. The Assembly language has a
structure of machine-oriented programming. The Assembly Language, in other words, has a
major control of the computer hardware. The Assembly Language makes use of mnemonics
and has a better relationship with the memory and the CPU unit far more than that of other
programming languages. The Assembly language is sometimes used as part of the source
code written in Pascal.

A high-level language consists of all those languages which are human problem-oriented. A
low-level language is not user-friendly, that is, makes it hard for the user to understand the
structure of the program. Pascal, C/C++, BASIC, COBOL, Fortran, etc.. are examples of high-
level programming languages. High-level languages represent their source code in such a
way that it is more understandable to the programmer.

Machine code is a language which uses binary coding in its source codes. What do you
understand by 0001001011 010101 1001110? It's machine code - the only language which is
understandable by the CPU.

Interpreters and Compilers

Every high-level language has its own source which needs to be translated into the CPU's
language - machine code. These translators are referred to as interpreters and compilers. A
high-level language package contains either an interpreter, or a compiler, with which a high-
level language uses to translate the source code into object code.

An interpreter is more slower than a compiler, the fact that it has to be loaded into memory
till the end of the translation of the program. It is less practical than the compiler. However,
the interpreter can be helpful for correcting out errors in programs i.e. it is ideal for
debugging. A compiler is faster due to its single, complete translation of the program into
object code. A compiler, compiles the source code (with no syntax errors) and makes a copy
of it. This copy is called the 'object code'. After it has been compiled, it does not need a
recompilation (unless the source code is changed and a recompilation is required to affect
the change). The object code used by the OS in order to execute the compiled program.

Pascal Program Structure

Before we study basic building blocks of the Pascal programming language, let us look a
bare minimum Pascal program structure so that we can take it as a reference in
upcoming chapters.

A Pascal program basically consists of the following parts:

 Program name
 Uses command

 Constant declarations

 Variables declarations

 Functions declarations

 Procedures declarations

 Main program block

 Statements and Expressions within each block

 Comments

Every pascal program generally have a heading statement, a declaration and an


execution part strictly in that order. Following format shows the basic syntax for a
Pascal program:

program {name of the program}


uses {comma delimited names of libraries you use}
const {global constant declaration block}
var {global variable declaration block}

function {function declarations, if any}


{ local variables }
begin
...
end;

procedure { procedure declarations, if any}


{ local variables }
begin
...
end;
begin { main program block starts}
...
end. { the end of main program block }

Pascal Hello World Example

Following is a simple pascal code that would print the words "Hello, World!":

program HelloWorld;
uses crt;

(* Here the main program block starts *)


begin
writeln('Hello, World!');
readkey;
end.

Let us look various parts of the above program:

 The first line of the program program HelloWorld; indicates the name of the
program.
 The second line of the program uses crt; is a preprocessor command, which tells
the compiler to include the crt unit before going to actual compilation.

 The next lines enclosed within begin and end statements are the main program
block. Every block in Pascal is enclosed within a begin statement and an end
statement. However, the end statement indicating the end of the main program is
followed by a full stop (.) instead of semicolon (;).

 The begin statement of the main program block is where the program execution
begins.

 The lines within (*...*) will be ignored by the compiler and it has been put to add
a comment in the program.

 The statement writeln('Hello, World!'); uses the writeln function available in


Pascal which causes the message "Hello, World!" to be displayed on the screen.

 The statement readkey; allows the display to pause until the user presses a key.
It is part of the crt unit. A unit is like a library in Pascal.

 The last statement end. ends your program.

Compile and Execute Pascal Program:

 Open a pascal compiler and add the above-mentioned code.


 Save the file as hello.pas

 Compile and then run


Pascal - Basic Syntax

You have seen a basic structure of pascal program, so it will be easy to understand other basic
building blocks of the pascal programming language.

Variables

A variable definition is put in a block beginning with a var keyword, followed by definitions
of the variables as follows:

Var A_Variable, B_Variable ... : Variable_Type;

Pascal variables are declared outside the code-body of the function which means they are not
declared within the begin and end pairs, but they are declared after the definition of the
procedure/function and before the begin keyword. For global variables, they are defined after
the program header.

Functions/Procedures

In Pascal, a procedure is set of instructions to be executed, with no return value and a


function is a procedure with a return value. The definition of function/procedures will be as
follows:

Function Func_Name(params...) : Return_Value;


Procedure Proc_Name(params...);

Comments

The multiline comments are enclosed within curly brackets and asterisks as {* ... *}. Pascal
allows single-line comment enclosed within curly brackets { ... }.

{* This is a multi-line comments


and it will span multiple lines. *}

{ This is a single line comment in pascal }

Case Sensitivity

Pascal is a case non-sensitive language, which means you can write your variables, functions
and procedure in either case. Like variables A_Variable, a_variable and A_VARIABLE have
same meaning in Pascal.

Pascal Statements

Pascal programs are made of statements. Each statement specifies a definite job of the
program. These jobs could be declaration, assignment, reading data, writing data, taking
logical decisions, transferring program flow control, etc.

For example:
readln (a, b, c);
s := (a + b + c)/2.0;
area := sqrt(s * (s - a)*(s-b)*(s-c));
writeln(area);

Reserved Words in Pascal

The statements in Pascal are designed with some specific Pascal words, which are called the
reserved words. For example, the words, program, input, output, var, real, begin, readline,
writeline and end are all reserved words. Following is a list of reserved words available in
Pascal: and; array; begin; case; const, div; do; downto; else; end, file; for; function; goto; if

in; label; mod; nil; not;of; or; packed; procedure; program, record; repeat; set; then; to

type; until; var; while; withCharacter set and Identifiers in Pascal

The Pascal character set consists of:

 All upper case letters (A-Z)


 All lower case letters (a-z)

 All digits (0-9)

 Special symbols - + * / := , . ;. () [] = {} ` white space

The entities in a Pascal program like variables and constants, types, functions, procedures and
records, etc., have a name or identifier. An identifier is a sequence of letters and digits,
beginning with a letter. Special symbols and blanks must not be used in an identifier.

Pascal - Data Types

Data types of an entity indicates the meaning, constraints, possible values, operations,
functions and mode of storage associated with it.

Integer, real, Boolean and character types are referred as standard data types in pascal as in
any other programming language. Data types can be categorized as scalar, pointer and
structured data types. Examples of scalar data types are integer, real, Boolean, character,
subrange and enumerated. Structured data types are made of the scalar types; for example,
arrays, records, files and sets. We will discuss the pointer data types later.

Pascal data types can be summarized as below in the following diagram:


Constants

Use of constants makes a program more readable and helps to keep special quantities at one
place in the beginning of the program. Pascal allows numerical, logical, string and character
constants. Constants can be declared in the declaration part of the program by specifying the
const declaration.

Syntax of constant type declaration is follows:

Const Identifier = contant_value;

Following are some examples of constant declarations:

PIE = 3.141592;
NAME = 'Stuart Little';
CHOICE = yes;
OPERATOR = '+';

Subrange Types

Subrange types allow a variable to assume values that lie within a certain range. For example,
if the age of voters should lie between 18 to 100 years, a variable named age could be
declared as:

Var age: 18 ... 100;

PASCAL OPERATORS
Arithmetic Operators

Following table shows all the arithmetic operators supported by Pascal. Assume variable A
holds 10 and variable B holds 20, then:

Show Examples

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

div Divides numerator by denominator B div A will give 2

Modulus Operator and remainder of after an


mod B mod A will give 0
integer division

Relational Operators

Following table shows all the relational operators supported by Pascal. Assume variable A
holds 10 and variable B holds 20, then:

Show Examples

Operator Description Example

Checks if the values of two operands are equal or


= (A = B) is not true.
not, if yes, then condition becomes true.

Checks if the values of two operands are equal or


<> not, if values are not equal, then condition (A <> B) is true.
becomes true.

Checks if the value of left operand is greater than


> the value of right operand, if yes, then condition (A > B) is not true.
becomes true.

Checks if the value of left operand is less than the


< value of right operand, if yes, then condition (A < B) is true.
becomes true.

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

Checks if the value of left operand is less than or


<= equal to the value of right operand, if yes, then (A <= B) is true.
condition becomes true.

Boolean Operators

Following table shows all the Boolean operators supported by Pascal language. All these
operators work on Boolean operands and produce Boolean results. Assume variable A holds
true and variable B holds false, then:

Examples

Operator Description Example

Called Boolean AND operator. If both the


and (A and B) is false.
operands are true, then condition becomes true.

It is similar to the AND operator, however, it


guarantees the order in which the compiler
and then evaluates the logical expression. Left to right and (A and then B) is false.
the right operands are evaluated only when
necessary.

Called Boolean OR Operator. If any of the two


or (A or B) is true.
operands is true, then condition becomes true.

It is similar to Boolean OR, however, it guarantees


the order in which the compiler evaluates the
or else (A or else B) is true.
logical expression. Left to right and the right
operands are evaluated only when necessary.

Called Boolean NOT Operator. Used to reverse the


not logical state of its operand. If a condition is true, not (A and B) is true.
then Logical NOT operator will make it false.

DECISION MAKING IN PASCAL

Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages:
Pascal programming language provides the
following types of decision making statements.

Statement Description
An if - then statement consists of a boolean expression
if - then statement
followed by one or more statements.
An if - then statement can be followed by an optional else
If-then-else statement statement, which executes when the boolean expression is
false.
You can use one if or else if statement inside another if or
nested if statements
else if statement(s).
A case statement allows a variable to be tested for equality
case statement
against a list of values.
It is similar to the if-then-else statement. Here, an else term
case - else statement
follows the case statement.
You can use one case statement inside another case
nested case statements
statement(s).

he if-then statement is the simplest form of control statement, frequently used in decision
making and changing the control flow of the program execution.

Syntax:

Syntax for if-then statement is:

if condition then S

Where condition is a Boolean or relational condition and S is a simple or compound


statement. Example of an if-then statement is:

if (a <= 20) then


c:= c+1;

If the boolean expression condition evaluates to true, then the block of code inside the if
statement will be executed. If boolean expression evaluates to false, then the first set of code
after the end of the if statement (after the closing end;) will be executed.
Pascal assumes any non-zero and non-nil values as true, and if it is either zero or nil, then it is
assumed as false value.

Flow Diagram:

Example:

Let us try a complete example that would illustrate the concept:

program ifChecking;
var
{ local variable declaration }
a:integer;
begin
a:= 10;
(* check the boolean condition using if statement *)
if( a < 20 ) then
(* if condition is true then print the following *)
writeln('a is less than 20 ' );
writeln('value of a is : ', a);
end.

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

a is less than 20
value of a is : 10

An if-then statement can be followed by an optional else statement, which executes when the
Boolean expression is false.

Syntax:
Syntax for the if-then-else statement is:

if condition then S1 else S2;

Where, S1 and S2 are different statements. Please note that the statement S1 is not
followed by a semicolon. In the if-then-else statements, when the test condition is true, the
statement S1 is executed and S2 is skipped; when the test condition is false, then S1 is
bypassed and statement S2 is executed.

For example,

if color = red then


writeln('You have chosen a red car')
else
writeln('Please choose a color for your car');

If the boolean expression condition evaluates to true, then the if-then block of code will be
executed, otherwise the else block of code will be executed.

Pascal assumes any non-zero and non-nil values as true, and if it is either zero or nil, then it is
assumed as false value.

Flow Diagram:

Example:

Let us try a complete example that would illustrate the concept:

program ifelseChecking;
var
{ local variable definition }
a : integer;
begin
a := 100;
(* check the boolean condition *)
if( a < 20 ) then
(* if condition is true then print the following *)
writeln('a is less than 20' )
else
(* if condition is false then print the following *)
writeln('a is not less than 20' );
writeln('value of a is : ', a);
end.

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

a is not less than 20


value of a is : 100

The if-then-else if-then-else Statement

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

When using if-then , else if-then , else statements there are few points to keep in mind.

 An if-then statement can have zero or one else's and it must come after any else if's.
 An if-then statement 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.

 No semicolon (;) is given before the last else keyword, but all statements can be
compound statements.

Syntax:

The syntax of an if-then-else if-then-else statement in Pascal programming language is:

if(boolean_expression 1)then
S1 (* Executes when the boolean expression 1 is true *)
else if( boolean_expression 2) then
S2 (* Executes when the boolean expression 2 is true *)
else if( boolean_expression 3) then
S3 (* Executes when the boolean expression 3 is true *)
else
S4; ( * executes when the none of the above condition is
true *)

Example:

The following example illustrates the concept:


program ifelse_ifelseChecking;
var
{ local variable definition }
a : integer;
begin
a := 100;
(* check the boolean condition *)
if (a = 10) then
(* if condition is true then print the following *)
writeln('Value of a is 10' )
else if ( a = 20 ) then
(* if else if condition is true *)
writeln('Value of a is 20' )
else if( a = 30 ) then
(* if else if condition is true *)
writeln('Value of a is 30' )
else

(* if none of the conditions is true *)


writeln('None of the values is matching' );
writeln('Exact value of a is: ', a );
end.

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

None of the values is matching


Exact value of a is: 100

You have observed that if-then-else statements enable us to implement multiple decisions in a
program. This can also be achieved using the case statement in simpler way.

Syntax:

The syntax of the case statement is:

case (expression) of
L1 : S1;
L2: S2;
...
...
Ln: Sn;
end;

Where, L1, L2... are case labels or input values, which could be integers, characters, boolean
or enumerated data items. S1, S2, ... are Pascal statements, each of these statements may have
one or more than one case label associated with it. The expression is called the case selector
or the case index. The case index may assume values that correspond to the case labels.

The case statement must always have an end statement associated with it.
LOOPS IN PASCAL

Programming languages provide various control structures or loops that allow for more
complicated execution paths. A loop statement allows us to execute a statement or group of
statements multiple times. Following is the general form of a loop statement in most of the
programming languages:

Pascal programming language provides the following types of loop constructs to handle
looping requirements.

Loop Type Description

Repeats a statement or group of statements while a given


while-do loop condition is true. It tests the condition before executing the loop
body.

Executes a sequence of statements multiple times and


for-do loop
abbreviates the code that manages the loop variable.

Like a while statement, except that it tests the condition at the


repeat-until loop
end of the loop body.

You can use one or more loop inside any another while, for or
nested loops
repeat until loop.
The for-do 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 for the for-do loop in Pascal is as follows:

for < variable-name > := < initial_value > to [down to] <
final_value > do
S;

Where, the variable-name specifies a variable of ordinal type, called control variable or index
variable; initial_value and final_value values are values that the control variable can take; and
S is the body of the for-do loop that could be a simple statement or a group of statements.

For example,

for i:= 1 to 10 do writeln(i);

Here is the flow of control in a for-do loop:

 The initial step is executed first, and only once. This step allows you to declare and
initialize any loop control variables.
 Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next
statement just after the for-do loop.

 After the body of the for-do loop executes, the value of the variable is either increased
or decreased.

 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-do loop terminates.

Flow Diagram
Example:

program forLoop;
var
a: integer;
begin
for a := 10 to 20 do
begin
writeln('value of a: ', a);
end;
end.

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

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

The while-do loop statement in Pascal allows repetitive computations till some test condition
is satisfied. In other words, it repeatedly executes a target statement as long as a given
condition is true.

Syntax:
The syntax of a while-do loop is:

while (condition) do S;

Where, condition is a Boolean or relational expression whose value would be true or false
and S is a simple statement or group of statements within BEGIN ... END block.

For example,

while number>0 do
begin
sum := sum + number;
number := number - 2;
end;

When the condition becomes false, program control passes to the line immediately following
the loop.

Flow Diagram:

Here, key point of the while loop is that the loop might not ever run. When the condition is
tested and the result is false, the loop body will be skipped and the first statement after the
while loop will be executed.

Example:

program whileLoop;
var
a: integer;
begin
a := 10;
while a < 20 do
begin
writeln('value of a: ', a);
a := a + 1;
end;
end.

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

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Unlike for and while loops, which test the loop condition at the top of the loop, the repeat ...
until loop in Pascal checks its condition at the bottom of the loop.

A repeat ... until loop is similar to a while loop, except that a repeat ... until loop is guaranteed
to execute at least one time.

Syntax:

repeat
S1;
S2;
...
...
Sn;
until condition;

For example,

repeat
sum := sum + number;
number := number - 2;
until number = 0;

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop execute once before the condition is tested.
If the condition is false, the flow of control jumps back up to repeat, and the statement(s) in
the loop execute again. This process repeats until the given condition becomes true.

Flow Diagram:

Example:

program repeatUntilLoop;
var
a: integer;
begin
a := 10;
(* repeat until loop execution *)
repeat
writeln('value of a: ', a);
a := a + 1
until a = 20;
end.

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

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Loop Control Statements:

Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.

Pascal supports the following control statements. Click the


following links to check their details.

Control Statement Description

Terminates the loop or case statement and transfers execution


break statement to the statement immediately following the loop or case
statement.

Causes the loop to skip the remainder of its body and


continue statement
immediately retest its condition prior to reiterating.

Transfers control to the labeled statement. Though it is not


goto statement
advised to use goto statement in your program.

C Programming language
C is one of the older programming languages—it was developed in the 70s—but it is still very
powerful thanks to how low-level it is. Learning C is a great way to introduce yourself to
more complex languages as well, and the knowledge you gain will be useful in almost every
programming language and can help you get into application development. To learn how to
start programming in C, see Step 1 below.

The C is the most widely used computer language, it keeps fluctuating at number one scale of
popularity along with Java programming language, which is also equally popular and most
widely used among modern software programmers.

Why to use C?
C was initially used for system development work, in particular the programs that make-up
the operating system. C was adopted as a system development language because it produces
code that runs nearly as fast as code written in assembly language. Some examples of the use
of C might be:

 Operating Systems
 Language Compilers
 Assemblers

 Text Editors

 Print Spoolers

 Network Drivers

 Modern Programs

 Databases

 Language Interpreters

 Utilities

Steps
Part 1 of 6: Getting Ready

Download and install a compiler. C code needs to be compiled by a program that


interprets the code into signals that the machine can understand. Compilers are usually
free, and different compilers are available for different operating systems.

o For Windows, try Dev C++ or tuo C


o For Mac, XCode is one of the best C compilers.

o For Linux, gcc is one of the most popular options.

C can be very powerful. It was designed for Unix operating systems, but has been
ported and expanded for nearly all operating systems. The modern version of C is C+
+. C is essentially comprised of functions, and in these functions you can use
variables, conditional statements, loops to store and manipulate data.

2. 3. Examine some basic code.

Take a look at the (very) basic program below to get a good idea about how some of
the various aspects of the language work together, and to get an idea of how programs
function.

#include <stdio.h>

int main()
{
printf("Hello, World!\n");
system("PAUSE");
return 0;
}
o The # i n c l u d e command occurs before the program starts, and loads libraries
that contain the functions you need. In this example, s t d i o . h lets us use the
p r i n t f ( ) and system( ) functions.
o The i n t m a i n ( ) command tells the compiler that the program is running the
function called "main" and that it will return an integer when it is finished. All
C programs run a "main" function.

o The brakes { } indicate that everything inside them is part of the function. In
this case, they denote that everything inside is a part of the "main" function.
o The p r i n t f ( ) function displays the contents of the parentheses on the user's
screen. The quotes ensure that the string inside is printed literally. The \ n
sequence tells the compiler to move the cursor to the next line.
o The ; denotes the end of a line. Most lines of C code need to end with a
semicolon.
o The system (“pause”) or g e t c h a r ( ) command tells the compiler to wait for
a keystroke input before moving on. This is useful because many compilers
will run the program and immediately close the window. This keeps the
program from finishing until a key is pressed.
o The r e t u r n 0 command indicates the end of the funciton. Note how the
"main" function is an i n t function. This means that it will need an integer to
be returned once the program is finished. A "0" indicates that the program has
performed correctly; any other number will mean that the program ran into an
error.

Always comment on your code.

Comments are part of the code that is not compiled, but allows you to explain what is
happening. This is useful for reminding yourself what your code is for, and for helping
other developers who might be looking at your code.

o To comment in C place / * at the start of the comment and * / at the end.


o Comment on all but the most basic parts of your code.

o Comments can be used to quickly remove parts of your code without deleting
them. Simply enclose the code you want to exclude with comment tags and
then compile. If you want to add the code back, remove the tags.

Part 2 of 6: Using Variables

Understand the function of variables.

Variables allow you to store data, either from computations in the program or from
user input. Variables need to be defined before you can use them, and there are several
types to choose from.

o Some of the more common variables in C programming include i n t , c h a r ,


and f l o a t . Each one stores a different type of data.
Learn how variables are declared. Variables need to be established, or "declared",
before they can be used by the program. You declare a variable by entering the data
type followed by the variable's name. For example, the following are all valid variable
declarations:

float x;
char name;
int a, b, c, d;

o Note that you can declare multiple variables on the same line, as long as they
are the same type. Simply separate the variable names with commas.
o Like many lines in C, each variable declaration line needs to end with a
semicolon.

Know where to declare variables. Variables must be declared at the beginning of


each code block (The parts of your code that are enclosed in {} brackets). If you try to
declare a variable later in the block, the program will not function correctly.

Use variables to store user input. Now that you know the basics of how variables
work, you can write a simple program that will store the user's input. You will be
using another function in the program, called s c a n f . This function searches and takes
the input that is provided for specific values.

#include <stdio.h>

int main()
{
int x;

printf( "Enter a number: " );


scanf( "%d", &x );
printf( "You entered %d", x );
system("PAUSE");
return 0;
}

o The " % d " string tells s c a n f to look for integers in the user input.
o The & before the variable x tells s c a n f where to find the variable in order to
change it, and stores the integer in the variable.
o The final p r i n t f command reads back the inputted integer to the user.

2. Learn the basic conditional operators. Conditional statements revolve around the
use of mathematical operators that compare values. The following list contains the
most commonly used conditional operators.
3. = /*assignment */
4. > /* greater than */
5. < /* less than */
6. >= /* greater than or equal to */
7. <= /* less than or equal to */
8. == /* equal to */
9. != /* not equal to */
10.
11. 10 > 5 TRUE
12. 6 < 15 TRUE
13. 8 >= 8 TRUE
14. 4 <= 8 TRUE
15. 3 == 3 TRUE
16. 4 != 5 TRUE

Manipulate your variables.

You can use mathematical expressions to manipulate the data that you have stored in
your variables. The most important distinction to remember for mathematical
expressions is that a single = sets the value of the variable, while = = compares the
values on either side to see if they are equal.

x = 3 * 4; /* sets "x" to 3 * 4, or 12 */
x = x + 3; /* adds 3 to the original value of "x", and sets the new
value as the variable */
x == 15; /* checks to see if "x" equals 15 */
x < 10; /* checks if the value of "x" is less than 10 */

Part 3 of 6: Using Conditional Statements

Understand the basics of conditional statements.

Conditional statements are what drive most programs. They are statements that are
determined to be either TRUE or FALSE, and then acted upon based on the result. The
most basic of the statements is the i f statement.

o TRUE and FALSE work differently in C than what you might be used to.
TRUE statements always end up equaling a nonzero number. When you
perform comparisons, if the result is TRUE then a "1" is returned. If the result
is FALSE, then a "0" is returned. Understanding this will help you see how IF
statements are processed.
2. 2

Write a basic IF statement. You can use IF statements to determine what the
program should do next after the statement is evaluated. You can combine it with
other conditional statements later to create powerful multiple options, but for now
write a simple one to get used to them.

#include <stdio.h>

int main()
{
if ( 3 < 5 )
printf( "3 is less than 5");
getchar();
}

3. 4
Use ELSE/ELSE IF statements to expand your conditions. You can build upon IF
statements by using ELSE and ELSE IF statements to handle different results. ELSE
statements run if the IF statement is FALSE. ELSE IF statements allow you to include
multiple IF statements into one code block to handle various cases. See the example
program below to see how they interact.

#include <stdio.h>

int main()
{
int age;

printf( "Please enter your current age: " );


scanf( "%d", &age );
if ( age <= 12 ) {
printf( "You're just a kid!\n" );
}
else if ( age < 20 ) {
printf( "Being a teenager is pretty great!\n" );
}
else if ( age < 40 ) {
printf( "You're still young at heart!\n" );
}
else {
printf( "With age comes wisdom.\n" );
}
return 0;
}

o The program takes the input from the user and takes it through the IF
statements. If the number satisfies the first statement, then the first p r i n t f
statement is returned. If it does not satisfy the first statement, it is taken
through each ELSE IF statement until it finds one that works. If it doesn't
match any of them, it goes through the ELSE statement at the end.

Part 4 of 6: Learning Loops

Understand how loops work.

Loops are one of the most important aspects of programming, as they allow you to
repeat blocks of code until specific conditions are met. This can make repeating
actions very easy to implement, and keeps you from having to write new conditional
statements each time you want something to happen.

o There are three main types of loops: FOR, WHILE, and DO...WHILE.
2. 2

Use a FOR loop.

This is the most common and useful loop type. It will continue running the function
until the conditions set in the FOR loop are met. FOR loops require three conditions:
initializing the variable, the condition to be met, and the way the variable is updated. If
you don't need all of these conditions, you will still need to leave a blank space with a
semicolon, otherwise the loop will run forever.
#include <stdio.h>

int main()
{
int y;

for ( y = 0; y < 15; y++;){


printf( "%d\n", y );
}
getchar();
}

o In the above program, y is set to 0, and the loop continues as long as the value
of y is less than 15. Each time the value of y is printed, 1 is added to the value
of y and the loop is repeated. Once y = 15, the loop will break.
3. 3

Use a WHILE loop.

WHILE loops are more simple than FOR loops. They only have one condition, and
the loop acts as long as that condition is true. You do not need to initialize or update
the variable, though you can do that in the main body of the loop.

#include <stdio.h>

int main()
{
int y=0;

while ( y <= 15 ){
printf( "%d\n", y );
y++;
}
getchar();
}

o The y + + command adds 1 to the y variable each time the loop is executed.
Once y hits 16 (remember, this loop goes as long as y is less than or equal to
15), the loop breaks.
4. 4

Use a DO...WHILE loop. This loop is very useful for loops that you want to ensure
run at least once. In FOR and WHILE loops, the condition is checked at the beginning
of the loop, meaning it could not pass and fail immediately. DO...WHILE loops check
conditions at the end of the loop, ensuring that the loop executes at least once.

#include <stdio.h>

int main()
{
int y;

y = 5;
do {
printf("This loop is running!\n");
} while ( y != 5 );
getchar();
}

o This loop will display the message even though the condition is FALSE. The
variable y is set to 5 and the WHILE loop is set to run when y does not equal 5,
so the loop terminates. The message was already printed since the condition is
not checked until the end.
o The WHILE loop in a DO...WHILE set must be ended with a semicolon. THis
is the only time a loop is ended with a semicolon.

Part 5 of 6: Using Functions

1. 1

Understand the basics of functions. Functions are self-contained blocks of code that
can be called upon by other parts of the program. They make it very easy to repeat
code, and they help make the program simpler to read and change. Functions can
include all of the previously-covered techniques learned in this article, and even other
functions.

o The m a i n ( ) line at the beginning of all of the above examples is a function,


as is g e t c h a r ( )
o Functions are essential to efficient and easy-to-read code. Make good use of
functions to streamline your program.
2. 2

Start with an outline. Functions are best created when you outline what you want it
to accomplish before you begin the actual coding. The basic syntax for functions is
"return_type name ( argument1, argument2, etc.);". For example, to create a function
that adds two numbers:

int add ( int x, int y );

o This will create a function that adds two integers (x and y) and then returns the
sum as an integer.
3. 3

Add the function to a program. You can use the outline to create a program that
takes two integers that the user enters and then adds them together. The program will
define how the the "add" function works and use it to manipulate the inputted
numbers.

#include <stdio.h>

int add ( int x, int y );

int main()
{
int x;
int y;

printf( "Enter two numbers to add together: " );


scanf( "%d", &x );
scanf( "%d", &y );
printf( "The sum of your numbers is %d\n" add( x, y ) );
getchar();
}

int add ( int x , int y )


{
return x + y;
}

o Note that the outline is still located at the top of the program. This tells the
compiler what to expect when the function is called and what it will return.
This is only necessary if you want to define the function later in the program.
You could define a d d ( ) before the m a i n ( ) function and the result would be
the same without the outline.
o The actual functionality of the function is defined at the bottom of the
program. The m a i n ( ) function collects the integers from the user and then
sends them to the a d d ( ) function to be processed. The a d d ( ) function then
returns the results to m a i n ( )

o Now the a d d ( ) has been defined, it can be called anywhere in the program.

You might also like