0% found this document useful (0 votes)
25 views165 pages

Algorithm 1 & 2 - by MR Benabderrezak

Uploaded by

krkrwassim7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views165 pages

Algorithm 1 & 2 - by MR Benabderrezak

Uploaded by

krkrwassim7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 165

Algorithm 1

1
workplan
1. What is an Algorithm ?

2. Variables and Constants

3. Data Types / Operators

4. Input / Output

5. Conditions / Loops

6. Arrays (1-D , 2-D)

7. Strings

8. Structures (Structs) 2

2
3

3
Inputs
- Refer to the data that is read by an algorithm from an external source,

such as a file, keyboard input, or network socket

4
Output
- An algorithm's output specifies the results that must have occurred by

the time the algorithm is finished.

5
Basic structure

6
Basic structure

7
Characteristics of an algorithm ?
● Clear and Unambiguous

Each of its steps should be clear in all aspects and must lead to only one meaning.

● Well-Defined Inputs

If an algorithm says to take inputs, it should be well-defined inputs.

9
Characteristics of an algorithm ?
● Well-Defined Outputs

The algorithm must clearly define what output will be yielded and it should be

well-defined as well.

● Finite-ness

The algorithm must be finite, i.e. it should terminate after a finite time.

10

10
Characteristics of an algorithm ?
● Feasible

The algorithm must be simple, generic, and practical, such that it can be executed with the

available resources.

● Language Independent

The Algorithm must be just plain instructions that can be implemented in any language, and yet

the output will be the same, as expected.

11

11
Variables
- Variables are symbolic names given to data where the value of the data

stored may change during the execution of the program.

12

12
Variables

13

13
Basic Data types
- Each variable /constant has an associated data type.

- It specifies the type of data that the variable can store like

1. integer : -1 , -7 , 0 , 1 , 2

2. character : ‘a’ , ‘b’,

3. floats : 2.3 , 3.8, -7.89

4. characters : “a” , “word not single letter”

14

14
Basic Data types ranges

Type Range

Int -32,768 to 32,767


Float 3.4E-38 to 3.4E+38
Double 1.7E-308 to 1.7E+308
Char -128 to 127

15

15
16

16
Constants
- A constant is a data item whose value cannot change during the

program's execution.

17

17
Constants

18

18
Read in an algorithm
- To read a variable from keyboard we use :

1. read ( variable_name) : when we write a pseudo algorithm

2. scanf(“%x”,&variable_name”) : when we write a program c

19

19
Write in an algorithm
- To write (print) a variable to the console we use :

1. write ( variable_name) : when we write a pseudo algorithm

2. printf(“%x”,variable_name”) : when we write a program c

20

20
Example

21

21
22

22
Example

23

23
Example

24

24
Operators
1. Arithmetic operators

2. Assignment operators

3. Comparison operators

4. Logical operators

25

25
1. Arithmetic operators

26

26
1. Arithmetic operators

27

27
2. Assignment operators

28

28
29

29
30

30
3. Comparison operators

31

31
32

32
33

33
34

34
3. Logical operators

35

35
36

36
37

37
38

38
39

39
Conditions
- Also known as conditional statements or control structures

- Used to make decisions based on certain conditions

40

40
Conditions

41

41
Conditions - If statement
- The if statement is used to execute a block of code if a specified condition is

true

42

42
Conditions - If statement

43

43
Conditions - If-else statement

44

44
Conditions - If-else statement

45

45
Conditions - switch statement
The switch statement is used to perform different actions based on different possible

values of a variable

46

46
Conditions - switch statement

47

47
Conditions - switch statement

48

48
Loops
Loops are used in programming to repeat a block of code multiple times

49

49
Loops
In most programming languages, there are mainly three types of loops:

1. for loop

2. while loop

3. do-while loop

4. Foreach loop

50

50
Loops- For
The for loop is used to repeatedly execute a block of code a specified number of

times

51

51
Loops- For

52

52
Loops- For

53

53
54

54
Loops- while
The while loop is used to repeatedly execute a block of code as long as a condition is

true

55

55
Loops- while

56

56
Loops- while

57

57
58

58
Loops- do-while
- The do-while loop is used to repeatedly execute a block of code at least once,

and then continue execution as long as a condition is true.

- Syntax

59

59
Loops- do-while

60

60
Loops- do-while

61

61
62

62
Arrays
- Arrays are data structures in programming used to store a collection of

elements

of the same type.

63

63
Arrays 1-D
One-dimensional arrays, also known as simple arrays or vectors, are arrays that

store elements in a single row or a single column

64

64
Arrays 1-D

65

65
Arrays 1-D

66

66
Arrays 1-D

67

67
Arrays 1-D

68

68
Arrays 2-D
- Two-dimensional arrays, also known as matrices or grids

- Are arrays that store elements in a tabular form with rows and columns with the same

