Simple sequential algorithm
Algorithme séquentiel simple
Topics-
1. Notion of Language and Human Language
2. Parts of an algorithm
3. Data- Variables and constants
4. Basic operations
5. Input and output instructions
6. Construction of a simple algorithm
7. Representation of an algorithm by an organizational chart
8. C programming Language
1. Notion of Language and Human Language
1.1 Language definition
Language is the function of expressing thought and communication
between humans, implemented by speech or writing or by signs
between a transmitter and a receiver. Any system of signs allowing
communication such as computer languages.
Language
Transmitter Communication Canal Receiver
1. Notion of Language and Human Language
1.2 Algorithmic Language
The word Algorithm comes from the distortion of the name of a 9th
century Persian scholar called Al Khwarizmi.
Definition 1- An Algorithm is a finite sequence of actions to
solve a given problem.
Definition 2- An algorithm describes processing on a set
finite data of a simple nature (numbers or characters) or more
complex (structured data).
1. Notion of Language and Human Language
1.3 Steps to resolve a problem
An Algorithm is an informal language or incompletely formalized:
- free text (i.e. description of the different steps in natural
language),
- flowchart (diagram representing the steps),
- pseudo-code (simplified version of a computer language) or
others.
1. Notion of Language and Human Language
1.3 Steps to resolve a problem
An algorithm is flexible, it aims to express a resolution method in a
way that is understandable to a human being. But for the same
reason,
An algorithm cannot be processed directly by a computer; it must be
formalized, i.e. transformed into a program.
Faced with any problem, we must first ask ourselves a certain number
of questions.
The answer to these questions will facilitate the resolution of the
problem, that is to say, achieving a result.
The steps to resolve a problem are as follows:
1. Notion of Language and Human Language
1.3 Steps to resolve a problem
1- Understand the problem statement.
2- Break the problem down into sub-
problems that are easier to solve.
3- Associate a specification with each sub-problem
4- Development of the algorithm. - The necessary data,
- The resulting data,
- The procedure to follow to arrive
at the result starting from a set of
data
1. Notion of Language and Human Language
1.3 Steps to resolve a problem
Example
Consider three cubes stacked in an order (assuming C is on B which
is itself on A)
It is assumed that the robot understands the following actions: goto
a place, putCube and takeCube.
1. Notion of Language and Human Language
Begin
I Goto P1;
I// What should we prepare
I Take a cube;
I Cube A, B, C;
I Goto P2;
I Place P1, P2;
I PutCube;
I// Now let's start the treatment
I Goto P1;
I Goto P1;
I Take a cube;
I Take a cube;
I Goto P2;
I Goto P2;
I PutCube;
I PutCube;
END.
1. Notion of Language and Human Language
The observation is that the
algorithm contains repeated
instructions- So, we can declare an action
I Goto P1; called move from place X to Y
I Take a cube; allowing us to group these
I Goto P2; actions as follows:
I PutCube;
1. Notion of Language and Human Language
Begin I Initialize P2;
I Cube A, B, C; I MoveIt(P1,P2);
I Place P1, P2; I MoveIt(P1,P2);
I Action MoveIt(X1, X2); I MoveIt(P1,P2);
I Begin END.
I Goto X1;
I Take a cube; The second algorithm is
I Goto X2; clearer and more reusable
I PutCube; since it can exchange P1 and
I End; P2 to move the cubes from P2
to P1 and return to the initial
order.
1. Notion of Language and Human Language
1. Characteristics of a Good Algorithm
Input and output should be defined precisely.
Each step in the algorithm should be clear and unambiguous.
Algorithms should be most effective among many different ways to
solve a problem.
An algorithm shouldn't include computer codem, Instead, the algorithm
should be written in such a way that it can be used in different
programming languages.
2. Algorithm Examples
Algorithm to add two numbers
We assume that we have two numbers and we want to
display their sum
Algorithm to find the perimeter of a rectangle
Similarly we consider a rectangle whose length and width are
known.
You are asked to find its perimeter using an algorithm
Algorithm 1: Add two numbers entered by the user
Input are: num1, num2
Formula: sum = num1 + num2
Output: sum
Step 1: Start
Step 2: Declare variables num1, num2 and sum;
Step 3: Accept values num1, num2;
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2 ;
Step 5: Display sum;
Step 6: Stop.
Algorithm 2: Algorithm to calculate Perimeter of Rectangle
Input are: Length, width
Formula: 2 * (length + width)
Output: Perimeter
Step 1: Start
Step 2: Declare variables lenght, width and perim;
Step 3: accept length;
Step 4: Accept width;
Step 5: perim =2 * (lenght + width);
Step 6: Display perim;
Step 7: Stop.
Algorithm parts
2- Algorithm parts
To correctly write an Algorithm, we have to draw up a framework to respect in
order to develop an algorithm divided into 4 parts:
2- Algorithm parts
To correctly write an Algorithm, we have to draw up a framework to respect in
Part 1 Part 2 Part 3 Part 4
order to develop an algorithm divided into 4 parts:
Header Declaration of Declaration of Body of the
variables functions and algorithm
Simply allows you to
Contains all instructions or
identify the algorithm. procedures
The declaration makes it given to resolve the
The syntax. An algorithm can be broken
possible to identify the list problem. The body is
down into several sub-
of objects or quantities marked at the beginning
problems which can be
used and manipulated in with the keyword Begin and
solved separately. These
the body of the algorithm. It ends with the keyword End
sub-problems give rise to
is an exhaustive list divided followed by a period to stop
what we call functions or
into two parts of constants execution and release of
procedures. These behave in
and variables. the memory space reserved
the same way as a simple
for the program and its
algorithm.
objects.
2- Algorithm parts
Thus, the general syntax is presented as follows:
Algorithm Main
Step 1: Start // or {
Step 2: Declaration Variables; Step 3.1: start
Step 3.2:Declaration Variables;
Step 3: Declaration of Step 3.3: Declaration of functions and
functions and procedures procedures
Step 3.4: Body
Step 4: Body; Step 3.5: return;
Step 5: Stop. // or }
Note: To write a comment, we precede it with a slash followed by an asterisk in a
nested manner as follows:
/* Hier I write my comment in order to make my algorithm readable */
Data: Variables and constants
1- Identifier
An algorithm uses and manipulates values that are @10A9
Memory addresses in RAM
stored in memories. The memory boxes (the Heap) @10AA
are divided into memory units which are
addressable (i.e. each box has its own address: @10AB
like the rooms in a hotel) where the manipulated @10AC
data must be placed in order to be able to use
@10AD
them as it is illustrated in Figure aside. However, it
is necessary to know @10AE
@10AF
1- Identifier
— The reference name given to designate this location called
identifier and which is imperative to avoid handling addresses that
are difficult to remember (memory addresses),
— The size of the data to be able to reserve the sufficient number
of bytes (type)
Rules to respect when creating an Identifier
The rules for naming identifiers are as follows −
•Identifier names are unique.
•Cannot use a keyword as identifiers.
•Identifier has to begin with a letter or underscore (_).
•It should not contain white space.
•Special characters are not allowed.
•Identifiers can consist of only letters, digits, or underscore.
•Only 31 characters are significant.
•They are case sensitive.
Example
Following is the C program to identify which terms are called as
identifiers − Sum, X1, Delta, …
1- Identifier
Begin Letter End.
Letter From a to z and from A to Z
digit From 0 to 9
_
Underscore symbol (trait d’union en français)
Figure- Flowchart of identifier syntax to respect while writing identifiers relating to: constant, variable, algorithm and label.
Note: The identifier must be mnemonic starting with a letter and not containing
special characters like -, +, /. . . etc.
E.g. take the syntactic diagram of an identifier given in the course.
We can classify Data structure into two categories:
1- Primitive Data structure
2- Non- Primitive Data structure
Data Structure
Primitive Non-Primitive
Data Structure Data Structure
Integer
Linear Non-Linear
Data Structure Data Structure
Float
Character Static Dynamic
Boolean Array Linked List Stack Queue Tree Graph
Figure . Classification of Data Structures
Data: 1. Constants
1- Constants
A constant is a data item whose value cannot change during the program's execution.
Thus, as its name implies – the value is constant.
A constant is a variable or value that cannot be altered once defined
Syntax
Const ConstIdentifier = Value ;
Example- PI = 3.1415927 whose value
is universal and does not change,
Const PI = 3.1415927;
Data: 2. Variables
2.1- Variable Definition
A variable is a data item whose value can change during the program's execution. Thus,
as its name implies – the value can vary.
Example-
Both 'a' and 'b' are variables. They are symbolic representations of any numbers. For
example, the variable 'a' could contain the number 5 and the variable 'b' could contain the
number 10. During execution of the program, the statement "a + b" is replaced by the
Actual Values "5 + 10" and the result becomes 15.
So a, b are numeric variables
2.1- Variable Definition- Characteristics
A variable is a data item whose value can change during the program's execution. Thus,
as its name implies – the value can vary.
Name or Identifier-
A variable appears in programming under a name associated with the memory location
where the measurement of the variable is stored.
Type-
- To distinguish the space needed (in size) to store the values of a variable, we use the
type which defines a set of infinite number of values having the same characteristics such
as for example integers, floats, strings...etc.
Value-
the value is a measurement that can be assigned to a variable. The values that a variable
of an algorithm can take precisely defines its type.
Address-.
- This is the location in the computer's memory where the value of the variable is stored in
the memory heap.
2.1- Variable Definition- Syntax
Syntax
Type VarIdentifier ;
Type VarIdentifier , VarIdentifier2,…, VarIdentifiern;
Example-
Integer a; /* declaration of one variable a. Thus, a may have values belonging to Z */
Float b, volume; /* declaration of 2 variables having the same type Float */
2.2- Variable Types
Definition-
It is the association of an identifier with a set of representation and manipulation rules.
Determines the memory size allocation
the values to be manipulated are of different types, which requires different sizes to store
the information.
Defines the rules of coding
Representation rules describe the form that information must take in memory. This form is
called a code. The rule allowing information to be transformed into a code is called coding.
2.2- Variable Types
Types of variable type
There are two kinds of types in Algorithms: simple types and complex types.
Simple type - representation of information in memory, according to the rules defined for
a given type.
Complex type - type of data describing composite information, i.e. made up of several
values, themselves of simple or complex types.
2.2- Simple Type
1- Numerical values
Integer: To represent integers. Variables of this type do not accept a decimal part in the
assigned value. However, this value can be positive or negative.
Real- To represent real numbers. In this case the decimal part of the number is
essential and if it does not exist it is worth zero. The real number can also be positive or
negative.
Syntax
Integer type Real type
Integer <identifier> ; /* Only one variable */ Real <identifier> ; /* Only one variable */
Integer <identifier>, <identifier>, <identifier>; Real <identifier>, <identifier>, <identifier>;
/* several numerical variables without decimal /* several numerical variables having decimal
part*/ part*/
Example: integer Family member; Example: real average, salary;
2.2- Simple Type
2- Textual values It is possible to use one or more characters to represent textual data.
Char: Is a value that is between 0 and 255 by reference to the ASCII table. The basic
ASCII code represented 7-bit characters (i.e. 128 possible characters, from 0 to 127).
Extended ASCII code is not unique and is highly platform dependent.
String: A sequence of characters forms a character string. This string is characterized
by a size which represents the number of characters constituting the string. Also, the
string must be delimited by two apostrophes so as not to create confusion for the compiler
of values with identifiers.
Syntax
char type string type
char <identifier> ; /* Only one variable */ string <identifier> ; /* Only one variable */
char <identifier>, <identifier>, <identifier>; string <identifier>, <identifier>, <identifier>;
/* one character by variable */ /* several character variables */
Example: : char answer, punctuation; Example: string name, date, observation;
2.2- Simple Type
3- Boolean (or logic) values There are obviously other types other than numeric and
text, those to express logical values namely: True, False. By reference to Bool algebra
this type is called Boolean or logic type.
boolean: This type can only take two states or values: true or false.
How many bytes does it need?
Syntax
boolean type
boolean <identifier> ; /* Only one variable */
char <identifier>, <identifier>, <identifier>;
/* several character variables */
Example: : boolean Excluded, Apt; ; /* both can only take True or False as values */
Algorithm Body
Basic operations
3.1- Basic Operations in Algorithm
We can also perform operations on declared variables and constants, such as
additions, multiplications, etc.
To carry out operations, we will use operators. These allow you to perform a well-
defined operation on values called operands, producing a result called the operation
value. This value has a type that is also well defined by the operation.
There are many algorithmic operators that can be classified in different ways.
First- They can be classified according to the number of operands they require, which
gives three categories:
1. unary operators which require a single operand;
2. binary operators which require two;
3. and finally, ternary operators require three.
3.1- Basic Operations in Algorithm
Second- Operators can also be classified according to the nature of the operations they
carry out. This is the classification that we have used to develop this concept.
For each operator, we will look at several characteristics linked to:
1. Description of the operation carried out;
2. The types of operands on which it is applicable;
3. and the type of result it provides.
3.1.1- Arithmetic operators
1- Arithmetic operators- are operators that are performed on numeric variables or
constants (integer or real). The following table shows different arithmetic operations.
Symbol Designation Example
+ Addition a+b
- Subtraction a–b
* Multiplication a*b
/ Division a/b
Div Integer Division a div b
3.1.2- Arithmetic operators
2- Equality and Comparison Operator- The equality and comparison operators are all
binary operators. They return a boolean (true or false) as a result. These operators are
often used to express conditions. Comparison operators test a condition and return 1 if that
condition is logically true and 0 if that condition is false.
3.1.3- Arithmetic operators
3-Logical operator- Logical operators are applied on Boolean operands and produce a
result which is also Boolean. In Algorithms there are three logical operators, including one
unary and two binary operators presented in Tab
Logical operators
Not Negation
And Conjunction (Logical And)
Or Disjunction (Logical Or)
Boolean operators
== Equal
<>, != Different
3.1.4- Arithmetic operators
4- Text operators- Text operators apply to character or string type operands. The result
necessarily produces a string of characters. In algorithm there are three operators to
process character strings.
Symbol Designation Example
+ Concatenation a+b
< Less than a<b
> Greater than a>b
== Equal a == b
<>, != Different a != b
Example : ’Azerty’ < ‘Qwerty’ is true because ’A’ < ’Q’
3.2- Expressions
Definition- An expression is a concatenation of a set of operands and operators. The
result is a numerical or logical or textual value depending on the variables and constants it
contains. There are two types of expression:
A- Arithmetic expressions - the evaluation result of which is a number.
E.g. 4 ∗ (2 + X), 4 ∗ 2 + X
B- Logical (or Boolean) expressions - whose evaluation result is "true" or "false", i.e. a
Boolean.
E.g (age >= 16) and (age <= 65) and (non-employed) //where age is of numeric
type and employee of Boolean type
3.2- Expressions
Note that:
- A combination of integer with {+ or - or * } gives always an Integer;
- A combination of integer with / (division) gives a Real;
- A combination of real numbers always gives a Real
- A combination of characters or string with comparison operators gives a Boolean result
An expression is evaluated from left to right taking into account priorities or precedence.
3.2- Expressions- Operator precedence
An expression is evaluated from left to right taking into account priorities or precedence.
Operator precedence- determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.
1- Prefix increment and decrement(++, --), Unary plus and minus, Logical NOT
2- Multiplication *,dividion (/), Remainder (%),
3- addition, subtraction, disjunction
4-<,>,<=,>=.
5- For relational == and ≠
6- And
7-Or
3.4- I/O Instructions
1- Assignment The use variables and assign values to them. This is indicated in pseudocode
using an arrow symbol (←). The arrow points from the value being assigned towards the variable it
is being assigned to. We distinguish two types of assignments
A- Internal assignment
assignment is an action that modifies the value of one and only one variable, also called
internal reading since values can be assigned to variables automatically within the
algorithm.
● Syntax
Identifier Value / expression / variable / Constant;
Example:
Const integer Pi = 3.14;
a5;
b a;
a a+ 2* b;
S 2* a * Pi ;
3.4- I/O Instructions
B- External assignment
External assignment is an assignment of values but this time from outside the algorithm.
The input instruction therefore suspends the execution of the program and invite the
user to enter a value from an the input device.
The value entered will be stored or automatically assigned to the variable in memory.
It is obvious to know that this input instruction is used only with variables (no constants
or expressions can be used inn this case).
● Syntax
Read(variable); or Read (Var1, vvar2,…, varn);
Example:
integer n; read(n);
3.4- I/O Instructions
● Effects of a read instruction
- If the variable has not been declared, the reading is not executed, the general
execution ends (this type of situation must be avoided!),
- If the value entered is of a type different from the type of the variable, the execution
ends (this type of situation should be avoided)
- Otherwise, the value entered on the keyboard is assigned to the variable.
3.4- I/O Instructions
2- Display
This instruction allows the algorithm to communicate values to the user by
displaying them on the screen (viewing the information placed in memory).
● Syntax
Display (value/expression/constant/variable);
Example
Display(“Your family name”); Display(a+ 2*b);
Display(“the sum is:”, a+b);
4- Construction of a simple algorithm
● The structure of an algorithm is as follows:
Algorithm AlgorithmIdentifier;
Const Idconst = value;
Var types listOfVariables;
begin
/* Internal/external data input operations as appropriate with or read instruction*/ ;
/* Manipulation of variables and constants necessary for solving the problem*/ ;
/* Don't forget to display the results with Display instruction*/ ;
End.
algorithm by a
flowchart
Main Shapes
4- Flowchart
Definition
A flowchart is simply a graphical representation of steps. It shows steps in
sequential order and is widely used in presenting the flow of algorithms. Typically, a
flowchart shows the steps as boxes of various kinds, and their order by connecting them
with arrows.
4.1- Flowchart Symbols
Different flowchart shapes have different conventional meanings. The meanings of some of
the more common shapes are as follows:
a- Terminator
The terminator symbol represents the starting or
ending point of the system. Example Begin End
b- Process
A box indicates some particular operation.
Example AA+1
c- Data
It represents information entering or leaving the
system. An input might be an order from a A
customer.
Output can be a product to be delivered.
d- Decision A>0
A diamond represents a decision or branching
point. Lines coming out from the diamond
indicates different possible situations, leading to
different sub-processes.
e- Display
A box indicates some particular operation.
Example
f- Flow
Lines represent the flow of the sequence and
direction of a process.
Flowchart Example
– Medical Service
This is a hospital flowchart
example that shows how
clinical cases shall be
processed.
This flowchart uses decision
shapes intensively in
representing alternative
flows.
Stop
Let’s start with
C Language
Introduction to C