Search an integer from an array of integers in C

/* Click here to see a list of all C/C++ programs */

#include<stdio.h>

main()
{
int array[10];
int i,found,element,position;
found=0;   //variable ‘found’ acts like a flag variable

printf(“\nPlease enter 10 integer elements : \n\n”);
for(i=0;i<10;i++)   //to accept 10 integers in the array
{
printf(“Element %d: “,i+1);
scanf(“%d”,&array[i]);
}

printf(“\nPlease enter the element to be searched: “);
scanf(“%d”,&element);

for(i=0;i<10;i++)
{
if(array[i]==element)
{
found=1;   //if the element is present, assign found=1
position=i+1;   //store the position at which the element is present
}
}

if(found==1)   //if found has value ’1′, the element must be present
{
printf(“\nThe element %d is present at position %d\n\n”,element,position);
}
else   //if  found still has original value ’0′, then the element is not present
{
printf(“\nThe element %d is not present in the array\n\n”,element);
}
}

/* OUTPUT:

[tc@localhost ~]$ cd Desktop
[tc@localhost Desktop]$ gcc searcharray.c
[tc@localhost Desktop]$ ./a.out

Please enter 10 integer elements :

Element 1: 12
Element 2: 5
Element 3: 63
Element 4: 41
Element 5: 74
Element 6: 91
Element 7: 87
Element 8: 324
Element 9: 86
Element 10: 59

Please enter the element to be searched: 86

The element 86 is present at position 9

[tc@localhost Desktop]$ ./a.out

Please enter 10 integer elements :

Element 1: 12
Element 2: 5
Element 3: 63
Element 4: 41
Element 5: 74
Element 6: 91
Element 7: 87
Element 8: 324
Element 9: 86
Element 10: 59

Please enter the element to be searched: 22

The element 22 is not present in the array

[tc@localhost Desktop]$

*/

/* Click here to see a list of all C/C++ programs */

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.