C Program to search an element in an array using functions - IProgramX

Q. Write a function for Linear Search, which accepts an array of n elements and a key as parameters and returns the position of key in the array and -1 if the key is not found. Accept n numbers from the user, store them in an array. Accept the key to be searched and search it using this function. Display appropriate messages


Program

#include <stdio.h>
int main()
{
int arr[100],n;
void accept(int a[100], int n);
int find(int a[100], int n);
accept(arr,n);
find(arr,n);
}
void accept(int array[100], int n)
{
  int  c ;

  printf("Enter the number of elements in array\n");
  scanf("%d", &n);

  printf("Enter %d integer\n", n);

  for (c = 0; c < n; c++)
    scanf("%d", &array[c]);
}
int find(int array[100], int n)
{
int search,c;
  printf("Enter a number to search\n");
  scanf("%d", &search);

  for (c = 0; c < n; c++)
  {
    if (array[c] == search)
    {
      printf("%d is present at location %d.\n", search, c+1);
      break;
    }
  }
  if (c == n)
    printf("%d isn't present in the array.\n", search);

  return 0;
}

Output:

Enter the number of elements in array
5
Enter 5 integer
3
5
2
8
4
Enter a number to search
8
8 is present at location 4.

Post a Comment

0 Comments