Home > Net >  Incorrect result for the sum of the two lowest numbers in a sorted array
Incorrect result for the sum of the two lowest numbers in a sorted array

Time:02-16

I want to make a program in C that prints the sum of the two smallest numbers in a given array. The way I tried to solve it is: first, I sort the array with a "bubbleSort" function, and then I just add up the first and second elements in the sorted array (arr[0] arr[1]). It works fine with many other samples, but the array given in the code example below gives me a completely incorrect result; what is the reason for this? And, is this a correct solution for my program, or should I change my approach?

int main(){
   int arr[] = {2000000000, 2000000000, 2000000000, 2000000000, 2000000000}; //unsorted array
   int n = sizeof(arr)/sizeof(arr[0]);

   bubbleSort(arr, n); //Function to Bubble Sort the given array

   printf("Sorted array: \n"); 
   printArray(arr, n); //prints sorted array, which in this particular case is just the same the original

   int result = arr[0]   arr[1]; // result should be "4000000000"
   printf("Result: %i\n", result); //Result is "-294967296", which is clearly incorrect

   return 0;
}

CodePudding user response:

The answer you are getting is a garbage value. There's a integer overflow. So, use long int instead. Like this

long int arr[] = {2000000000, 2000000000, 2000000000, 2000000000, 2000000000};
  • Related