Advertisement
avr39ripe

SBUFirstLastNegElemInArray

Jun 20th, 2020
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5.     const int arrSize{ 10 };
  6.     int arr[arrSize]{ 1,3,4,-2,6,-3,8,-9,7,0 };
  7.     //int arr[arrSize]{ 1,3,4,2,6,3,8,9,7,0 };
  8.  
  9.     int firstNegIdx{ -1 };
  10.     int lastNegIdx{ -1 };
  11.     int prod{ 1 };
  12.  
  13.     for (int i{ 0 }; i < arrSize; ++i)
  14.     {
  15.         if ( arr[i] < 0 and (firstNegIdx == -1) ) { firstNegIdx = i; };
  16.         if ( arr[i] < 0 ) { lastNegIdx = i; };
  17.     }
  18.  
  19.     if (lastNegIdx >= 0)
  20.     {
  21.         std::cout << "Last negative elem index is: " << lastNegIdx <<
  22.             " and elem value is " << arr[lastNegIdx] << '\n';
  23.     }
  24.     else
  25.     {
  26.         std::cout << "There are no negative elements in this array!\n";
  27.     }
  28.    
  29.     if (firstNegIdx >= 0)
  30.     {
  31.         std::cout << "First negative elem index is: " << firstNegIdx <<
  32.             " and elem value is " << arr[firstNegIdx] << '\n';
  33.     }
  34.     else
  35.     {
  36.         std::cout << "There are no negative elements in this array!\n";
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement