Don't miss your Year-End Offer: Up to 20% OFF

Sum of Positive Numbers in Java Array

13 February 2024
public class HackerAlgo {

    // Sum of Positive Numbers
    public static int sumOfPositiveNumbers(int[] arr) {
        int sum = 0;

        // Traverse the array and add positive numbers to the sum
        for (int num :arr) {
            if (num> 0) {
                sum += num;
            }
        }

        return sum;
    }

    public static void main(String[] args) {
        // Example for Sum of Positive Numbers
int[] arr1 = {10, -5, 20, -3, 7};
System.out.println("Sum of positive numbers: " + sumOfPositiveNumbers(arr1));

int[] arr2 = {-8, -12, -5, -2};
System.out.println("Sum of positive numbers: " + sumOfPositiveNumbers(arr2));
# Sum of Positive Numbers
def sum_of_positive_numbers(arr):
    # Sum of positive numbers
    return sum(num for num in arr if num> 0)

# Example usage
arr1 = [10, -5, 20, -3, 7]
print("Sum of positive numbers:", sum_of_positive_numbers(arr1))

arr2 = [-8, -12, -5, -2]
print("Sum of positive numbers:", sum_of_positive_numbers(arr2))
#include <iostream>
#include <vector>

class HackerAlgo {
public:
    // Sum of Positive Numbers
    static int sumOfPositiveNumbers(const std::vector<int>&arr) {
        int sum = 0;

        // Traverse the array and add positive numbers to the sum
        for (int num :arr) {
            if (num> 0) {
                sum += num;
            }
        }

        return sum;
    }
};

int main() {
    // Example for Sum of Positive Numbers
std::vector<int> arr1 = {10, -5, 20, -3, 7};
std::cout<< "Sum of positive numbers: " << HackerAlgo::sumOfPositiveNumbers(arr1) << std::endl;

std::vector<int> arr2 = {-8, -12, -5, -2};
std::cout<< "Sum of positive numbers: " << HackerAlgo::sumOfPositiveNumbers(arr2) << std::endl;

    return 0;
}
class HackerAlgo {
    // Sum of Positive Numbers
    static sumOfPositiveNumbers(arr) {
        // Sum of positive numbers
        return arr.reduce((sum, num) =>num> 0 ? sum + num : sum, 0);
    }
}

// Example usage
const arr1 = [10, -5, 20, -3, 7];
console.log("Sum of positive numbers:", HackerAlgo.sumOfPositiveNumbers(arr1));

const arr2 = [-8, -12, -5, -2];
console.log("Sum of positive numbers:", HackerAlgo.sumOfPositiveNumbers(arr2));

Leave a Comment