Linear Search in C and C++ Languages

Linear search simply means 'looking for an element in the whole array from one end to the other'. The searched element is compared with the first element of array first, then with the second, then with the third, so on upto the end of the array. This is time consuming when the array is pretty enough. The time complexity is highest.The C and C++ programs for linear search is given below.

C Program:

#include<stdio.h>

void main()
{
int array[30], num, search, i;

printf("\nEnter the number of elements");

scanf("%i", &num);

printf("\nEnter the elements\n");

for (i = 0; i < num; i++)

{

scanf("%i", &array[i]);

}

printf("\nEnter the number to search for");

scanf("%i", &search);

for (i = 0; i < num; i++)

{

if (search == array[i])

printf("found at %i th position", i);

}

}


C++ Program:



#include<iostream.h>

int main()

{

int array[30], num, search, i;

cout<<"\nEnter the number of elements";

cin>>num;

cout<<"\nEnter the elements\n";

for (i = 0; i < num; i++)

{

cin>>array[i];

}

cout<<"\nEnter the number to search for";

cin>>search;

for (i = 0; i < num; i++)

{

if (search == array[i])

cout<<"found at position"<< i;

}

return 0;

}


No comments :

Post a Comment