Write a C program to search a number in an array using linear search.
#include <stdio.h>
#define MAX 256
int main() {
int arr[MAX], ele, i, n;
/* get the number of entries from the user */
printf("Enter the number of array entries:");
scanf("%d", &n);
/* get the array entries from the user */
printf("Enter the array entries:\n");
for (i = 0; i < n; i++) {
printf("Data[%d]: ", i);
scanf("%d", &arr[i]);
}
/* get the element to be searched */
printf("Enter the element to be searched:");
scanf("%d", &ele);
/* checks whether search element in available in i/p array */
for (i = 0; i < n; i++) {
if (arr[i] == ele) {
printf("Search element found!!\n");
return 0;
}
}
/* search element not found */
printf("Given search element is not found!!\n");
return 0;
}
#define MAX 256
int main() {
int arr[MAX], ele, i, n;
/* get the number of entries from the user */
printf("Enter the number of array entries:");
scanf("%d", &n);
/* get the array entries from the user */
printf("Enter the array entries:\n");
for (i = 0; i < n; i++) {
printf("Data[%d]: ", i);
scanf("%d", &arr[i]);
}
/* get the element to be searched */
printf("Enter the element to be searched:");
scanf("%d", &ele);
/* checks whether search element in available in i/p array */
for (i = 0; i < n; i++) {
if (arr[i] == ele) {
printf("Search element found!!\n");
return 0;
}
}
/* search element not found */
printf("Given search element is not found!!\n");
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the number of array entries:5
Enter the array entries:
Data[0]: 10
Data[1]: 20
Data[2]: 30
Data[3]: 40
Data[4]: 50
Enter the element to be searched:50
Search element found!!
Enter the number of array entries:5
Enter the array entries:
Data[0]: 10
Data[1]: 20
Data[2]: 30
Data[3]: 40
Data[4]: 50
Enter the element to be searched:50
Search element found!!
No comments:
Post a Comment