0% found this document useful (0 votes)
2 views16 pages

Algorthm Hnd

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 16

SWE 114 :

Introduction to
algorithms

COURSE FACILITATOR :
TIOSSOCK NBONOUR BOREL
nbonouborel@gmail.com

1
Definition
An algorithm is a sequence of operations to be performed to achieve a result.
Algorithm is a step-by-step procedure, which defines a set of instructions to be
executed in a certain order to get the desired output. Algorithms are generally
created independent of underlying languages, i.e. an algorithm can be implemented
in more than one programming language.

Representation of an algorithm
There are two ways to easily represent an algorithm:
 The programming flowchart, a graphical representation used to analyze a
problem. This representation of the algorithm has the advantage of being
visual, but is poorly suited to complex problems (layout, paper to be used). This
method of representation is gradually being abandoned in favor of a structured
language.

2
Example: graphical algorithm that calculates the sum of two numbers entered on the
keyboard.

 Structured language or pseudo-code: pseudo because the code used in an


algorithm is not rigid. Pseudo-code is the textual representation of the
algorithm.

Properties of Algorithm
Not all procedures can be called an algorithm. An algorithm should have the following
characteristics

3
Categories of algorithms
 Search: Algorithm to search an item in a data structure.

 Sort: Algorithm to sort items in a certain order.

 Insert: Algorithm to insert item in a data structure.

 Update: Algorithm to update an existing item in a data structure.

 Delete: Algorithm to delete an existing item from a data structure.

4
How to write an algorithm
An algorithm has more or less the same general organization. There are three main
parts.

Name of algorithm

Declaration part: declaration of variables and constants

Processing part

START

Actions and conditions

STOP

The algorithm must have a well-defined structure. This structure must include :

-The header, which includes the name of the algorithm to identify it.

- Variable and constant declarations.

- The body of the algorithm, which contains the instructions.

5
The elementary actions of an algorithm
a. Assign

Assignment is the most common instruction in an algorithm. It consists in assigning a


variable a value belonging to its domain, i.e. giving it a first value or changing its
current value. In pseudo-code, the assignment instruction is noted with the sign

Example. X 2

Means that the variable X takes the value 2.

b. Write (or display)

The Write instruction is used to display values on an output device, usually the screen.

c. Read (or enter)

The Read instruction allows the user to enter values via an input device (usually the
keyboard) for use by the algorithm. The value entered on the keyboard will be
assigned to a variable. Read is therefore an assignment instruction.

Read and Write instructions enable dialogue between the program and the user.

Example:

Read (“Enter sales”; CA)

Write (“Sales are:”; CA)

With the Read instruction, the message “Enter sales” appears on the screen and the
user enters the sales value on the keyboard. This value is assigned to the variable CA.

With the Write instruction, the message “Sales are: “ appears on the screen, followed
by the value of the variable CA entered by the user.

6
Arithmetic Operators in Programming:
Arithmetic operators in programming are fundamental components of programming
languages, enabling the manipulation of numeric values for various computational
tasks. Here's an elaboration on the key arithmetic operators:

Operator Description Examples

Combines two numeric


+ (Addition) result <- 5 + 3; (result will be 8)
values, yielding their sum.

Subtracts the right operand difference <- 10 - 4;(difference


- (Subtraction)
from the left operand. will be 6)

Multiplies two numeric


product <- 3 * 7; (product will
* (Multiplication) values, producing their
be 21)
product.

Divides the left operand by


quotient <- 15 / 3; (quotient will
/ (Division) the right operand, producing
be 5)
a quotient.

Returns the remainder after