type (int, float, char, ....)

69

69
Arrays 2-D

70

70
Arrays 2-D

71

71
Loop through an Array 2-D

72

72
Strings
- Strings are used for storing text/characters. ex : "Hello World"

- A String in C is a sequence of characters terminated with a null character ‘\0’

73

73
74

74
75

75
Structures (Structs)
- A way to group several related variables into one place.

- Each variable in the structure is known as a member of the structure.

- Example

76

76
Structures (Structs)

77

77
Structures (Structs)

78

78
Structures (Structs)

79

79
Algorithm 2

81
workplan
1. Functions

2. File handling

3. Recursion

4. Pointers

5. Dynamic variables

6. Stack / Queue

7. Linked List / Trees 82

82
Functions
• A function is a block of code which only runs when it is called

• Functions are important for reusing code

• Define the code once, and use it many times

83

83
Functions

84

84
Create Function
To create a function, we need to specify :

1. Return type

2. The name of the function

3. The parameters

85

85
Function Parameters

return_type function_fame (parameter1, parameter2)


{
// code to be executed
}

86

86
Function Parameters

87

87
File Handling
In C, you can create, open, read, and write to files by:

1. Declaring a pointer of type FILE

2. Use the fopen() function

88

88
File Handling

89

89
Create File

90

90
Write to File

91

91
Write to File

• As a result, when we open the file on our computer, it looks like this:

92

92
Append Content

93

93
Append Content
• As a result, when we open the file on our computer, it looks like this:

94

94
Read from file
• To read from a file, you can use the r mode:

95

95
Read from file

96

96
Read from file

Note

• The fgets() function only reads the first line of the file.

• If you remember, there were two lines of text in filename.txt

• To read every line of the file, we use a while loop

97

97
Read from file

Hello World!
Hi everybody!

98

98
Recursion
• Recursion is the technique of making a function call itself.

99

99
Recursion - Example
• Adding two numbers together is easy to do, but adding a range of
numbers is more complicated.

100

100
Recursion - Example

101

101
Recursion - Example

• When running, the program follows these steps:


Iteration 1: 10 + sum(9)
Iteration 2: 10 + ( 9 + sum(8) )
Iteration 3: 10 + ( 9 + ( 8 + sum(7) ) )
Iteration 4: ...
Iteration 10: 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
Iteration 11: 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
102

102
Recursion - Example 2

103

103
Recursion - Example 3 (Find max in an array)

104

104
Recursion - Example 4 (print numbers from 1 to a given number )

105

105
Recursion - Example 4 (print numbers from 1 to a given number )

106

106
Recursion - Example 4 (print numbers from 1 to a given number, Method 2)

107

107
Recursion - Example 4 (print numbers from 1 to a given number, Method 2)

108

108
Recursion - Example 4 (print numbers from 1 to a given number, Method 2)

109

109
Recursion - More Examples
https://www.w3resource.com/c-programming-exercises/recursion/index.php

110

110
Pointers
- When a variable is created in C, a memory address is assigned
to the variable.

- The memory address is the location of where the variable is stored on


the computer.

111

111
Pointers
To access it, use the reference operator (&), and the result represents
where the variable is stored

112

112
Pointers
● A pointer is a variable that stores the memory address of another
variable as its value.

● A pointer variable points to a data type (like int) of the same type,
and is created with the * operator.

113

113
Pointers

114

114
Pointers - Example 1

115

115
Pointers - Example 2

116

116
Dynamic variables
1. Compile Time

• Refers to the period during which a program is compiled, or translated from its

human-readable source code into machine-readable code

• During the compile time, the program is not executing any instructions

and there is no active interaction with the user.


117

117
Dynamic variables
2. Run time (execution time)
- refers to the period of time during which a program is running, from when

it is started until it is terminated

- During runtime, the program is executing instructions, performing

calculations, and manipulating data according to the instructions given by

the program's code

118

118
Dynamic variables
3. Memory Allocation

• Memory allocation refers to the process of setting aside a portion of the

computer's memory (RAM) for a program to use.

• This is where variables, arrays, and other data structures used by the

program are stored

119

119
Dynamic variables

• Dynamic variable, also known as dynamically allocated memory

• is a way to allocate memory for a variable at runtime, rather than at


compile time.

120

120
Dynamic variables
- When we create a dynamic variable, we use functions like malloc() or

calloc() to allocate memory for the variable.

- Once the memory is allocated, we can use the variable just like any other

variable in our program

121

121
Dynamic variables

122

122
Dynamic variables

123

123
Stack
A stack is a linear data structure, a collection of items of the same type

124

124
Stack
- A stack is a data structure that allows for the insertion and removal of

elements at one end only

- A stack follows the L.I.F.O principle, with the last inserted element being

the first to be removed.

- To access older items, previous elements must be removed

125

