In python, loops are mainly used to execute a block of code repeatedly.
There are two main types of loop:
1.While loop
2.For loop
1. While Loop
A while loop runs as long as the condition is true.
Example:
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
flowchart of While loop:
2. For Loop
A for loop is used to repeat a block of code for every item in a sequence such as a string, list, or range.
Using For Loop with String
Example:
name = "Python"
for ch in name:
print(ch)
Output:
P
y
t
h
o
n
flowchart of For loop:
Linear Search
In Linear Search, we iterate over all the elements of the array and check if it the current element is equal to the target element. If we find any element to be equal to the target element, then return the index of the current element. Otherwise, if no element is equal to the target element, then return -1 as the element is not found.
Linear search is also known as sequential search.
Time Complexity of Linear search:
->Best case: O(1)
->Average case: O(N)
->Worst case: O(N)
Flowchart of Linear search:
Binary search
Binary search works only on sorted data. Instead of checking every element one by one, it checks the middle element and decides whether to search on the left side or right side.
This method reduces the number of comparisons and makes searching faster.
Time Complexity of Binary search:
-> Best Case: O(1)
-> Average Case: O(log N)
-> Worst Case: O(log N)
Flowchart of Binary search:
references:
https://www.geeksforgeeks.org/python/loops-in-python/
https://www.geeksforgeeks.org/dsa/linear-search/




Top comments (0)