0% found this document useful (0 votes)
9 views

Chap 2

Uploaded by

bidayousef
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Chap 2

Uploaded by

bidayousef
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Chapter 2 : Sequential Algorithms

1. Algorithm vs Program
An algorithm is the precise description of the method of solving a problem in the form of simple
instructions. The algorithm is characterized by:
 Identification of information involved in a program
 Abstraction: modeling, formalization and representation of this information
 List of operations to be applied to this information.
 Definition of the order of operations to be respected.
Algorithmic Language: Any algorithm is expressed in a natural language called Language
Algorithmic or pseudo-language, it describes objects in a structured, clear and complete manner
manipulated by the algorithm as well as all the instructions to be executed on these objects to
obtain results.
A program is the translation of the algorithm into a formal language that the machine can
understand and execute. This language is called a programming language (python, C, Java, etc.)
and it is governed by a syntax just as much as the natural language of man is.

2. Algorithm Components
An algorithm consists of three main parts:
 The header: this part is used to give a name to the algorithm. It is preceded by the word
Algorithm;
 The declarative part: in this part, we declare the different elements that the algorithm
uses (constants, variables, structures, procedures and functions.);
 The body of the algorithm: this part contains the instructions of the algorithm. It is
delimited by the words “Begin” and “end”.

3. Data: Variables and constants


 Constants represent numbers, characters, strings of characters whose value cannot be
modified during the execution of the algorithm. Constants are introduced by the
keyword “Const” as:
Const name_identifier = value ;
Example:
Const pi = 3.14
 Variables can store digits, numbers, characters, character strings, etc. whose value can
be modified during the execution of the algorithm. Variables are introduced by the
keyword “Var” as:
Var name_identifier : type ;

Constants as well as variables are designed by identifiers. Herein, an identifier is a name that
follows a particular syntax:
 It is made up of a series of letters of the (Latin) alphabet and numbers.
 It necessarily begins with a letter.
 The underscore "_" can play the same role as a letter of the alphabet.
Examples: x, y, PI, student_name, _x, etc.

Remarks
• To facilitate the readability of an algorithm, it is preferable to use meaningful names.
• The identifier must be different from all the keywords (Begin, End, If, Then, Else,
etc.).
• Characters of the Greek alphabet are not allowed. If we need to use them, we must
write them in Latin alphabet like alpha, beta, gamma, delta, etc.
• It is not allowed to use accented characters in an identifier.
• It is not allowed to use subscripts or superscripts.

4. Standard primitive types


The type corresponds to the kind of information used. Standard primitive types are those types
that are available on most computers as built-in features.
The standard types in algorithmic languages include the whole numbers, the logical truth
values, and a set of printable characters. We denote these types by the identifiers INTEGER,
REAL, BOOLEAN, CHAR, and STRING (of characters). Each type has a set of operations.

4.1.The type INTEGER


The type INTEGER comprises a subset of the whole numbers whose size may vary among
individual computer systems. If a computer uses n bits to represent an integer in two's
complement notation, then the admissible values of x must satisfy -2n-1 ≤ x < 2n-1. It is
assumed that all operations on data of this type are exact and correspond to the ordinary laws
of arithmetic, otherwise, the computation will be interrupted. This event is called overflow.
Example :
Const coefficient = 6 ;
Temp = -273 ;
Var mark : integer ;

The standard operators for integers are the four basic arithmetic operations of addition (+),
subtraction (-), multiplication (*) and division (/, DIV).

4.2.The type REAL


The type REAL denotes a subset of the real numbers. Whereas arithmetic with operands of the
types INTEGER is assumed to yield exact results, arithmetic on values of type REAL is
permitted to be inaccurate within the limits of round-off errors caused by computation on a
finite number of digits.
Example :
Const pi = 3.14 ;
Var mean : real ;

The standard operators are the four basic arithmetic operations of addition (+), subtraction (-),
multiplication (*), and division (/).

