Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading