How to sum the positive and negative elements of an array in C

1 Answer

0 votes
#include <stdio.h>

int main()
{
    int arr[] = { 3, 11, -4, 6, -8, -1, 9, 5, -2, -7, };
    int size = sizeof(arr) / sizeof(arr[0]);

    int pos_sum = 0, neg_sum = 0;

    for (int i = 0; i < size; i++) {
        if (arr[i] > 0)
            pos_sum = pos_sum + arr[i];
        if (arr[i] < 0)
            neg_sum = neg_sum + arr[i];
    }

    printf("Sum of positive elements = %d\n", pos_sum);
    printf("Sum of negative elements = %d", neg_sum);
 
    return 0;
}




/*
run:

Sum of positive elements = 34
Sum of negative elements = -22

*/

 



answered May 12, 2023 by avibootz
...