C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Sum of Positive and Negative Numbers in Array

C Program: Sum of Positive and Negative Numbers in Array

C

#include <stdio.h>

 

int main() {

    int arr[100], n, i;

    int positiveSum = 0, negativeSum = 0;

 

    // Input size of the array

    printf("Enter number of elements in the array: ");

    scanf("%d", &n);

 

    // Input array elements

    printf("Enter %d elements:\n", n);

    for (i = 0; i < n; i++) {

        scanf("%d", &arr[i]);

    }

 

    // Calculate sum of positive and negative numbers

    for (i = 0; i < n; i++) {

        if (arr[i] > 0)

            positiveSum += arr[i];

        else if (arr[i] < 0)

            negativeSum += arr[i];

    }

 

    // Display results

    printf("\nSum of positive numbers: %d", positiveSum);

    printf("\nSum of negative numbers: %d\n", negativeSum);

 

    return 0;

}

Output

 
INPUT :
Enter number of elements in the array: 6
Enter 6 elements:
5 -2 7 -9 4 -3

OUTPUT :
Sum of positive numbers: 16
Sum of negative numbers: -14

Explanation

  1. The program takes the size of the array and its elements as input.
  2. It loops through each element:
    • If the element is greater than 0 → add to positiveSum.
    • If less than 0 → add to negativeSum.
  3. Both sums are displayed separately.