Parviz
Parviz

Reputation: 17

Creating a new array containing all the elements of the original array that are located before the first negative element

This is what I want: Based on the original array, create a new array containing all the elements of the original array that are located before the first negative element. Here is my code:

#include <iostream>
#include <ctime>
#include <cmath>
#include <iomanip>
#include <vector>

using namespace std;
int main() {

  const int N = 1000;
  int a[N];
  int k;
  bool f = false;
  vector<int> b;
  cout << "Input size of array: ";
  cin >> k;
  cout << "Input elements: ";
  for (int i = 0; i < k; i++) cin >> a[i];
  cout << endl;
  for (int i = 0; i < k; i++)
  {
    if (a[i] < 0 && !f)
    {
      f = true;
    }
    if (f) b.push_back(a[i]);
  }
  if (!f) cout << "No negative \n >> ";
  else for (int i = 0; i < b.size(); i++) cout << b[i] << " ";
  cin.get();
  return 0;
}

I output ARTER the first negative, but need BEFORE the first negative.

Upvotes: 0

Views: 59

Answers (1)

codermehraj
codermehraj

Reputation: 46

Here you are using f as a flag which is initially false. This means you didn't get any negative yet. When The f will be true then you can say that you got at least one negative number and as f is true you will not push any elements further.

So, You should push in the vector until you get at least 1 negative number. Which means you have to push only when the flag is false.

So your push statement should look like this:

if (!f) b.push_back(a[i]);

Upvotes: 1

Related Questions