Example: If the elements of array are: 10, 12, 20, 25, 13, 10, 9, 40, 60, 5
Element to search is: 25
Output: Element exists
Required knowledge:
Basic C programming, If else, For loop, ArrayAlgorithm:
Step 1: Read elements in array A.Step 2: Read element to be searched in num.
Step 3: Set i=0, flag=0. We have initially supposed that the number doesn't exists in the array hence we set flag=0.
Step 4: If A[i]==num then set flag=1 and print "Element found" and goto Step 6.
Step 5: Set i=i+1 and repeat Step 4 till i<size (Where size is the size of array).
Step 6: If the value of flag=0 then print "Element not found".
Program:
/** * C program to search an element in an array */ #include <stdio.h> int main() { int arr[100]; int size, i, num, flag; /* * Read size of array and elements in array */ printf("Enter size of array: "); scanf("%d", &size); printf("Enter elements in array: "); for(i=0; i<size; i++) { scanf("%d", &arr[i]); } printf("\nEnter the element to search within the array: "); scanf("%d", &num); /* Supposes that element is not in the array */ flag = 0; for(i=0; i<size; i++) { /* * If element is found in the array */ if(arr[i]==num) { flag = 1; printf("\n%d is found at position %d", num, i+1); break; } } /* * If element is not found in array */ if(flag==0) { printf("\n%d is not found in the array", num); } return 0; }
Output
Enter size of array: 10
Enter elements in array: 10 12 20 25 13 10 9 40 60 5
Enter the element to search within the array: 25
25 is found at position 4
Enter elements in array: 10 12 20 25 13 10 9 40 60 5
Enter the element to search within the array: 25
25 is found at position 4
Happy coding ;)
You may also like
- Array and Matrix programming exercises index.
- C program to find maximum and minimum elements in array.
- C program to find second largest element in an array.
- C program to copy all elements of an array.
- C program to insert an element in array at specified position.
- C program to delete an element from array at specified position.
- C program to sort elements of array in ascending order.
- C program to sort elements of array in descending order.
- C program to print all unique elements in array.
- C program to enter any number and print it in words.
- C program to find power of any number without using pow() function.
- C program to find sum of all Prime numbers between 1 to n.
- C program to check whether two matrices are equal or not.
- C program to find sum of main diagonal elements of a matrix.
- C program to find transpose of a matrix.
- C program to find determinant of a matrix.