4.3.The type BOOLEAN


The two values of the standard type BOOLEAN are denoted by the identifiers TRUE and
FALSE.
For example, if x has for value 3, and y is 4, the expression “x=y” would be evaluated as FALSE.

4.4.The type CHAR


The character type is a finite and completely ordered set of characters (symbols). It includes:
• The letters of the Latin alphabet: a .. z, A .. Z.
• The numbers: 0 .. 9.
• Symbols used as operators: + - * / < = > …
• Punctuation characters: . , ; ! ? …
• Special characters: @ % & # …
• And others.

The character set defined by the International Standards Organization (ISO), and particularly
its American version ASCII (American Standard Code for Information Interchange) is the most
widely accepted set. The figure below shows the ASCII table with all 256 characters. They are
numbered from 0 to 255. Each character is stored in computer memory on one byte.
Table 2. 1. ASCII Table

To determine the rank (the order) of a character ('A' for example) in the set of characters
represented by this table, one must add the two numbers found on the same line (in the first
column on the left) and the same column (in the first row at the top). Example: The rank of the
character 'A' is equal to 64 + 1 = 65.
A character type constant is represented by one and only one character framed by two quotes.
Examples: ',a', 'b', 'C', '!', '#', …
The operations defined by functions on the Character type are:
ORD( c ): This function returns a positive integer corresponding to the rank of the character c,
in all the characters.
Examples: Ord('!') = 33, Ord ('A') = 65, Ord ('a') =97.
CHR(i): is the inverse function of Ord. For a positive integer i, it returns the character of rank
i.
Examples: Chr(33) = '!', Chr(65) = 'A', Chr(97) = 'a'.
SUCC( c ): provides the character that immediately follows the character c in all the characters.
Examples: Succ('a') = 'b', Succ('3') = '4', Succ('%') = '&'.
PRED( c ): provides the character immediately preceding the character c in all characters. This
is the inverse function of Succ.
Examples: Pred('b') = 'a', Pred ('4') = '3', Pred ('&') = '%'

4.5.The type STRING


A string is a sequence of characters enclosed by two double quotes.
Examples: “Algorithmics”, “Ahmed Ali”, …
The number of characters in a string is called length of the string.
"Algorithmic" is a string of length 13.
"": represents the empty string of length 0. It does not contain any characters.
We mention two predefined functions on the strings
• length( str ): it provides the length of the string str.
• concat(str1, str2): it provides the string obtained by concatenation of the two strings
str1 and str2.
Example: concat("Module", "Algorithmic") = "Algorithmic Module”

In summary, each type has a particular size and representation in computer memory. The
different forms of constants should not be confused.
Examples: 3 (integer type), 3.0 (real type), '3' (character type) and "3" (string type).

5. Basic operations
An expression is a series of operations applied to a set of factors (arguments or parameters).
Each expression has a value and a type.
If an expression contains several operators with the same priority, these operators are left-
associative.
Example:
The expression: X + Y * Z , leads to the evaluation of X + (Y * Z).
In case, one wish to modify the semantic induced by this rule, parenthesis have to be used.

5.1.Arithmetic operations
The standard operators are the four basic arithmetic operations of addition (+), subtraction (-),
multiplication (*) and division (/, DIV).
Whereas the slash denotes ordinary division resulting in a value of type REAL, the operator
DIV denotes integer division resulting in a value of type INTEGER.
If we define the quotient q = m DIV n and the remainder r = m MOD n, the following relations
hold, assuming n > 0: q*n + r = m and 0 ≤ r < n Examples 31 DIV 10 = 3 31 MOD 10 = 1 -31
DIV 10 = -4 -31 MOD 10 = 9

5.2.Boolean operation and comparison


The Boolean operators are the logical conjunction, disjunction, and negation whose values are
defined in Table 2.
Table 2. Logical operators
A B A and B A or B not(A)
True True True True False
True False False True False
False True False True True
False False False False True

