C Program To Search An Element In An Array

C Program To Search An Element In An Array: A simple program to search an element in an array using for loop and if else statement.

#include <stdio.h>

void main(){
    int arr[2], i, found, search, pos;

    printf("Enter the elements in the array: \n");

    for (int i = 0; i < 2; i++)
    {
        scanf("%d",&arr[i]);
    }

    printf("Enter the element you want to search: ");
    scanf("%d",&search);

    for (int i = 0; i < 2; i++)
    {
        if(arr[i] == search)
        {
            pos = i+1;
            found = 1;
            break;
        }
    }

    if(found == 1)
    {
        printf("\n%d is found at position %d\n", search, pos);
    }
    else
    {
        printf("%d is not found in the array", search);
    }
}

Explanation:

In this program we are traversing through the array and checking if the element is equal or not equal to search element. If it is then note the index value in a variable called position, and using another variable found for boolean purpose.

if found is equal to 1 then element is found and if not then element not found.