125
Stack
The following are the basic operations served by stacks.

❖ push: Adds an element to the top of the stack.

❖ pop: Removes the topmost element from the stack.

❖ isEmpty: Checks whether the stack is empty.

❖ isFull: Checks whether the stack is full.

❖ topEelement: Displays the topmost element of the stack.


126

126
Stack
The basic syntax for declaring a stack typically involves creating :

1. an array

2. an integer variable to keep track of the top element's position

127

127
Stack

128

128
Stack

129

129
Stack

130

130
Queue
- A queue is a linear data structure

- A collection of items of the same type

131

131
Queue
• A queue is a data structure that allows for the insertion and removal

of elements at one end only

• A queue follows First-In-First-Out (FIFO) principle, which means that the

first element added to the queue will be the first one to be removed

132

132
Queue
❖ isEmpty(): To check if the queue is empty

❖ isFull(): To check whether the queue is full or not

❖ dequeue(): Removes the element from the frontal side of the queue

❖ enqueue(): It inserts elements to the end of the queue

❖ getFront: Pointer element responsible for fetching the first element from the queue

❖ getRear: Pointer element responsible for fetching the last element from the queue

133

133
Queue
The basic syntax for declaring a queue typically involves creating :

a. an array

b. 2 integer variables to keep track of the first & last element's position

134

134
Queue

135

135
Queue

136

136
Queue

137

137
Queue

138

138
Queue

139

139
Queue

140

140
Linked List
- A linked list is a data structure that consists of a sequence of nodes

- each node containing a value and a reference to the next node in the list

141

141
Linked List vs Array

142

142
Why Linked List ?
• The size of the arrays is fixed

• Insertion of a new element / Deletion of a existing element in an array is

expensive

143

143
Linked List Drawbacks
• Random access is not allowed.( sequentially starting from the first node)

• Searching for an element is costly

• Sorting of linked lists is very complex and costly

• Appending an element to a linked list is a costly operation

• ...etc (see below : https://www.geeksforgeeks.org/what-is-linked-list/ )

144

144
Linked List
- The basic syntax for declaring a linked list typically involves creating :

1. A struct contain Data (it can be 1 variable or more)

2. Pointer to same struct

145

145
Linked List - Basic Operations
1. Deletion (in the head , middle, end)

2. Insertion (in the head , middle, end)

3. Search

4. Display

146

146
Linked List - Basic Operations
1. Display

147

147
Linked List - Basic Operations
2. Delete ( in the head)

148

148
Linked List - Basic Operations
3. Insert ( in the head)

149

149
Trees

150

150
Trees

Tree in c is :

✔ A non-linear data structure

✔ Contains nodes that are not connected linearly

✔ They are connected in a hierarchical manner

151

151
Why Trees ?

152

152
Why Trees ?
• Hierarchical structure

• Efficient searching/sorting

• Balanced trees for consistent performance

• Binary trees/heaps for various operations

• Decision trees in machine learning

• Tree-based search algorithms


153

153
Why Trees ?
• Storage overhead

• Insertion and deletion complexity

• Lack of dynamic operations

• Inefficiency for sorted data

• Unbalanced trees

• Lack of random access

• Memory fragmentation

• Difficulty in tree traversal


154

154
Trees
The basic syntax for declaring a tree typically involves creating :

1. a struct contain Data (it can be 1 variable or more)

2. pointer to the left child node and the right child node

155

155
Trees - Basic Operations
● Insertion / Deletion / Search

● Traversal (In-order, Pre-order, Post-order, Level-order)

● Height / Depth / Counting Nodes

● Minimum/Maximum

● Checking Balanced Tree

● Checking if Binary Search Tree

● Mirror Image
156

156
Trees - Basic Operations
1. In-Order Traversal : the left subtree is visited first, then the root node, and
finally the right subtree.

157

157
Trees - Basic Operations
1. Pre-Order Traversal : the root node is visited first, then the left subtree,
and finally the right subtree.

158

158
Trees - Basic Operations
3. Post-Order Traversal : the left subtree is visited first, then the right subtree,
and finally the root node.

159

159
Trees - Practice Time
● Given the root of a binary tree and an integer target_sum

● return true if the tree has a root-to-leaf path such that adding up all the values

along the path equals targetSum.

● A leaf is a node with no children.

160

160
Trees - Practice Time

target_sum = 22

Output: true

Explanation: The root-to-leaf path with the target

sum is shown

161

161
Trees - Practice Time

target_sum = 5

Output: false

Explanation: There two root-to-leaf paths in the tree:

(1 --> 2): The sum is 3.

(1 --> 3): The sum is 4.

There is no root-to-leaf path with sum = 5.


162

162
Trees - Practice Time (Proposed Solution)

163

163
References
1. https://www.w3schools.com/
2. https://chat.openai.com/
3. https://www.programiz.com/

164

164

You might also like