Search an element in an array with C.
#include <stdio.h>
int main()
{
int arr[100];
int size, i, toSearch, found;
/* Input size of array */
printf("Enter size of array: ");
scanf("%d", &size);
/* Input elements of array */
printf("Enter elements in array: ");
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
found = 0;
for (i = 0; i < size; i++)
{
if (arr[i] == toSearch)
{
found = 1;
break;
}
}
if (found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array", toSearch);
}
return 0;
}
Output
Enter size of array : 5
Enter elements in array : 1 2 3 4 5
Enter element to search : 4
4 is found at position 4
0 Comments