Search code examples
csum

Sum of positive numbers is a negative number


So this code is supposed to find the minimum_sum and maximum_sum (sum of [arr_elemnts-1] numbers) values of a sorted array of positive numbers (exemple arr=[5,4,3,2,1] gives min_sum=1+2+3+4=10 max_sum=5+4+3+2=14)

it works fine for most cases, but when I input the elements of the array as 140537896 243908675 670291834 923018467 520718469 instead of returning min=1575456874 max=2357937445 it returns min=1575456874 max=-1937029851 (I am a beginner, any idea what I did wrong ?)

#include <stdio.h>

int sort(int n, long int arr[n])
{
    int aux;

    for (int i = 0; i < n - 1; i++)
    {
        for (int j = 0; j < n - 1; j++)
        {
            if (arr[j + 1] < arr[j])
            {
                aux = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = aux;
            }
        }
    }
    return 0;
}

void sum(int n, long int arr[n])
{
    long int min_sum = 0;
    long int max_sum = 0;
    for (int i = 0; i < n - 1; i++)
    {
        min_sum = min_sum + arr[i];
    }
    printf("min sum is : %ld \n", min_sum);
    for (int i = n - 1; i > 0; i--)
    {
        max_sum = max_sum + arr[i];
    }
    printf("max sum is : %ld",max_sum);
}

int main()
{
    int n;
    printf("----MIN MAX---- \n");
    do {
        printf("Enter n : ");
        scanf("%d", &n);
    } while (n <= 0);
    long int arr[n];
    for (int i = 0; i < n; i++)
    {
        printf("Enter arr[%d]: ", i);
        scanf("%ld", &arr[i]);
    }
    sort(n, arr);
    sum(n, arr);
}

Solution

  • Usually, long ints are limited to 32 bits (maximum 2,147,483,647).

    You could maybe try a long long int instead, which is 64 bits (maximum 9,223,372,036,854,775,807).

    I'm not very familiar with c, but to expand on why the sum of big number would be negative, it is possible that when adding them together, some bits get ignored or replaced and become negative. You could try adding 1 to a 32 bit 2,147,483,647 to see what happens.

    See Integer overflow on wikipedia