0

Can somebody detect where is the problem in my code?

write a function with input and no output that takes an array of 5 integers and prints the possible minimum and maximum summation of 4 of its numbers #include <stdio.h> #include <stdlib.h> int h[]={8,2,5,1,4}; int i,max,p,x,z,min,l,f,s,q; int k; int m[4]; int n[4]; int size=sizeof(h)/sizeof(int); void j(int h[],int size); int main() { j(h,size); printf("The min sum = %d",max); printf("The max sum = %d",f); } void j(int h[],int size){     for (i=0;i<size;i++){                 for (p=i+1;p<size;p++){         if (h[i]>h[p]){             max=h[i];}     } for (k=0;k<size;k++){ if(h[k]<max){ m[k]=h[k];}} z=m[0]+m[1]+m[2]+m[3];           }           //////////////////              for (s=0;s<size;s++){                 for (q=i+1;q<size;q++){         if (h[s]>h[q]){             min=h[q];}        for (l=0;l<size;l++){           if(h[l]>min){             n[l]=h[l];           }}         f=n[0]+n[1]+n[2]+n[3];           } }     }

7th Sep 2018, 12:35 AM
Retag Tarek
Retag Tarek - avatar
1 Odpowiedź
+ 1
If you are allowed to sort the array it would be easier to find min & max sum. Here's an example for finding min & max sum using qsort function: Reference for qsort: https://en.cppreference.com/w/c/algorithm/qsort #include <stdio.h> #include <stdlib.h> int h[]={8,2,5,1,4}; // Comparison function for qsort int cmp(const void *a, const void *b) { return *(int*)a - *(int*)b; } int main() { int items = sizeof(h) / sizeof(int); int min_v = 0, max_v = 0; // Sort the array. qsort(h, items, sizeof(int), cmp); for(int i = 0; i < 4; ++i) { // sum min_v from h[0] - h[3] min_v += h[i]; // sum max_v from h[4] - h[1] max_v += h[4 - i]; } printf("The min sum = %d\n", min_v); printf("The max sum = %d", max_v); return 0; }
7th Sep 2018, 8:54 AM
Ipang