Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

28. what is best way to search an element in array ?

write a program

1. Input size and elements in array from user. Store it in some variable


say size and arr.
2. Input number to search from user in some variable say toSearch.
3. Define a flag variable as found = 0. I have initialized found with 0, which
means initially I have assumed that searched element does not exists in array.
4. Run loop from 0 to size. Loop structure should look like for(i=0; i<size; i+
+).
5. Inside loop check if current array element is equal to searched number or not.
Which is if(arr[i] == toSearch) then set found = 1 flag and terminate from loop.
Since element is found no need to continue further.
6. Outside loop if(found == 1) then element is found otherwise not.
7. #include <stdio.h>
8.
9. #define MAX_SIZE 100 // Maximum array size
10.
11.int main()
12.{
13. int arr[MAX_SIZE];
14. int size, i, toSearch, found;
15.
16. /* Input size of array */
17. printf("Enter size of array: ");
18. scanf("%d", &size);
19.
20. /* Input elements of array */
21. printf("Enter elements in array: ");
22. for(i=0; i<size; i++)
23. {
24. scanf("%d", &arr[i]);
25. }
26.
27. printf("\nEnter element to search: ");
28. scanf("%d", &toSearch);
29.
30. /* Assume that element does not exists in array */
31. found = 0;
32.
33. for(i=0; i<size; i++)
34. {
35. /*
36. * If element is found in array then raise found flag
37. * and terminate from loop.
38. */
39. if(arr[i] == toSearch)
40. {
41. found = 1;
42. break;
43. }
44. }
45.
46. /*
47. * If element is not found in array
48. */
49. if(found == 1)
50. {
51. printf("\n%d is found at position %d", toSearch, i + 1);
52. }
53. else
54. {
55. printf("\n%d is not found in the array", toSearch);
56. }
57.
58. return 0;
59. }
Output

Enter size of array: 10


Enter elements in array: 10 12 20 25 13 10 9 40 60 5

Enter element to search: 25

25 is found at position 4

You might also like