Searching One-Dimensional Arrays - C Array

C examples for Array:Array Element

Introduction

Use looping structures, such as the for loop, to iterate through each element until the search value is found or the search is over.

Demo Code

#include <stdio.h> 
int main()//from   w ww . j  av a2  s . c  o  m
{
   int x = 0;
   int iValue = 0;
   int iFound = -1;
   int iArray[5];

   for (x = 0; x < 5; x++)
      iArray[x] = (x + x);   //initialize array 

   printf("\nEnter value to search for: ");

   scanf_s("%d", &iValue);

   for (x = 0; x < 5; x++) {
      if (iArray[x] == iValue) {
         iFound = x;
         break;
      }
   }

   if (iFound > -1)
      printf("\nI found your search value in element %d\n", iFound);
   else
      printf("\nSorry, your search value was not found\n");
}

Result


Related Tutorials