Wednesday, July 3, 2024
HomeLanguagesJavascriptJavaScript program to count positive and negative numbers in an array

JavaScript program to count positive and negative numbers in an array

Given an array of numbers. Write a JavaScript program to find positive and negative numbers in an array.

Example:

Input:   numbers_array1= [10,20, -1,22,99,20, -9]
Output: positive no’s=5, negative no’s =2

Input:   numbers_array2= [-121, – 78, -13, 54, -23]
Output:  positive no’s=1, negative no’s=4

Example 1: This code count positive and negative numbers from the given array using JavaScript for loop. Iterate each element in the list using for loop and check if (num >= 0), the condition to check negative numbers. If the condition satisfies, then increase negative count else increase the positive count

Javascript




<script>   
    var numbers=[10,-12,89,56,-83,8,90,-8]
    var pos_count=neg_count=0
    for(let i=0;i<numbers.length;i++)
    {
      if (numbers[i]<0)
       neg_count++;
      else
       pos_count++;
    }
    console.log(`The positive numbers in an array is ${pos_count}`)
    console.log(`The negative numbers in an array is ${neg_count}`)
</script>


Output

The positive numbers in an array is 5
The negative numbers in an array is 3

Example 2: The following code uses JavaScript while loop.

Javascript




<script>  
    var numbers=[7,-8,55,-87,28,74,-21,54,4]
    var pos_count=neg_count=i=0
    while(i<numbers.length)
    {
      if (numbers[i]<0)
       neg_count++;
      else
       pos_count++;
      i++;
    }
    console.log(`The positive numbers in an array is ${pos_count}`)
    console.log(`The negative numbers in an array is ${neg_count}`)
</script>


Output

The positive numbers in an array is 6
The negative numbers in an array is 3

Example 3: The following code uses JavaScript using forEach Loop 

Javascript




var numbers=[-8,10,23,44,-80,-15,-13,-1]
var pos_count=neg_count=0
numbers.forEach(element => {
  if (element<0)
   neg_count++;
  else
   pos_count++;
});
console.log(`The positive numbers in an array is ${pos_count}`)
console.log(`The negative numbers in an array is ${neg_count}`)


Output

The positive numbers in an array is 3
The negative numbers in an array is 5

Example 4:Using map method

Javascript




var numbers=[10,-12,89,56,-83,8,90,-8]
var pos_count=neg_count=0
numbers.map(function(element)
{
  if (element<0)
   neg_count++;
  else
   pos_count++;
});
console.log(`The positive numbers in an array is ${pos_count}`)
console.log(`The negative numbers in an array is ${neg_count}`)


Output

The positive numbers in an array is 5
The negative numbers in an array is 3

Example 5:Using Recursion

Javascript




function countNumbers(numbers, index, pos_count, neg_count) {
    if (index < numbers.length) {
        if (numbers[index] < 0) {
            neg_count++;
        } else {
            pos_count++;
        }
        return countNumbers(numbers, index + 1, pos_count, neg_count);
    } else {
        return { pos_count, neg_count };
    }
}
 
var numbers=[-8,10,23,44,-80,-15,-1]
var counts = countNumbers(numbers, 0, 0, 0);
console.log(`The positive numbers in an array is ${counts.pos_count}`)
console.log(`The negative numbers in an array is ${counts.neg_count}`)


Output

The positive numbers in an array is 3
The negative numbers in an array is 4

Efficient Code:-

This code is more efficient because it eliminates the need for recursion and the function calls that come with it, and instead uses a simple for loop to iterate through the array. This should result in faster execution and less memory usage.

Javascript




function countNumbers(numbers) {
    let pos_count = 0;
    let neg_count = 0;
 
    for (let i = 0; i < numbers.length; i++) {
        if (numbers[i] < 0) {
            neg_count++;
        } else {
            pos_count++;
        }
    }
    return { pos_count, neg_count };
}
 
var numbers = [-8, 10, 23, 44, -80, -15, -1]
              var counts = countNumbers(numbers);
console.log(`The positive numbers in an array is $ {counts.pos_count}`)
console.log(`The negative numbers in an array is $ {counts.neg_count}`)


C++




#include <iostream>
using namespace std;
 
struct Counts {
    int pos_count;
    int neg_count;
};
 
Counts countNumbers(int numbers[], int size) {
    Counts counts = {0, 0};
    for (int i = 0; i < size; i++) {
        if (numbers[i] < 0) {
            counts.neg_count++;
        } else {
            counts.pos_count++;
        }
    }
    return counts;
}
 
int main() {
    int numbers[] = {-8, 10, 23, 44, -80, -15, -1};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    Counts counts = countNumbers(numbers, size);
    cout << "The positive numbers in an array is " << counts.pos_count << endl;
    cout << "The negative numbers in an array is " << counts.neg_count << endl;
    return 0;
}


Java




class Main {
    static class Counts {
        int pos_count;
        int neg_count;
    }
 
    static Counts countNumbers(int[] numbers) {
        Counts counts = new Counts();
        counts.pos_count = 0;
        counts.neg_count = 0;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] < 0) {
                counts.neg_count++;
            } else {
                counts.pos_count++;
            }
        }
        return counts;
    }
 
    public static void main(String[] args) {
        int[] numbers = {-8, 10, 23, 44, -80, -15, -1};
        Counts counts = countNumbers(numbers);
        System.out.println("The positive numbers in an array is " + counts.pos_count);
        System.out.println("The negative numbers in an array is " + counts.neg_count);
    }
}


C#




using System;
 
class MainClass {
    struct Counts {
        public int pos_count;
        public int neg_count;
    }
    public static Counts countNumbers(int[] numbers) {
        Counts counts = new Counts { pos_count = 0, neg_count = 0 };
        for (int i = 0; i < numbers.Length; i++) {
            if (numbers[i] < 0) {
                counts.neg_count++;
            } else {
                counts.pos_count++;
            }
        }
        return counts;
    }
    public static void Main(string[] args) {
        int[] numbers = new int[] {-8, 10, 23, 44, -80, -15, -1};
        Counts counts = countNumbers(numbers);
        Console.WriteLine("The positive numbers in an array is " + counts.pos_count);
        Console.WriteLine("The negative numbers in an array is " + counts.neg_count);
    }
}


Output

The positive numbers in an array is $ {counts.pos_count}
The negative numbers in an array is $ {counts.neg_count}

Example 7:  using the Array.prototype.filter() method to filter out positive and negative numbers

Javascript




// defining the array of numbers
var numbers=[-8,10,23,44,-80,-15,-13,-1]
 
// creating a new array containing only positive numbers using filter method
var positiveNumbers = numbers.filter(function(number) {
  // return only numbers greater than or equal to 0
  return number >= 0;
});
 
// creating a new array containing only negative numbers using filter method
var negativeNumbers = numbers.filter(function(number) {
  // return only numbers less than 0
  return number < 0;
});
 
// printing the count of positive numbers in the array
console.log(`The positive numbers in an array is ${positiveNumbers.length}`)
 
// printing the count of negative numbers in the array
console.log(`The negative numbers in an array is ${negativeNumbers.length}`)


Output

The positive numbers in an array is 3
The negative numbers in an array is 5

Time complexity: O(n)
Auxiliary Space: O(n) 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments