Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Searching an Array with Linear Search in C Programming

August 26, 2013 Posted by: GPA Views: 563 0 comments

Problem

Searching an Array with Linear Search in C Programming.

Solution

Sometimes it is necessary to determine whether an array contains some value. The process of finding a particular element of an array is called searching. In this article we discuss simple linear search technique. In the below example, we have taken an array size=8 and array contains next values - {5, 1, 12, -5, 16, 2, 12, 14}. The method if(input_array[i]==key) , if the searching element is same as key element then return index of element.

 

Example:

   

#include <stdio.h>
#include <stdlib.h>
//main function
int main(int argc, char *argv[])
{
   int size=8;
   int input_array[8] = {5, 1, 12, -5, 16, 2, 12, 14};//input array
   int key,i;
   int keyindex=-1;
   printf("globalproganswer.com\n");
   printf("Enter search key: ");
   scanf("%d",&key);
   //search
   for(i=0;i<size;i++){  //check if such element is in array
       if(key==input_array[i]){
         keyindex=i;  
       }
   }
   if(keyindex!=-1){
       printf("Index of this element is: %d",keyindex);
   }else{
      printf("No such element");
   }
   printf("\n");
   system("PAUSE");
   return 0;
}

Output

searching an array with linear search in c

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe