C Program to Search an Element in Array

1. Introduction

Searching for an element in an array is one of the basic tasks when working with data structures. This post will guide you through a C program that searches for a specific element in an array. We'll then provide an in-depth explanation to help you understand the logic behind the code.

2. Program Overview

The C program will:

1. Obtain the size of the array and its elements from the user.

2. Ask the user for the element they wish to search.

3. Search for the element in the array.

4. Display the position of the element if found or notify the user if the element is not present.

3. Code Program

#include <stdio.h>

int main() {
    int n, i, search, flag = 0;
    int arr[100];
    
    // Collecting the number of elements in the array
    printf("Enter the number of elements in array: ");
    scanf("%d", &n);
    
    // Obtaining the elements
    printf("Enter %d integers:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Getting the element to search
    printf("Enter the element to search: ");
    scanf("%d", &search);
    
    // Searching the element
    for(i = 0; i < n; i++) {
        if(arr[i] == search) {
            printf("Element found at position: %d\n", i);
            flag = 1;
            break;
        }
    }
    
    if(flag == 0) {
        printf("Element not found in the array.\n");
    }

    return 0;
}

Output:

Enter the number of elements in array: 5
Enter 5 integers:
10
20
30
40
50
Enter the element to search: 40
Element found at position: 3

4. Step By Step Explanation

1. Variable Declaration:

- n is the number of elements in the array.

- arr[100] is the array containing the elements.

- search holds the value of the element we want to find.

- flag acts as a marker to indicate whether the element has been found.

2. Input Gathering:

- We begin by asking the user for the number of elements and the elements themselves.

- We then ask for the value of the element they want to search for.

3. Searching for the Element:

- We use a for loop to iterate through the array.

- Inside the loop, we use an if condition to check if the current element in the array (arr[i]) is equal to the search value.

- If a match is found, we display the position and set the flag to 1. We also break out of the loop, as our objective is achieved.

4. Notifying if Element is Not Found:

- After the loop, we check the value of the flag. If it's still 0 (meaning no match was found), we notify the user that the element is not in the array. 

This program efficiently checks each element of the array to see if it matches the search value. If you are looking to work with larger datasets or require faster search times, there are more advanced search algorithms and data structures to consider, such as binary search or hash tables.

Comments