C program to search an element in the array

Write a C program to read elements in an array and search whether an element exists in the array or not. C program to search an elements in an array linearly.

Example: If the elements of array are: 10, 12, 20, 25, 13, 10, 9, 40, 60, 5
Element to search is: 25
Output: Element exists

Required knowledge:

Basic C programming, If else, For loop, Array

Algorithm:

Step 1: Read elements in array A.
Step 2: Read element to be searched in num.
Step 3: Set i=0, flag=0. We have initially supposed that the number doesn't exists in the array hence we set flag=0.
Step 4: If A[i]==num then set flag=1 and print "Element found" and goto Step 6.
Step 5: Set i=i+1 and repeat Step 4 till i<size (Where size is the size of array).
Step 6: If the value of flag=0 then print "Element not found".

Program:

/**
 * C program to search an element in an array
 */

#include <stdio.h>

int main()
{
    int arr[100];
    int size, i, num, flag;

    /*
     * Read size of array and elements in array
     */
    printf("Enter size of array: ");
    scanf("%d", &size);

    printf("Enter elements in array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }

    printf("\nEnter the element to search within the array: ");
    scanf("%d", &num);

    /* Supposes that element is not in the array */
    flag = 0; 
    for(i=0; i<size; i++)
    {
        /* 
         * If element is found in the array
         */
        if(arr[i]==num)
        {
            flag = 1;
            printf("\n%d is found at position %d", num, i+1);
            break;
        }
    }

    /*
     * If element is not found in array
     */
    if(flag==0)
    {
        printf("\n%d is not found in the array", num);
    }

    return 0;
} 
Output
X
_
Enter size of array: 10
Enter elements in array: 10 12 20 25 13 10 9 40 60 5

Enter the element to search within the array: 25

25 is found at position 4

Happy coding ;)


You may also like

Labels: , ,