Note that comparisons are operations yielding a result of type BOOLEAN. Thus, the result of
a comparison may be assigned to a variable, or it may be used as an operand of a logical operator
in a Boolean expression.
For instance, given Boolean variables p and q and integer variables x = 5, y = 8, z = 10, the two
assignments:
p is x = y, and q is (x ≤ y) AND (y < z)

yield p = FALSE and q = TRUE.

Comparison operators are: <, >, =, ≠, ≤, ≥

6. Basic instructions
In algorithmics, there are three elementary instructions: Read, Write and assignment ().

6.1.The reading instruction (READ)


The READ instruction allows us to give a value to a variable from the keyboard.
Syntax: Read(variableName)
Examples:
Read(A)
Read(B)
Read(C)

Several successive reading instructions can be grouped into a single instruction. For the
previous example, we can replace the three read instructions with:
Read(A, B, C).

On a computer, when the processor receives the Read(variableName) order, it stops execution
of the program and waits for a value. The user must then enter a value from the keyboard. As
soon as the entry is validated (by pressing the Enter key ↵), execution of the program continues.
The value passed by the user is assigned to the variable and overwrites its previous value.
The Read(variableName) instruction causes an error if the value entered does not belong to the
type of the variable, unless it is an integer value and the variable is of real type. In which case
the integer value is converted to a real value.

6.2.The writing instruction (WRITE)


The WRITE instruction allows display on screen. There are two types of display:
• Either we display the value of a variable or an expression:
Syntax: Write (variableName)
Example: Write(X) or Write(2*X+Y). If X = 10 and Y= 5 then, the first instruction displays
10 and the second displays 25
• Either we display a text (a message):
Syntax: Write (“a message”)
Example: Write( "The result is = ")

Several successive writing instructions can be grouped into a single instruction.


For example, the sequence of instructions:
Write (“The result is =" )
Write (X)
Can be replaced by: Write (“The result is =”, X). This instruction displays the string "Result is
=10.”
Note: Message communication is very useful in programming. It offers the possibility:
o To guide the user by telling him what the machine expects of him following a
reading order.
o To explain the results of a treatment

6.3.The assignment )
Assignment is a statement that stores the value of an expression in a variable.
Syntax: variableName  expression.
This statement reads: variableName receives expression.
Examples: X  7 // Assign a constant value to the variable X (X receives 7).
Y  X // Copy the value of variable X into variable Y (Y receives X).
Z  2 * X + T / Y // Z receives 2 * X + T / Y.
Remarks:
If the variable already contained a value, it would be replaced by the value of the expression.
The old value of the variable is lost and there is no way to recover it.
A type check operation is performed before assignment. It is an error if the value of the
expression does not belong to the type of the variable, unless it is a value integer and that the
variable is of real type. In this case the integer value is converted to real.
Example :
Algorithm Permutation
Var X, Y, Z : integer ;
Begin
Read( X, Y ) ;
ZX;
XY;
YZ;
Write (X, Y)
End.

If the read values of X and Y are 17 and 10 respectively, what would be the outputted values.

7. Examples of algorithms
Example 1: The following algorithm displays a hello message.
Algorithm hello_v1;
Begin
write ("Salut Tous le monde ");
End.

Example 2 :
Algorithm hello_v2;
Var name : string ;
Begin
write ("Please, enter your name ");
read(name);
write("hello ", name);
End.

