Chapter 02
Chapter 02
Chapter 02
2.2.2. Compiler
A computer program that converts the source code written in a particular programming language into targeted
code that can be executed directly by a computer. There are many programming languages that a programmer
cannot know all of them. To enable programmers to work in teams and exchange solutions, they need to
formulate these solutions in algorithmic language. Algorithmic language is the common language of all
programmers.
2.2.3. Integrated Development Environment (IDE)
To write a program, you can use any text editor such as Notepad. However, this method makes the
development process very difficult. Therefore, there is a set of programs that provide all the necessary tools
for the development process called IDE (Integrated Development Environment). IDE provides all the
necessary tools for designing, developing, testing, debugging, and deploying applications, which makes
development easier and faster. The IDE includes all the necessary tools to start designing applications, such
as:
Code editor: for writing and editing program code. It performs automatic formatting, making the process of
reading easier.
Project manager: to manage the files that make up a single project.
Debugger: detects and corrects errors in the code.
Shortcuts to compile and run the program.
Other tools...
example: -2, 7, 3.12, 6e-7, 'k', ''خ, '1', '!', "azerty", ""سالم, true, false
3.1.1. Identifier
An identifier is the name given by the programmer to any element of the algorithm that they want to create.
Examples include the name of the algorithm, variable name, type name, constant name, function name, etc.
There are rules and conditions in the C language that we adopt in the algorithm for naming identifiers:
Rules for Naming Identifiers:
The identifier name can only contain literal symbols and numerals from A to Z, a to z, and 0 to 9, as
well as the underscore symbol "_".
Algorithms and data structures 1 Chapter 2: Simple sequential algorithm
It must be a single word, meaning the name cannot contain spaces " ".
It must start with a letter or "_", not with a digit.
It must not be a reserved word.
The identifier must be unique; it is not possible to define more than one element with the same name.
It is recommended to use meaningful names, for example, we use "Width" instead of "x".
Examples of Valid Identifiers:
x, pi, Mat_info, isEmpty, n5, _if, _0a (it's better to avoid it)
Examples of Invalid Identifiers:
α, ج, π, é ,élève (unacceptable symbols)
Operation C observation
not negation ! true if the operand is false, and false if it's true.
and && true only if both operands are true, otherwise, it returns false
or || true if at least one of the operands is true, otherwise, false.
xor exclusive true if one is true and the other is false, otherwise, it returns false.
OR
= equivalence == true if both operands are equal..
String Operators:
+: used to concatenate two strings. For example, "hello" + "world" gives "helloworld" without adding spaces.
"hello" + " " + "world" gives "hello world".
Operator Priority:
When evaluating an expression, we follow the priority summarized in the following table. If the priorities are
equal, priority is given to the operation on the left.
priority the operation
0 )(
1 + and - sign, not.
2 * / mod div
3 -+
4 >, >=, <, <=
5 ≠, =
6 and
7 or
Parentheses are used to change priority (and sometimes for readability).
3.1.3. Expression
An expression is a structure of values and identifiers, connected by operations. When evaluated, it results in a
single value. Expressions are created using values, variables, parentheses, and operations.
Example:
Assuming a=2, b=3, and ok=true,
expression result expression result expression result
5 5 a+3 5 ok True
a 2 "In"+"fo" Info a*(b-7)>8 et ok False
3.1.4. Instruction
An instruction (statement) is a command or step in the solution, meaning it is the action that will be
executed.
Algorithms and data structures 1 Chapter 2: Simple sequential algorithm
3.1.6. Comments
Comments are texts that are ignored during the translation of the program and are not part of the algorithm.
They are added to programs to provide explanations and facilitate understanding.
In C, comments can be added using «//» for single-line comments. It begins with // and ends with a line break.
Comments can also be added, starting with « /* » and ending with « */ », which can extend over several lines.
example:
// One-line commentary
/* Comment
It can span multiple lines*/
Header: Comprised of the word "Algorithm," followed by the name that explains the problem to be
solved. The name should be a valid identifier.
Declarations: Reserved for reserving memory space for data (constants and variables) that will be used
as input and output.
Instructions: A set of steps or commands that will be executed during the algorithm's execution. It
starts with "Begin" and ends with "End." There are five main types of instructions:
1. Assignment instruction.
2. Read (input) instruction.
3. Write (output) instruction.
4. Conditional instruction.
5. Iterative (loop) instruction.
Const ou Constant: These are two reserved words that allow constant declaration.
Identifier: The name given to the constant.
Value: The value assigned to the constant.
Example:
Const
Pl= 3.1415926
DEP = ""قسم االعالم االلي
Advantages of Constants:
Condenses the code, where a long phrase can be replaced with a short word, such as using "PI" instead
of 3.1415926.
Helps avoid errors by providing a meaningful name. For example, "PI" instead of 3.1415926.
Simplifies code maintenance, as the value needs to be changed in one place only.
5.2. Variable
A variable is a location in memory used to store data. It has a name, a type, and a value (address in the second
semester).
Name: Identifier used by the programmer to refer to and manipulate the variable. For example, "weight."
Type: In computers, everything is represented as 0 and 1. The type determines how it is translated, as
well as the size of memory to reserve. For example, "int" (32 bits).
Value: The content of the bits that make up the variable, i.e., its value. Typically, this is the part that
changes during program execution. For example, 1101 represents the number 13, or -5 if we consider the
leftmost 1 as the sign "-".
Variable Declaration:
Var Identifier: Type
Var ou Variable: These are two reserved words that allow variable declaration.
Identifier: The name given to the variable.
Algorithms and data structures 1 Chapter 2: Simple sequential algorithm
A comma "," can be used to declare multiple variables of the same type.
Examples:
Var
age: integer
gender: character
x, y, z: real
Note: By convention, constant names are written in uppercase, and variable names are written in lowercase.
6. Data Types
A data type represents the domain to which data belongs, such as numbers, text, images, audio, or video. The
data type determines how the bits, which compose the variable, are translated and the size of memory to
reserve, i.e., the number of bits and allowed operations. When defining a variable, its type must be specified.
There are five basic data types in the algorithm:
1. Integer such as:-5, 0, 1, 13
2. Real: -7, 0, 1, 3.14, 2.7e03
3. Boolean Contains only true or false.
4. Character: Includes all symbols on the keyboard, such as digits, letters in all languages, and printed
(visual) and unprinted symbols. They are always enclosed in single quotes (e.g., 'a', 'M', '1', '+', ',', ')'س.
5. String: A set of symbols, with a length of 0 or more, always enclosed in double quotes (e.g.,
"computer," "Good luck\n," "1", "3.14").
Notes:
We use "." instead of "," to express decimal numbers.
1 is not the same as 1., not the same as '1', and not the same as "1." The first is an integer, the second
is a real number, the third is a character, and the last is a string.
'a' is not the same as "a." The first is a character, and the second is a string of length 1.
Lowercase letters are not the same as uppercase letters. For example, 'a' is not the same as 'A.'
Some symbols (keys) do not print. For example, space ' ' or newline '\n'.
The backslash (\) is used to represent some invisible or special symbols visually. For example,
newline '\n' and tab '\t'. To print double quotes, we use ‘\"’ and to print a backslash, we use \\.
There is an empty string, denoted as "", which contains no characters and has a length of 0.
7. Basic Instructions
7.1. Assignment
This is the process that allows us to store a value in a variable.
Syntax:
variableexp
work correctly, the value of the right expression and the left variable must be of the same type or at least
compatible types.
Example:
a5
a gets 5
ba*2
b gets 10
a0
a gets 0
bb-1
b gets 9
c’b’
c gets the letter b
db>a
d gets true
s"name"
s gets the word "name"
Before a variable can be used, it must be declared and assigned an initial value. To obtain the value of any
variable or constant, simply write its name.
variable: This is the name of a variable. read() can only be used with variables.
When the program is executed and the input instruction read() is encountered, execution is paused until the
user enters data. The input process ends by pressing the Enter key. The program will continue to execute.
Several variables can be entered at once, separated by a comma ",". In this case, the user enters the value of
the first variable, then presses the space key, then enters the value of the second variable, and presses the Enter
key only after entering the value of the last variable.
Example:
Read(name) The user enters a series of letters, for example, <Muhammad>, then presses the Enter
key.
Read(a, b) They enter a number, for example, "15", then press space, then enter the second number,
for example, "20", then press the Enter key.
7.2.2. Output: Write()
Write() is a ready-to-use function in the algorithm. It displays on the screen whatever we put inside its
parentheses. It is always used to print results.
Syntax:
Write(exp)
or
Write("message")
exp: This is an expression, calculated to obtain a single value, to display on the screen.
Algorithms and data structures 1 Chapter 2: Simple sequential algorithm
"message": Any text you want to display as is on the screen. It is not calculated. It can be in any
language or set of letters. It must be enclosed in double quotes, which are not displayed on the screen.
Several values and texts can be displayed at once, separated by a comma ",".
Example:
Write(name) The value of the variable name appears on the screen,
for example, <Mohammed>.
a5 Displays 8 without changing the value of a.
Write(a+3)
Write("square of ", a, " is ", a * a) Displays: square of 5 is 25
Write("b=",a) Displays: b=5
Notes:
Always before the Read() instruction comes the Write() instruction, to explain to the user what is
expected to be entered.
The user writes on the keyboard, while the program (computer) reads <Read()> from the keyboard,
and the program writes <Write()> on the screen, while the user reads from the screen.
<Read()> can be generalized for the input of all input units, and <Write()> for the output of all output
units.
Example 2:
Write an algorithm that calculates the average for ASD1.
Algorithms and data structures 1 Chapter 2: Simple sequential algorithm
Algorithm avg_ASD1
Var
exam, td, tp, avg: real
Begin
Write("Enter the exam score, tutorial score, and practical score")
Read(exam, td, tp)
avg ← (exam * 3 + td + tp) / 5
Write("The average is:", avg)
End
Input - Output
read()/write()
Processing Symbols like assignment
Algorithms and data structures 1 Chapter 2: Simple sequential algorithm
yes
Algorithms and data structures 1 Chapter 2: Simple sequential algorithm
Example:
Algorithm to calculate the area of a circle the algorithm to check the accuracy of the password.
begin
Read (r)
sp*r*r
Write (s)
End
Generally, these files are libraries of predefined and ready-to-use functions. Example:
Example:
To use I/O functions (scanf and printf), we use the stdio.h library.
To use mathematical functions (sin, cos, exp, pow, sqrt, ...), we use the math.h library.
To use string functions (strlen, ...), we use the string.h library.
#include <stdio.h>
#include <math.h>
10.1.2. Macro
A macro, in its simplest form, is defined as follows:
Algorithms and data structures 1 Chapter 2: Simple sequential algorithm
Natural numbers in algorithms from 0 to +∞. Since integers contain natural numbers, we usually use
integers to express them. You can also add unsigned before a type in C to express only natural numbers.
Types Size (bytes) Size (bits) Range
unsigned char 1 8 0 ,28-1
unsigned short 2 16 0 ,216-1
unsigned long 4 32 0 ,232-1
unsigned int 4 32 0 ,232-1
Real numbers:
Types Size (bytes) Precision Range
float 4 6
double 8 8
long double 10 8
Boolean type: There is no boolean type in C, but int is used instead. True is represented by the number
1 and false by 0. Any number other than 0 is translated as true.
Character type is char.
String type: To express strings in C, we use arrays (Chapter 5) of char[] or pointers (second semester)
of char*.
10.2.2. Notes
The int type is the generic type for integers.
The char type is used for both integers and characters, where each character is associated with a number.
In C++, there's the bool type for Boolean and string for string.
In this course, we use char for characters, int for integers and Boolean, and float for real numbers.
Example: To declare a new type named Banane with an underlying type of int, you use:
typedef int Banane;
example:
int age;
char gender;
float x, y, z;
Banane b;
example:
int const N = 10;
const float Pl = 3.1415926;
const char[] DEP = ";"قسم االعالم االلي
Note: Macros can be used to declare constants as well, like:
#define DEP ""قسم االعالم االلي
10.4. Assignment
We use = instead of ←, and read "receives" rather than "equals".
Syntax:
variable = expression;
example:
a=5; a gets 5
b=a*2; b gets 10
a=0; a gets 0
b=b-1; b gets 9
c=’b’; c gets the letter b
d=b>a; d gets 1
s="name"; s gets the word name
Assignment shortcuts in C.
expression comment example
v+=exp ; v=v+(exp) ;
x=2 ;
v-=exp ; v=v-(exp) ;
x*=5+3 ; x=x*(5+3) ;
v*=exp ; v=v*(exp) ; Parentheses are important ≠ x=x*5+3 ;
v/=exp ; v=v/(exp) ; x become 16
v%=exp ; v=v%(exp) ;
Note:
v++ is not identical to v+1, but v=v+1.
v++, ++v, v=v+1, v+=1 are all equivalent if presented in a separate instruction.
The difference between v++, ++v when it appears in another sentence, is the pre- or post-addition.
Empty instruction: It's an instruction that does nothing, like the semicolon instruction " " and instructions
such as i + 1, where the result is calculated and ignored, without any change in the program state.
format: A text or string that is displayed as is on the screen, except for the "%" symbol to indicate
expression formats and the "\" character for escape sequences.
expression: Computed to obtain a single value, which will be displayed on the screen in the specified
format <format>.
The format follows this structure:
% [flags] [width] [.prec] type_char
width: Represents the minimum number of digits to display for a specific value. If this number is
greater than the required size, the difference is filled with spaces or zeros, depending on whether the
number starts with 0 or not.
.prec: The number of digits after the decimal point for floating-point numbers.
type_char: A character representing the type of value to output.
format use
%d To input or output a number in the decimal system (10)
%o To input or output a number in the octal system (8)
%x To input or output a number in the hexadecimal system (16)
%u To input or output an unsigned natural number unsigned
%i To input or output an integer (int) like %d
%f To input or output a real number (float)
%c To input or output a character (char)
%s To input or output a string (char[], char*)
%e To input or output a nbr in scientific format such as 3e-2
Some characters are special, so we must use an escape technique to use them. In C, the escape
character is (), backslash, and we use it to add a new line '\n' or a tabulation (a large space) '\t'. To
print double quotes ("), we use ", to print a backslash () we use \, and to print % we use %%.
example:
printf("Hello");
displays Hello
int a=13;
a=(13)10 a=(15)8 a=(D)16
printf("a=(%d)10\ta=(%o)8\ta=(%X)16\n",a ,a ,a);
a=66;
a=66 a=0.000000 a=B a=b
printf("a=%i\ta=%f\ta=%c\ta=%c\n",a ,a ,a ,a+32);
Because 66 is not necessarily 66 in float
And 66, if we see it as a character,
represents the letter B, while 66 + 32 =
98 represents the coding of the letter b in
lower case.
float pi=3.1415926;
3.141593 3.1416 003.14
printf("%f\t%.4f\t%06.2f" ,pi ,pi ,pi);
The user presses a, then enter. The program assigns a to c1 and \n to c2, and waits for the user to enter the
second character to be assigned to c3. To avoid this problem, we use:
scanf("%c", &c1) ;
scanf("% c", &c2) ;
scanf("% c", &c3) ;
The issue with scanf arises when attempting to input a string containing spaces into a variable.
For instance:
scanf("%s%s", v1, v2);
Upon entering the words "math info" and pressing Enter, the program assigns the first word to v1 and the
second word to v2. However, if we intend to input both words, such as a compound name, into a variable,
we use:
scanf("%s", v1);
Upon entering the words "math info" and pressing Enter, the program assigns only the first word to v1,
while the second word is lost.
To circumvent this problem, we employ the gets function, defined in the string.h library:
#include <string.h>
gets(v1);
3. int main()
4. {
5. //Local declarations (constants and variables)
6. //instructions
7. return 0;
8. }
explanation:
1. Include the stdio.h library which contains scanf and printf.
2. Place for public declarations.
3. main(): Every program must have a starting function called main which indicates the entry point of
the program.
4. Start of the main function body, corresponding to the "begin" in algorithms.
5. Place for local declarations.
6. Instructions.
7. return: The main function must return an integer (int). It returns 0 to the operating system to indicate
successful execution.
8. End of the main function and the program, corresponding to the "end" in algorithms.
Observations:
Declarations can be made either in the place of public or local declarations.
Code formatting, alignment, margins, spaces, and line breaks after special characters ([{}]) =+, ;: etc. are
not significant in the program. Much of the program can be composed on a single line, with semicolons
serving as separators between statements.
Code formatting, alignment, margins, spaces, and line breaks should be used for program readability.
An example demonstrating the process of translating an algorithm into C.
algorithm C comment
Algorithm circle_area The algorithm name
becomes the file name
circle_area.c
Const P=3.14 Const float P=3.14; can use #define P 3.14
Var r, s:entier int r, s; There is no var word in C
//r radius and s area // r the radius and s the This is not part of the
surface
program, but only for
explanation.
begin int main() Variables can be declared
{
after {.
Write ("Enter radius ") printf("Enter radius \n"); \n to return to the line
Read (r) scanf("%d", &r);
Don't forget & before the
variable
sp*r*r s=p*r*r;
Each instruction ends with
;
Write ("The area of the printf("The area of the
circle is:" , s) circle is: %d" , s); The format must be given
End }
example 2
Algorithms and data structures 1 Chapter 2: Simple sequential algorithm