Advertisement
avr39ripe

cppMinMaxProduct

May 27th, 2021
814
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5.     const int arrSize{ 10 };
  6.     int arr[arrSize]{ 5,2,4,1,6,7,8,3,4,1 };
  7.  
  8.     int minIdx{ 0 };
  9.     int maxIdx{ 0 };
  10.     int product{ 1 };
  11.  
  12.     for (int i{ 0 }; i < arrSize; ++i)
  13.     {
  14.         //std::cout << "arr[" << i << "] = " << arr[i] << '\n';
  15.         if (arr[i] < arr[minIdx])
  16.         {
  17.             //std::cout << "arr[minIdx] = arr[" << minIdx << "] = " << arr[minIdx] << '\n';
  18.             minIdx = i;
  19.             //std::cout << "Change minIdx to " << minIdx << '\n';
  20.         }
  21.         if (arr[i] > arr[maxIdx])
  22.         {
  23.             //std::cout << "arr[maxIdx] = arr[" << maxIdx << "] = " << arr[maxIdx] << '\n';
  24.             maxIdx = i;
  25.             //std::cout << "Change maxIdx to " << maxIdx << '\n';
  26.         }
  27.     }
  28.  
  29.     std::cout << "minIdx = " << minIdx << ' ' << " maxIdx = " << maxIdx << '\n';
  30.  
  31.     //if (minIdx < maxIdx)
  32.     //{
  33.     //  for (int i{ minIdx }; i < maxIdx; ++i)
  34.     //  {
  35.     //      product *= arr[i];
  36.     //  }
  37.     //}
  38.     //else if (minIdx > maxIdx)
  39.     //{
  40.     //  for (int i{ maxIdx+1 }; i < minIdx; ++i)
  41.     //  {
  42.     //      product *= arr[i];
  43.     //  }
  44.     //}
  45.    
  46.     int tmp{ 0 };
  47.     if (minIdx > maxIdx)
  48.     {
  49.         tmp = minIdx;
  50.         minIdx = maxIdx;
  51.         maxIdx = tmp;
  52.     }
  53.  
  54.     for (int i{ minIdx+1 }; i < maxIdx; ++i)
  55.     {
  56.         product *= arr[i];
  57.     }
  58.  
  59.     std::cout << "Product = " << product << '\n';
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement