Advertisement
Lavig

Лабораторна робота №14 (Завдання 2)

Dec 5th, 2024
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <windows.h>
  3. #include <vector>
  4.  
  5. using namespace std;
  6. int index(vector<int> arr, int a, int b);
  7. int main()
  8. {
  9.     SetConsoleOutputCP(1251);
  10.     vector<int> numbers{};
  11.     srand(time(0));
  12.     int num, elements{}, i{}, length{}, target{};
  13.     elements = rand() % 10 + 3;
  14.     cout << "Згенерований масив: " << endl;
  15.     for (i = 0; i < elements; i++) {
  16.         num = rand() % 10 + 1;
  17.         numbers.push_back(num);
  18.         cout << num << " ";
  19.     }
  20.     cout << endl;
  21.     while (true) {
  22.         cout << "Введіть будь-яке ціле число від 1 до 10: ";
  23.         cin >> target;
  24.         if (cin.fail() || cin.peek() != '\n' || target < 1 || target > 10) {
  25.             cin.clear();
  26.             cin.ignore(32767, '\n');
  27.             cout << "Число було введено неправильно. Спробуйте ще раз!" << endl;
  28.             continue;
  29.         }
  30.         else {
  31.             break;
  32.         }
  33.     }
  34.     length = numbers.size();
  35.     cout << "Індекс заданого числа: " << index(numbers, length, target);
  36. }
  37. int index(vector<int> arr, int a, int b)
  38. {
  39.     int i{};
  40.     for (i = 0; i < a; i++) {
  41.         if (arr[i] == b){
  42.             return i;
  43.         }
  44.     }
  45.     return -1;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement