Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

// C programming: my output is incorrect. does not match with the expected value

ID: 3861366 • Letter: #

Question

// C programming: my output is incorrect. does not match with the expected value.

/*
Compute the positions of the minimum and maximum of an array,
and place the results into the locations pointed at by min and max.
If there is more than one minimal or maximal position, report the
first one. If the array is empty, do nothing.
*/
void minmax(int a[], int len, int *minpos, int *maxpos)
{
     
     *minpos=*maxpos=a[0];

     for(int i=1; i<len; i++)
     {
        if(*minpos > a[i])
         *minpos=a[i];
        else if(*maxpos<a[i])
         *maxpos=a[i];
     }
}

#include <stdio.h>

void minmax(int a[], int len, int* min, int* max);

int main() {
   int a[] = { 1, 4, -1, -1, 9, 9, -2, 14, -10 };
   int min = 42;
   int max = 1729;
   minmax(a, 0, &min, &max);
   printf("min max: %d %d ", min, max);
   printf("Expected: 42 1729 ");
   minmax(a, 6, &min, &max);
   printf("min max: %d %d ", min, max);
   printf("Expected: 2 4 ");
   minmax(a, 9, &min, &max);
   printf("min max: %d %d ", min, max);
   printf("Expected: 8 7 ");
   int b[] = { -1, -4, -9 };
   minmax(b, 3, &min, &max);
   printf("min max: %d %d ", min, max);
   printf("Expected: 2 0 ");
   return 0;
}

/*Output
min max: 1 1
Expected: 42 1729
min max: -1 9
Expected: 2 4
min max: -10 14
Expected: 8 7
min max: -9 -1
Expected: 2 0
*/

Explanation / Answer

void minmax(int a[], int len, int *minpos, int *maxpos)
{
     
     *minpos=*maxpos=a[0];

     for(int i=1; i<len; i++)
     {
        if(*minpos > a[i])
         *minpos=a[i];
        else if(*maxpos<a[i])
         *maxpos=a[i];
     }
}

#include <stdio.h>

void minmax(int a[], int len, int* min, int* max);

int main() {
   int a[] = { 1, 4, -1, -1, 9, 9, -2, 14, -10 };
   int min = 42;
   int max = 1729;
   minmax(a, 0, &min, &max);
   printf("min max: %d %d ", min, max);
   printf("Expected: 42 1729 ");
   minmax(a, 6, &min, &max);
   printf("min max: %d %d ", min, max);
   printf("Expected: 2 4 ");
   minmax(a, 9, &min, &max);
   printf("min max: %d %d ", min, max);
   printf("Expected: 8 7 ");
   int b[] = { -1, -4, -9 };
   minmax(b, 3, &min, &max);
   printf("min max: %d %d ", min, max);
   printf("Expected: 2 0 ");
   return 0;
}