C Linear Search šŸŽÆ

beginner
14 min

C Linear Search šŸŽÆ

Welcome to our tutorial on C Linear Search! In this lesson, we'll learn how to search for an item in an array using the Linear Search algorithm. This technique is fundamental in programming and has real-world applications, such as finding a specific name in a list of contacts or locating a product in an inventory.

Before we dive in, let's make sure you're familiar with some basic concepts:

  • Arrays: A collection of elements identified by array index.
  • Variables: A named location used to store data.
  • Functions: A piece of code that performs a specific task.

Linear Search Explained šŸ“

Linear Search is a simple and naive method used to find an element in an array. It iterates through the array element by element until it finds the desired item or reaches the end of the array.

Here's a step-by-step breakdown of the Linear Search algorithm:

  1. Define the array and the value to be searched.
  2. Initialize a variable to keep track of the current index.
  3. While the current index is less than the array size, compare the array element at the current index with the target value.
  4. If a match is found, return the index.
  5. If the loop ends without finding a match, return -1 or an error message.

Implementing Linear Search in C šŸ’”

Now, let's write a Linear Search function in C.

c
#include <stdio.h> int linear_search(int arr[], int size, int target) { int i; for (i = 0; i < size; i++) { if (arr[i] == target) { return i; } } return -1; }

šŸ’” Pro Tip: It's a good practice to check if the array is not empty before performing a Linear Search.

Practical Application šŸ“

Let's put our Linear Search function to work! Consider an array containing exam scores:

c
int scores[] = {85, 67, 91, 78, 92}; int result = linear_search(scores, 5, 92); if (result != -1) { printf("The score 92 is at index %d.", result); } else { printf("The score 92 is not found in the list."); }

Upon running this code, we'll see that the score 92 is found at index 4.

Linear Search Efficiency šŸ“

It's essential to understand that Linear Search has a time complexity of O(n), where n is the number of elements in the array. This means that the algorithm becomes slower as the size of the array increases. Thus, for large datasets, more efficient search algorithms like Binary Search should be used.

Quiz Time šŸŽÆ

Quick Quiz
Question 1 of 1

What is the time complexity of the Linear Search algorithm?

That's all for today! In the next lesson, we'll learn about Binary Search, an optimization of Linear Search for sorted arrays. Until then, happy coding! šŸš€