avr39ripe

cppArrShiftNonZero

Jul 12th, 2021
867
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3.  
  4. int main()
  5. {
  6.     const int arrSize{ 10 };
  7.     int arr[arrSize]{1,2,0,0,5,0,7,0,9,0};
  8.     //int arr[arrSize]{ 1,2,3,4,5,6,7,8,9,10 };
  9.     //1,2,5,7,9,-1,-1,-1,-1,-1
  10.  
  11.     int insertPos{ 0 };
  12.     for (; arr[insertPos] != 0; ++insertPos);
  13.  
  14.     if (insertPos < arrSize)
  15.     {
  16.         //std::cout << "Found first zero index " << insertPos << '\n';
  17.         for (int testPos{ insertPos + 1 }; testPos < arrSize; ++testPos)
  18.         {
  19.             if (arr[testPos] != 0)
  20.             {
  21.                 arr[insertPos++] = arr[testPos];
  22.             }
  23.         }
  24.  
  25.         //for (; insertPos < arrSize; ++insertPos)
  26.         //{
  27.         //  arr[insertPos] = -1;
  28.         //}
  29.         for (; insertPos < arrSize; arr[insertPos++] = -1);
  30.     }
  31.     else
  32.     {
  33.         std::cout << "No ZEROES!!\n";
  34.     }
  35.  
  36.     for (int i{ 0 }; i < arrSize; ++i) { std::cout << arr[i] << '\t'; } std::cout << '\n';
  37.  
  38.     return 0;
  39. }
RAW Paste Data