Advertisement
kebria

Linear Search Using Function

Jun 26th, 2021
1,351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.83 KB | None | 0 0
  1. /* Linear Search */
  2.  
  3. #include <stdio.h>
  4. int linear_search(int num[], int n, int value)
  5. {
  6.     int position = -1;
  7.     for (i = 0; i < n; i++)
  8.     {
  9.         if (value == num[i])
  10.         {
  11.             position = i + 1;
  12.             break;
  13.         }
  14.     }
  15.     return -1;
  16.  
  17. }
  18. int main()
  19. {
  20.     int num[20];
  21.     int n, i;
  22.     printf("How many numbers? ");
  23.     scanf("%d", &n);
  24.     printf("Enter %d numbers : ", n);
  25.     for (i = 0; i < n; i++)
  26.     {
  27.         scanf("%d", &num[i]);
  28.     }
  29.     int value, position = -1;
  30.     printf("Enter the value you want to search : ");
  31.     scanf("%d", &value);
  32.    
  33.     int result = linear_search(num, n, value);
  34.     if (result == -1)
  35.         printf("Value is not found\n");
  36.     else
  37.         printf("Value is found at position %d", result );
  38. }
  39.  
  40.  
  41. /*
  42. Output:
  43. How many numbers ? 5
  44. Enter 5 numbers : 12 23 34 45 56
  45. Enter the value you want to search : 56
  46. Value is found at position 5
  47. */
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement