Professional Documents
Culture Documents
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.
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
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.
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.
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.
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 :
Begin
statment1
statment2
statment2
end.
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.
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.
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 ”)
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:
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.
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.
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.
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.
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:
But saying that by itself isn't enough to actually make any pancakes, we need to
break the task down:
Organise Kitchen
Make Pancakes
Serve
Organise Kitchen
Clean surfaces
Get out plain flour, salt, eggs, full fat milk, butter
Put on apron
Make Pancakes
Add butter
Whisk
Cook
Serve
And each of these tasks can be broken down further, let us take a look at the
Cook:
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
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:
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.
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.
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.
Code can make use of specific processor features such as special registers
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:
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 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
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:
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 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
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.
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.
Programming paradigm
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.
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.
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)
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]
A form of logical sentences commonly found in logic programming, but not exclusively, is
the Horn clause. An example is:
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.
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
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.
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.
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.
Program name
Uses command
Constant declarations
Variables declarations
Functions declarations
Procedures declarations
Comments
Following is a simple pascal code that would print the words "Hello, World!":
program HelloWorld;
uses crt;
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 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.
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:
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
Comments
The multiline comments are enclosed within curly brackets and asterisks as {* ... *}. Pascal
allows single-line comment enclosed within curly brackets { ... }.
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);
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
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.
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.
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.
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:
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
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
>= 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.
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
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:
if condition then S
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:
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:
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 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:
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:
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:
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:
When the above code is compiled and executed, it produces the following result:
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:
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.
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:
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,
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.
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
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.
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.
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 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.
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.
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.
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;
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
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 */
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;
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.
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
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;
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
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.
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.
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:
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 main()
{
int x;
int 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.