Extract negative numbers from array in C++

In this tutorial, we will learn how to extract negative numbers from an array.

An array can consist of positive as well as negative numbers. We will use the if-else statement to compare whether a number is positive or negative.

Extracting negative numbers from an array

We are given an array of numbers. Traverse the array using for loop and use the if-else statement to check whether the given number is less than zero or not. If the number is negative, print the given number.

Here is the code for extracting negative numbers from an array:

#include <iostream> 
using namespace std; 


int main() 
{ 
 int arr[] = { -3, 1, 2, 8, -7, 6, -9 };
 int n= sizeof(arr) / sizeof(arr[0]);
 cout<<"The negative elements in the given array are:"; 
 for(int i=0; i<n; i++) 
{ 
  if(arr[i] < 0) 
      { 
        cout<<arr[i]<<" ";
      } 
} 
return 0; 
}
Output:

The negative elements in the given array are:-3 -7 -9

In this tutorial, we learned how to find negative numbers from an array.

Leave a Reply

Your email address will not be published. Required fields are marked *