Example 3: The following algorithm computes and displays the surface of a rectangle
Algorithm surface_r;
Var length, width, surface : integer ;
Begin
write ("Enter the rectangle length: ");
read(length);
write ("Enter the rectangle width: ");
read(width);
surface  length * width ;
write(« The surface is : ", surface);
End.

Example 4: The following algorithm computes and displays the perimeter of a circle

Algorithm perimeter_c;
Const pi = 3.14;
Var radius : integer ;
perimeter : real;
Begin
write ("Enter the circle radius: ");
read(radius);
surface → 2 * pi * radius ;
write(« The perimeter is : ", surface);
End.
8. Flow chart
A flowchart is a diagrammatic representation of algorithm to plan the solution to the problem.
Constructed by using special geometrical symbols where each symbol represents an activity.
The activity would be input/output of data, computation/processing of data etc.

Flowchart symbols

Example of a flowchart that calculate the sum and product of two numbers.
9. The language C
C language is a low-level programming language, which means that the instructions appearing
in the programs remain close to those that the processor is directly capable to execute. Learning
to program with the C language allows you to acquire a good understanding of the mechanisms
that govern program delivery, including how the processor accesses the computer’s memory.
Another advantage of this language is that it is simple. This simplicity, however, does not
prevent its use for complex projects: many large software programs are programmed in C. For
example, the kernel of the Linux operating system, which equips a majority of modern
smartphones, is mainly written in C.
9.1. Structure of a C program
The basic structure of a C program is divided into 6 parts which makes it easy to read, modify,
document, and understand. The six sections are: Documentation, Preprocessor section,
Definition, Global declaration, Main function, and Sub programs.
While the main section is compulsory, the rest are optional in the structure of the C program.

9.1.1. Documentation
Documentation consists of the description of the program, programmer's name, and creation
date. These are generally written in the form of comments.
In a C program, single-line comments can be written using two forward slashes i.e., //, and we
can create multi-line comments using /* */.
Example:
// This is my first program
/*
I am 1st year licence student
*/

Both methods work as the document section in a program. It provides an overview of the
program. Anything written inside will be considered a part of the documentation section and
will not interfere with the specified code.

9.1.2. Preprocessor Section


All header files are included in this section which contains different functions from the libraries.
A copy of these header files is inserted into the code before compilation. The header files are
introduced by the C preprocessing directive “#include”.
Example :
#include <stdio.h>
#include <math.h>
There are various header files available for different purposes. Here are some examples of
header files in C:
• stdio.h: This header file contains declarations for standard input and output functions,
such as printf(), scanf(), and fopen().
• stdlib.h: This header file contains declarations for general utility functions, such
as malloc(), free(), and rand().
• math.h: This header file contains declarations for mathematical functions, such
as sin(), cos(), and log().
• string.h: This header file contains declarations for string manipulation functions, such
as strcpy(), strcat(), and strlen().
• time.h: This header file contains declarations for time and date functions, such
as time() and strftime().
In addition to these standard header files, there are also many user-defined header files that are
available. For example, a header file for a linked list data structure might contain declarations
for the struct node type and functions for creating, inserting, and deleting nodes in the linked
list.
9.1.3. Definition
A preprocessor directive in C is any statement that begins with the "#" symbol. In particular,
the “#define” is a preprocessor compiler directive used to create constants,
ie, “#define” basically allows the macro definition, which allows the use of constants in our
code.
Example :
#define PI 3.14159265358979323846

“#define” allows us to use constants in our code. It replaces all the constants with its value in
the code.

9.1.4. Global Declaration


This section includes declaration of global variables, function declarations, static global
variables, and functions.
Example:
const double PI = 3.14159265358979323846;
int my_global_variable = 10;
void my_global_function() {
// This function can be called from anywhere in the program.
}

Global variables and functions can be very useful, but they should be used with caution. If you
use too many global variables and functions, your program can become difficult to maintain
and debug. It is generally better to use local variables and functions whenever possible.

9.1.5. Main() Function


For every C program, the execution starts from the main() function. Thus, it is mandatory to
include a main() function in every C program.
The return type of the main() function can be either int or void. void main() informs the compiler
that the program will not yield any value, while int main() indicates that the program will return
an integer value.
Example:
int main() {
printf("Hello, world!\n");
return 0;
}

9.1.6. Sub Programs


Includes all user-defined functions (functions the user provides). They can contain the inbuilt
functions and the function definitions declared in the Global Declaration section. These are
called in the main() function. User-defined functions are generally written after the main()
function irrespective of their order.
Exemple:
void my_global_function() {
// This function can be called from anywhere in the program.
printf("This is a global function.\n");
}

A little more sophisticated function would be:

int add_two_numbers(int a, int b) {


return a + b;
}

9.1.7. Example of C program


Here is the example of the simpmlest program, one can write:

// My first C program
#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}

To execute a C program, one should follow these steps:


1. Compile the C program using a C compiler. The C compiler will convert the C source
code into machine code that the computer can understand.
2. Link the compiled C program with any necessary libraries. Libraries are collections of
pre-compiled code that can be used by C programs.
3. Execute the linked C program.

9.2.Data type in C
C includes the following basic data types:
• int - stores whole numbers
• float - stores real numbers
• double - stores real numbers with higher precision than float
• char - stores single characters
• void - specifies that a function does not return any value
In addition to these basic data types, C also has a number of compiler-specific data types, such
as long and short.
Example :
// Basic data types
int my_integer_variable = 10;
float my_floating_point_variable = 3.141592653589793;
char my_character_variable = 'a';
void my_void_function() {
// This function does not return any value.
}

// Compiler-specific data types


long my_long_integer_variable = 1234567890123456789; // A long integer variable
short my_short_integer_variable = 12345; // A short integer variable

When choosing a data type for a variable, it is important to consider the type of data that the
variable will store and the operations performed on it. For example, if you need to store a integer
number, you would use an integer data type. If you need to store a real number, you would use
a floating-point data type.
Using the correct data type for your variables can help to improve the performance and
reliability of your C programs.

Besides these types, in C, Boolean is a data type that contains two types of values, i.e., 0 and 1.
Basically, the bool type value represents two types of behavior, either true or false. Here, '0'
represents false value, while '1' represents true value.

9.3.Assignment and expressions


Assignment is a fundamental operation in C programming. Assignment in C is the process of
storing a value in a variable. To assign a value to a variable, you use the assignment operator
(=).

Example:
int a ;
a= 1 ;
We can also assign the value of one variable to another variable. Generally, the value is issued
from an expression.
An expression in C is a combination of operands and operators. Operands are the values that
are operated on, and operators are the symbols that perform the operations. Expressions can
be used to evaluate mathematical expressions, compare values, and perform other logical
operations.
Here are some additional tips for using assignment in C:
• Only assign values to variables of the correct data type.
• Be careful not to overwrite the value of an important variable.
• Use parentheses to make your code more readable and to avoid errors.
There are many operators in C, in particular, we mention:
o Arithmetic Operators
o Relational Operators
o Logical Operators

9.4.Input and output instructions


To perform above mentioned “read” and “write” operations, C offer us the instruction “scanf”
and “printf” respectively. oth functions are inbuilt library functions, defined in stdio.h (header
file).
9.4.1. printf() function
The printf() function is used for output. It prints the given statement to the console.
The syntax of printf() function is given below:
printf("format string",argument_list);
The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

9.4.2. scanf() function


The scanf() function reads formatted input from the standard input (usually the keyboard). It
takes a format string and a list of variables, similar to printf().
For example, scanf("%d", &arg); reads an integer into the variable arg.

Example:
int a,b,c;
double x;
scanf("%d%d", &a,&b);
c=a+b;
x= sqrt(c);
printf("The square root of %d: %.4lf\n",c, x);

9.5.Example of C program
// This program computes the area of a circle

#include <stdio.h>
#define PI 3.141592653589793

int main() {
float radius, area;

printf("Enter the radius of the circle: ");


scanf("%f", &radius);

area = PI * radius * radius;

printf("The area of the circle is: %.2f\n", area);

return 0;
}

You might also like