C program to search an element in an array

This program declares an array, takes user input to populate the array, then takes another input for the element to be searched. It searches for the element in the array using a loop and displays the result. The position is displayed if the element is found, and a message is shown if it is not found.

C program to search an element in an array

#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

Step 1: User Input

  • The program prompts the user to enter two elements for the array.
  • Enter the elements in the array:

Step 2: Array Initialization

  • The user enters two integers, and they are stored in the array.

Step 3: User Input for Search Element

  • The program prompts the user to enter an element they want to search for in the array.
  • Enter the element you want to search:

Step 4: Searching the Array

  • The program searches for the entered element in the array using a for loop.
  • If the element is found, it sets the found flag to 1 and breaks out of the loop, storing the position where the element was found.

Step 5: Displaying the Result

  • If the found flag is 1, it prints the position of the found element.
  • If the found flag is 0, it prints that the element is not found in the array.

Expected Output:

  • If you input array elements as 10 and 20 and then search for 20:
  • Enter the elements in the array: 10 20 Enter the element you want to search: 20 20 is found at position 2
  • If you input array elements as 10 and 20 and then search for 30:
  • Enter the elements in the array: 10 20 Enter the element you want to search: 30 30 is not found in the array

Leave a Comment