C

C Program To Search an Element in an Array

In this tutorial, we are going to see how to write a C program to search an element in an array. The program below asks the user to enter the size of the array, the elements of the array and the value of the element to be searched. Then it will check if the element entered by the user exists in the array.
 

C Program To Search an Element in an Array
#include <stdio.h>
 
int main() {
   int nbr, i, r, arr[30];
 
   printf("Enter the number of elements in the array: ");
   scanf("%d", &nbr);
 
   printf("Enter the array elements: ");
   for (i = 0; i < nbr; i++) {
      scanf("%d", &arr[i]);
   }
 
   printf("Enter the item to be searched: ");
   scanf("%d", &r);
 
   //Research starts from the index 0
   i = 0;
   while (i < nbr && r != arr[i]) {
      i++;
   }
 
   if (i < nbr) {
      printf("The element is found in the position = %d", i + 1);
   } else {
      printf("Element not found!");
   }
 
   return 0;
}

Output:

Enter the number of elements in the array: 6
Enter the array elements: 3 9 5 1 7 2
Enter the item to be searched: 5
The element is found in the position = 3

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *