You are on page 1of 8

QUESTION:

Given an array arr[] of n elements, write a program to search a given element x in arr[].

Examples :

Input : arr[] = {10, 20, 80, 30, 60, 50,

110, 100, 130, 170}

x = 110;

Output : 6

Element x is present at index 6

Input : arr[] = {10, 20, 80, 30, 60,

50,

110, 100, 130, 170}

x = 175;

Output : -1

Element x is not present in arr[].


EX:NO:3.3
DATE:26.11.2021 LINEAR SEARCH

AIM:

To write a c program to search a given element x in arr[].

Data structure used:array

Data type:integer

Routine:iterative

PSEUDOCODE:

BEGIN

int arr[100],key,i, n;

for i= 0;

for i=0;

BEGIN

if (arr[i] ==key)

Display the present at location ; break;

END

if (i== n)

Display isn't present in the array;

return 0;

END

SOURCE CODE:
#include <stdio.h>

int main()

int arr[100],key,i, n;

printf("Enter number of elements in array\n");

scanf("%d", &n);

printf("Enter %d integer(s)\n", n);

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

scanf("%d", &arr[i]);

printf("Enter a number to search\n");

scanf("%d", &key);

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

if (arr[i] ==key)

printf("%d is present at location %d.\n",key,i+1);

break;

if (i== n)

printf("%d isn't present in the array.\n", key);

return 0;
}

OUTPUT:

RESULT:

By using the above code to search a given element x in arr[] using linear search is successfully
done and output is verified.
QUESTION:
EX:NO:3.3
DATE:26.11.2021 BINARY SEARCH

AIM:

To write a c program to search a given element x in arr[] using binary search.

Data structure used:array

Data type:integer

Routine:iterative

PSEUDOCODE:

BEGIN

display"Enter value to find”;

for l= 0;

r=n - 1;

m=(l+r)/2;

while (l<=r) {

if (arr[m]<key)

l=m+1;

else if (arr[m] ==key)

display " found at location ";

break;

else
r= m-1;

m=(l+r/2);

if (l>r)

DISPLAY"Not found! %d isn't present in the list.\n;

END

return 0;

SOURCE CODE:
#include <stdio.h>

int main()

int i,l,r, m, n,key, arr[100];

printf("Enter number of elements\n");

scanf("%d", &n);

printf("Enter %d integers\n", n);

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

scanf("%d", &arr[i]);

printf("Enter value to find\n");

scanf("%d", &key);

l= 0;

r=n - 1;
m=(l+r)/2;

while (l<=r) {

if (arr[m]<key)

l=m+1;

else if (arr[m] ==key) {

printf("%d found at location %d.\n",key,m+1);

break;

else

r= m-1;

m=(l+r/2);

if (l>r)

printf("Not found! %d isn't present in the list.\n",key);

return 0;

OUTPUT:

RESULT:

By using the above code to search a given element x in arr[] using linear search is successfully
done and output is verified.

You might also like