You are on page 1of 40

Chapter 2

Programming Basics for Problem Solving


-Introduction to Algorithms-

EE121
FALL 2022
Dr. R. NAMANE
What is computer solving problem?

 It refers to the entire process of taking the


statement of a problem and developing a
computer program that solves problem.

Programming = process of problem solving


Steps in the Program Development
Process
 Four main steps are involved in the program
development process:
1. Analysis
2. Design
3. Implementation
4. Test
Analysis
 Analyse precisely what the program is supposed
to accomplish (requirements gathering).
 Specify Inputs/Outputs of the desired solution.

If you don’t know exactly where are you going,


how will you know when you get there?
Quote by Steve Maraboli
Design
 Produce an ordered sequence of steps that
describe the solution of the problem.
 This sequence of steps is called an algorithm.

 Flowchart is another tool to describe the


solution.
Implementation(Coding)
 Implement the program in some programming
language.
 Translation of the design into source code.
 Source code: Set of statements written in a certain
programming languages such as C.
Test and Debug
 It is for making sure that your program is running
correctly once all existing bugs (errors) are
located and removed.
Waterfall Model
Algorithms and Flowcharts
 Algorithm and flowchart are the powerful tools
for learning programming. An algorithm is a step-
by-step design of the process, while a flowchart
explains the steps of a program in a graphical
way.
 Algorithm and flowcharts helps to clarify all the
steps for solving the problem.
Algorithm
 Algorithm is a term of Arab origin. It is derived from the
name of the famous Persian mathematician “Al
Khawarizmi” (780-850) author of his famous book “Al
Djabr”, in which he introduced the fundamental
algebraic methods and techniques for solving equations.
 Algorithms are the building blocks of computer programs.
They are as important to programming as recipes are to
cooking.
 An algorithm is a well-defined procedure that takes input
and produces output. The analogy to a recipe is good here,
since a cook will take ingredients (the input), mix things
together and cook it (the procedure), and produce a
dish (the output).
Definition of an Algorithm
 An algorithm is a procedure (a well-ordered
collection of instructions) for solving a problem
in finite number of steps.
Why Algorithm?
An algorithm uses a formalism (set of words, structures,
rules) whose purpose is:
 Offer a common language understood by everyone and
which does not depend on a programming language.
 Facilitates the communication of the solution of a problem.

 Ensure a better design of a solution before its translation to


computer program.
 The translation of the design to different programming
languages is more simpler than translating a computer
program from one programming language.
General Structure of an Algorithm
Header
ALGORITHM name of the algorithm
VARIABLES (declaration of all data used inside the algorithm
Declaration
with a set of variables)

START
Action 1
Body Action 2

Action n
STOP
Variables
 Typically, an algorithm consists of instructions that
tell the computer what to do and data that the
algorithm uses.
 The data consists of constants or fixed values that
never change and variables or variable values that
may vary during the execution of the program.
 A variable may refer to an input data, output
data, or intermediate data.
 A variable is a named memory location in
RAM that holds a value.
Variables
In an algorithms:
 All variables must be declared before they
can be used!
 Every variable has:
• Name (Identifier)
• Data type
• Value
Variables Names (Identifiers)
A variable's name is known as an identifier. The identifer
given to a variable usually follows certain rules:
 It can contain letters and numbers but must start with a
letter.
 It must contain at least one letter (at the start of the name).
 It must not contain special characters such as !@£$%&* or
punctuation characters. However, an underscore can be
used. Spaces are not allowed.
 It should not be a reserved word. Examples of reserved
word: if, for, while, etc
 The name should be meaningful - choose variable names in
relation with the given problem.
 Examples of variable names: Nbr1, Nbr2, Value1, Value2, Sum,
Average, Surface,Total_price, …etc
Variables data types
 Each data type prescribes and limits the form of the data,
usually limited in length.
 Different data types have different sizes in memory
depending on the machine.
 Commonly used data types are:
 Integer
 Real (Floating-point)
 Character
 String
 Boolean
Integers
 An integer is a number that has no fractional part.
 There are often different sizes of integers available; for example, PCs
support short integers, which are 2 bytes, and long integers, which are 4
bytes.
 The range of values for short integers is [-215,+215[ ([-32768,+32767[ ).
 The range of values for long integers is [-231,+231[.
 Operations used on integers are:
 The four arithmetic operations: + , - , * , /
 Comparison operators: =, !=,<, <=, >, >=
 The division / is an integer division. Ex : 11/4 =2 and not 2.75 !)
 There exist a modulus operator %, which gives the remainder of an
integer division. Ex : 11%4=3
Real (floating-point)
 It a number with a decimal point that separates the integer and
fractional parts.
 Two floating-point formats exist: single and double precision.
 Single precision uses 4 bytes (6 digits of precision order).
 Double precision uses 8 bytes (14 digits of precision order).
 Operations used on integers are:
 The four arithmetic operations: + , - , * , /
 Comparison operators: =, !=,<, <=, >, >=
 The division / gives a decimal result. Ex : 11/4 =2.75 )
 The modulus operator % doesn’t exist.
Characters
 In graphics-based applications, the term character is generally
reserved for letters, numbers, and punctuation..
 It only can represent single character.
 The following are characters: a, A, @, $, 2,..
 By convention, characters are surrounded with single quotes.
Examples: ‘a’, ‘B’, ‘5’..
 A character is data type that takes 1 byte. This byte
corresponds to the ASCII code of that character. Example,
the ASCII code of letter ‘A’ is 65 in decimal and 01000001 in
binary.
 Operations used on characters are:
 Comparison operators: =, <, >, ..
String
 String is a sequence or a series of characters.
 By convention, strings are surrounded with double quotes.
Examples: “Boumerdes City”, “Mohamed Amine”,
“Computer”,..
 Operations used on strings are:
 Concatenation operators: & (for joining multiple strings
into one string).
Boolean
 This data type only have two possible values:
–True
– False
 Use this data type for simple flags that track true/false
conditions.
 Principal operations used on booleans are:
 Logic operators: AND, OR, NOT, ..
 Truth Table for Logical Operators:
A B A AND B A OR B NOT A
False False False False True
False True False True True
True False False True False
True True True True False
How to declare variables?
 Recall: All variables must be declared before they
can be used!
 Variables are declared as follows:
Variables list of identifiers : type
 Examples:
Variables i, j, k : integer
x, y : real
OK : boolean
Str1, Str2 : string

Be careful! Variables when declared, their values are undefined,


therefore their values must be defined or initialized before being used.
Constants
 Like variables, a constant enables a value to be assigned a name.
Unlike a variable, the value assigned to a constant cannot be
changed while the program is running.
 Constants follow the same naming conventions as variables, except
that they are usually in uppercase (by convention).
 In algorithms, constants are declared as follows:
Constant identifier = value
 A constant must always receive its value at the moment of
declaration.
 Example: To calculate the surface of a circle, the value of π is
constant , however its radius is a variable.
Constant PI=3.14159
Variable r: integer
Features Used in Making Algorithms
Three main features are used in making algorithms:
 Sequence (Stepping)

 Decision (Choosing)

 Repetition (Looping).
1. Sequence
 It is made by a sequence of statements placed one
after the other.
 The instruction above or before gets executed
first.
 The main instructions used here are:
Read instruction
Write instruction
Assignment operation and expressions
to manipulate data
Read instruction
 To accept data from the user, we use Input or Read instruction.
 Examples:
− Read (A) is an instruction to ask the user to introduce a value for
variable A.
− Read (V1, V2, V3) is an instruction to ask the user to introduce
three values for variables V1,V2, and V3 respectively.
 Remarks:
− The algorithm stops when it encounters a Read instruction and it does
not move to the next instruction until the user enters the requested data
from the keyboard followed by pressing the enter key to denote the end
of the input.
− Before reading the value of a variable, it is strongly advised to write
messages on the screen, in order to tell the user what to introduce.
Write instruction
 To display data for the user, we use Print or Write
instruction.
 Examples:
− Write (Sum) is an instruction to display the value of the
variable Sum on the display device.
− Write (X1, X2) is an instruction to display the values of the two
variables X1 and X2 on the display device.
− Write (“Hello World”) is an instruction to display the message
“HelloWorld” on the display device.
− Write (“The Sum is: ”, Sum) is an instruction to display the message
“The Sum is: ” followed by the value of the variable Sum on the
display device.
Expressions
 An expression is a mathematical phrase that can
contain ordinary numbers, variables (like x or y) and
operators (like add, subtract, multiply, and divide).
− Examples: a+1, a-b, (3*x-y)/2.

 Operators used in writing expressions in algorithms:


1. Assignment operator
2. Arithmetic operators
3. Comparison operators
4. Logical operators
Assignment operator
 It is used for assigning a value to a certain variable. It is used to fill
or modify the content of that variable’s memory location.
 It is denoted with the sign (←).
 In algorithms, the assignment operator is used as follows:
v←E
− Where v is a variable and E is an expression.
− E can be a single value, single variable, or an expression.
− If E is an expression, then the result of E is assigned to v.
− v and E must be compatible in their types.
− The assignment operator modifies only its left side.
 Examples:
i ← 10, i ← j, i ← 2*j+1, x ← 2.75, Ok ← True, c ← ‘m’,
str ← “IGEE”. Where i,j are integers, x is real, OK is boolean,
c is a character, and str is a string.
Remark:
The assignments i ← 0.63, i ← x, OK ← “L01” are non-valid.
Some remarks on the assignment operation
 In the opertaion v ← E, if E is an expression then E is first
evaluted an the its result is assigned to the variable v.
 The two operations a ← b and b ← a are different!

 The assignment operation is different from a mathematical


equation!
• For example the operation x ← x+5 is valid in
algorithms. However, x+2 ← 5 is non-valid!
• In algorithms, to increment or decrement the value of
a variable x we use: x ← x+1 and x ← x-1 respectively.
How expressions are evaluated?
 An expression is evaluated from left to right. However, the
operators’ precedence should be taken into consideration.
 Arithmetic operators (+, -, *, /, and %):
 They are used to perform numerical calculations among the
values.
 Precedence of Arithmetic Operators:
1. ( )
2. *, /, % (if several, from left to right).
3. +, - (if several, from left to right).
Examples
2+3-4+5 = 6 but (2+3)-(4+5) = 5-9 = -4
9 + 3 * 4 =21 but (9 + 3) * 4 = 48
Implicit data type conversion in expressions
 When evaluating an expression, implicit or automatic type
conversion is done when its operands are of different data types.
 Type conversion (type promotion) takes place to avoid loss of data.
 All the data types of the variables are upgraded to the data type of
the variable with the largest data type according to the following
order:
Boolean → character → integer → real
 Examples:
 If a←100 and b←12.5 then a + b is 112.5
 If ch←'a’ and a←10 then a + ch is 107 because the ASCII code of a
is 97
 If x←5.0 and a←3 then x/a is 1.66
Example1
 Write an algorithm for finding the sum of two
inputted integer numbers.
Example1- Solution
Algorithm Sum_of_two_numbers
Variables x,y,sum: integer
Start
Read (x,y)
sum←x+y
Write (sum)
Stop
Example2
 Write an algorithm for finding the average value
of four inputted integer numbers.
Example2- Solution1
Algorithm Average_of_four_numbers
Variables x1,x2,x3,x4: integer
avg: real
Start
Read (x1,x2,x3,x4)
avg←(x1+x2+x3+x4)/4
Write(avg)
Stop
Example2- Solution2
Algorithm Average_of_four_numbers
Variables x1,x2,x3,x4,sum: integer
avg: real
Start
Read (x1,x2,x3,x4)
sum←x1+x2+x3+x4
avg←sum/4
Write(avg)
Stop
Example3
 Write an algorithm for finding the volume of a
cone by given its diameter and its height.

Hint: the volume of cone having a radius r and


height h is given by the following formula:
Example3- Solution
Algorithm Volume_of_Cone
Constant PI=3.14159
Variables d,h,v,r: real
Start
Read (d,h)
r←d/2
v ←(PI*r*r*h)/3
Write(v)
Stop

You might also like