Chap 2
Chap 2
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”.
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.
The standard operators for integers are the four basic arithmetic operations of addition (+),
subtraction (-), multiplication (*) and division (/, DIV).
The standard operators are the four basic arithmetic operations of addition (+), subtraction (-),
multiplication (*), and division (/).
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 ('&') = '%'
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
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)
6. Basic instructions
In algorithmics, there are three elementary instructions: Read, Write and assignment ().
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.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 ) ;
ZX;
XY;
YZ;
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.
“#define” allows us to use constants in our code. It replaces all the constants with its value in
the code.
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.
// My first C program
#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}
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.
}
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.
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
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;
return 0;
}