Sum of Positive Numbers in Java Array
Sum of Positive Numbers in Java Array
Description:
Given an array arr[] of integers, find and print the sum of all positive numbers in the array.
Example 1:
Input: arr = {10, -5, 20, -3, 7}
Output: Sum of positive numbers = 37
Explanation: The positive numbers in the array are 10, 20, and 7. Their sum is 37.
Example 2:
Input: arr = Array = {-8, -12, -5, -2}
Output: Sum of positive numbers = 0
Explanation: There are no positive numbers in the array, so the sum is 0.
Constraints:
The array length |arr| is at least 1 and at most 10^5.
Java Code:
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));
Python Code:
# 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))
C++ Code:
#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; }
JavaScript Code:
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));