Advertisement
janac

Indices of even numbers

Nov 4th, 2021 (edited)
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. // Take a list of numbers and return the indices of the even numbers.
  6.  
  7. // This function takes an integer and returns
  8. // true if it is even. Otherwise, it returns false.
  9. int is_even(int number)
  10. {
  11.     // If two divides into the number evenly
  12.     if (number % 2 == 0)
  13.     {
  14.         // The number is even.
  15.         return true;
  16.     }
  17.     else // Otherwise,
  18.     {
  19.         // The number is odd.
  20.         return false;
  21.     }
  22. }
  23.  
  24. // This function takes a list of numbers and returns
  25. // the indices of the even numbers.
  26. vector<int> get_even_numbers(vector<int>& number_list)
  27. {
  28.     // These are the indices of the even numbers.
  29.     vector<int> even_number_indices;
  30.  
  31.     // We are testing this number.
  32.     int current_number;
  33.  
  34.     // Go from the beginning to the end of the number list.
  35.     for (size_t i = 0; i < number_list.size(); ++i)
  36.     {
  37.         // Test the next number.
  38.         current_number = number_list[i];
  39.  
  40.         // If the number is even,
  41.         if (is_even(current_number))
  42.         {
  43.             // Add its index to the new list.
  44.             even_number_indices.push_back(i);
  45.         }
  46.     }
  47.  
  48.     return even_number_indices;
  49. }
  50.  
  51. int main()
  52. {
  53.     // Create a list of numbers.
  54.     vector<int> numbers = { 1, 2, 3, 12, 24, 14, 19, 30 };
  55.  
  56.     // Get a list of the even numbers.
  57.     vector<int> even_numbers = get_even_numbers(numbers);
  58.  
  59.     // Display the even numbers.
  60.     for (size_t i = 0; i < even_numbers.size(); ++i)
  61.     {
  62.         cout << even_numbers[i] << endl;
  63.     }
  64.  
  65.     return 0;
  66. }
  67.  
  68.  
  69.  
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement