FaycaLProgrammer

linearSeatch

Sep 20th, 2024
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <iomanip>
  5.  
  6. using  namespace std;
  7.  
  8. int linearSearch(int A[], int N, int X)
  9. {
  10.     for (int i = 0; i < N; i++)
  11.     {
  12.         if (A[i] == X) {
  13.             return i;
  14.         }
  15.     }
  16.     return -1;
  17. }
  18.  
  19.  
  20. int main()
  21. {
  22.     const int N = 20; // حجم المصفوفة
  23.     int A[N] = { 17, 3, 45, 8, 29, 12, 56, 4, 23, 9, 31, 5, 48, 27, 1, 15, 36, 19, 7, 50 };
  24.     int x = 31;
  25.  
  26.  
  27.     // طباعة محتوي المصفوفة
  28.     for (int i = 0; i < N; i++)
  29.         cout << A[i] << " ";
  30.  
  31.     cout << "\n\n";
  32.  
  33.     // متغير لحفض نتيحة تنفيذ الدالة
  34.     int result = linearSearch(A, N, x);
  35.  
  36.     // التأكد من قيمة المتغير هل تساوي سالب واحد
  37.     // في حال نجاح العملية فالمتغير يحمل قيمة الفهرس
  38.     if (result != -1)
  39.         cout << "the value " << x << " is found in " << result << endl;
  40.    
  41.     else
  42.         cout << "the value " << x << " not found in " << result << endl;
  43.  
  44.     return 0;
  45. }
  46.  
  47.  
  48.  
Advertisement
Add Comment
Please, Sign In to add comment