Session 1
Session 1
1
Muhammad ibn Musaal -
Khwarizmi
Father of Algorithm
2
Definition:
An algorithm is a finite set of instructions that accomplishes a particular
task.
All algorithms must satisfy the following criteria.
Characteristics:
1. Input : Zero or more quantities are externally supplied.
2. Output : At least one quantity is produced.
3. Definiteness : Each instruction is clear and unambiguous.
Statements such as “add 6 or 7 to x” is not permitted”
To check whether the algorithm giving correct output or not for all
possible inputs.
3. How to analyze an algorithm
Based on performance measures such as space and time
i) How much time required
ii) How much space required
We can use a natural language like English, but if we select this option,
we must make sure that the resulting instructions are definite.
We can also represent algorithms using pseudo code that resemble C
and Pascal.
We present most of our algorithms using pseudo code that resembles C
and Pascal.
1. Comments begin with // and continue until end of the line.
2. Blocks are indicated with matching braces: { and }.
i. A compound statement
ii. Body of a procedure.
3.
i. An identifier begins with a letter.
ii. The data types of variables are not explicitly declared.
iii. The types will be clear from the context.
iv. Whether a variable is global or local to a procedure will also be evident
from the context.
v. We assume simple data types such as integer, float, char, boolean, and so
on.
9
4. Assignment of values to variables is done using the assignment
statement.
< variable > := < expression >
5. There are two boolean values true and false. To produce these values,
logical operators and, or and not and the relational operators <, ≤,=, ≠, ≥
and > are provided.
repeat
<statement 1>
:
<statement n>
until ( condition )
The statements are executed as long as condition is false
9. Input and output are done using the instructions read and write.
Ex: read n;
write n;
12
10. Procedure or function starts with the word
Algorithm.
General form :
Algorithm Name( <parameter list> )
{
body
}
where Name is the name of the procedure.
Simple variables to procedures are passed by value.
Arrays and records are passed by reference
WRITE AN ALGORITHM TO FIND SUM OF N NUMBERS IN THE GIVEN LIST
Algorithm sum(a,n)
{
s:=0;
for i:=1 to n do
s:=s+a[i];
return s;
}
14
WRITE AN ALGORITHM TO FIND FACTORIAL OF A GIVEN NUMBER.
15
SAMPLE QUESTIONS
• Describe the concept of recursion in algorithms. Provide an example algorithm that uses recursion
• What is an algorithm? Provide a brief definition and explain its importance in computer science.
16