the division of the left
% (Modulo) remainder <- 10 % 3; (rem
operand by the right
operand.

What are constants and variables?


Constants

Constants are symbolic names given to data where the value of the data cannot
change during the execution of the program. Many constants such as PI are built into
programming languages.

Variables

7
Variables are symbolic names given to data where the value of the data stored may
change during the execution of the program. In effect, a variable is a named area of
memory used to store data.

To be used, a variable needs to be declared and defined: Declaring a variable means


telling the compiler/interpreter that such and such a name exists in such and such a
context, to enable it to resolve the uses of that name.

Example: Var variable_name : DATA TYPE (Var age: int;)

Data Type

 Integer types: byte, short, int, long.


 Floating-point types: float, double, used to represent decimals.
 Character type: char, used to represent letters, punctuation, and even emojis
in various languages.
 Boolean type: bool, used to represent "yes" or "no" decisions.

Conditional Structure in algorithm?


Conditional structures, also known as control flow statements, are essential in algorithms to make
decisions and execute different code paths based on specific conditions. These structures allow you to
create dynamic and flexible algorithms that can adapt to various inputs and scenarios.

Types of Conditional Structures:

1. If Statement:

Executes a block of code if a given condition is true.

Example:

if (age >= 18) then

write "You are an adult."

end if
8
2- If-Else Statement:

Executes one block of code if a condition is true, and another block if it's false.

Example

3- If-Else-If Ladder:

Allows for multiple conditions to be checked sequentially.

Example

9
Switch Case: A Concise Decision-Making Structure

A switch case statement is a control flow statement that allows you to execute different code blocks
based on the value of a variable or expression. It's often used as an alternative to a series of if-else
statements, especially when you have multiple possible values to check.

Basic Structure:

Explanation:

1. Expression: The value to be compared against the cases.


2. Cases: Each case label specifies a possible value for the expression.
3. Code Block: The code to be executed if the expression matches the case value.
4. break Statement: Terminates the switch statement, preventing execution of subsequent cases.
5. default Case: Optional, executed if no case matches the expression.

Example: A Simple Menu

10
Key Points:

 The break statement is crucial to prevent "fall-through" behavior, where execution continues to
the next case if no break is encountered.
 The default case is optional but recommended for handling unexpected input values.
 switch cases can only compare exact matches, not ranges or inequalities.
 In some languages, you can use fall-through behavior intentionally by omitting the break
statement.

When to Use switch Case:

 When you have a variable or expression with a limited number of possible values.
 When you want to avoid nested if-else statements, which can become complex and difficult to
read.
 When you need to perform different actions based on specific values.

By understanding the switch case statement, you can write more concise and efficient code for
decision-making scenarios.

11
The For Loop in Algorithms
A for loop is a control flow statement in programming and algorithms that allows you to execute a
block of code repeatedly a specific number of times. It's particularly useful when you know beforehand
how many iterations you need to perform.

Basic Structure of a For Loop:

Breakdown of the Components:

1. Initialization:
o This part is executed only once, at the beginning of the loop.
o It typically involves declaring and initializing a loop counter variable.
o Example: int i = 0;
2. Condition:
o This is a boolean expression that is checked before each iteration.
o If the condition is true, the loop body is executed.
o If the condition is false, the loop terminates.
o Example: i < 10
3. Increment/Decrement:
o This part is executed after each iteration of the loop body.
o It usually involves modifying the loop counter variable.
o Example: i++ (increment by 1), i-- (decrement by 1)

Example: Printing Numbers from 1 to 5

Common Use Cases:

 Iterating over arrays or lists


 Repeating a task a fixed number of times
 Generating sequences of numbers
 Simulating algorithms and data structures

Example: Calculating the Sum of Numbers from 1 to 100

12
The While Loop

A while loop is another fundamental control flow statement in programming and algorithms. Unlike a
for loop, where the number of iterations is predetermined, a while loop continues to execute as long as a
given condition remains true.

Basic Structure of a While Loop:

Example: Printing Numbers from 1 to 5

Key Points to Remember:

 The condition must eventually become false to avoid an infinite loop.


 The loop counter variable (in this case, i) must be updated within the loop body to ensure the
condition eventually becomes false.

Common Use Cases:

 Reading input until a specific condition is met


 Simulating events that occur repeatedly until a certain point
 Implementing iterative algorithms like binary search or bubble sort

Example: Reading Input Until a Negative Number is Entered

13
Choosing the Right Loop:

 Use a for loop when you know the exact number of iterations in advance.
 Use a while loop when you don't know the exact number of iterations or when you want to
continue the loop until a certain condition is met.

By understanding both for and while loops, you can effectively control the flow of your algorithms and
write more efficient and flexible code.

The Do-While Loop

A do-while loop is another control flow statement that is similar to a while loop, but with one key
difference: the condition is checked after the loop body is executed. This guarantees that the loop body
will execute at least once, regardless of the initial condition

14
Basic Structure of a Do-While Loop:

Breakdown of the Components:

1. Loop Body:
o The code within the curly braces is executed at least once.
2. Condition:
o This is a boolean expression that is checked after the loop body.
o If the condition is true, the loop body is executed again.
o If the condition is false, the loop terminates.

Example: Printing Numbers from 1 to 5

Key Points to Remember:

 The loop body is always executed at least once.


 The condition is checked after the loop body, so the loop will continue as long as the condition
is true.

Common Use Cases:

 Input validation: Ensuring that the user enters valid input before proceeding.
 Menu-driven programs: Repeating a menu until the user chooses to exit.
 Game loops: Continuously updating the game state and rendering the screen.

15
Choosing the Right Loop:

 Use a while loop when you're not sure if the loop body needs to be executed at least once.
 Use a do-while loop when you want to ensure that the loop body is executed at least once,
regardless of the initial condition. 1

16

You might also like