Problem Statement:
Write a function that returns the number of negative numbers in an array.
Approach:
- Initialize a counter to 0.
- Loop through the array.
- If the element is less than 0, increment the counter.
- Return the final count after the loop ends.
Example:
Input: arr = [2, -6, 4, 8, 1, -9]
Output: 2
Time & Space Complexity:
Time Complexity: O(n) — where n is the number of elements in the array.
Space Complexity: O(1) — Only a counter variable is used.
Visualisation:
function countNegativeNumbers(arr) {
let count = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] < 0) {
count++;
}
}
return count;
}
let arr = [2, -6, 4, 8, 1, -9];
let result = countNegativeNumbers(arr);
console.log("Result:", result); // Output: 2
def count_negative_numbers(arr):
count = 0
for num in arr:
if num < 0:
count += 1
return count
arr = [2, -6, 4, 8, 1, -9]
result = count_negative_numbers(arr)
print("Result:", result) # Output: 2
public class Main {
public static int countNegativeNumbers(int[] arr) {
int count = 0;
for (int num : arr) {
if (num < 0) count++;
}
return count;
}
public static void main(String[] args) {
int[] arr = {2, -6, 4, 8, 1, -9};
int result = countNegativeNumbers(arr);
System.out.println("Result: " + result); // Output: 2
}
}
#include <iostream>
using namespace std;
int countNegativeNumbers(int arr[], int n) {
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] < 0) count++;
}
return count;
}
int main() {
int arr[] = {2, -6, 4, 8, 1, -9};
int result = countNegativeNumbers(arr, 6);
cout << "Result: " << result << endl; // Output: 2
return 0;
}
#include <stdio.h>
int countNegativeNumbers(int arr[], int n) {
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] < 0) count++;
}
return count;
}
int main() {
int arr[] = {2, -6, 4, 8, 1, -9};
int result = countNegativeNumbers(arr, 6);
printf("Result: %d\n", result); // Output: 2
return 0;
}
using System;
class Program
{
static int CountNegativeNumbers(int[] arr)
{
int count = 0;
foreach (int num in arr)
{
if (num < 0)
{
count++;
}
}
return count;
}
static void Main()
{
int[] array = { 3, -1, 0, -4, 5, -6 };
int result = CountNegativeNumbers(array);
Console.WriteLine("Number of negative elements: " + result);
}
}
