I read Stephen Prath's "C language". Stopped on programming exercises (chapter 10):

Write a function that returns the largest value from an array of int values. Test this feature with a simple program.

That is, the function must take the array itself (int) in the arguments and return the largest value. What did I do:

#include<stdio.h> #define SIZE 7 int max(int*,int); int main(void){ int arr[SIZE] = {9,2,3,4,7,55,6}; printf("%d\n",max(arr,SIZE)); } int max(int *arr, int v){ int arr2[v]; int a,b,c; for(a=0;a<v;a++){ arr2[a]=arr[a]; } for(a=0;a<v;a++){ for(b=1;b<v;b++){ if(arr2[b]>arr2[b-1]){ c=arr2[b]; arr2[b]=arr2[b-1]; arr2[b-1]=c; } } } return arr2[0]; } 

I used a sorting algorithm (Nubian) and wrote it into another array in order not to change the old one. So the question is, how would it be more correct to solve this problem?

    3 answers 3

     #include<stdio.h> #define SIZE 7 int max(int*,int); int main(void){ int arr[SIZE] = {9,2,3,4,7,55,6}; printf("%d\n",max(arr,SIZE)); } int max(int *arr, int v){ int max = arr[0]; for(int i=1;i<v;i++){ if(max<arr[i]) max = arr[i]; } return max; } 

      MGM, take and find the maximum?

       int max = arr[0]; int i; for(i = 1; i < v; ++i) if(arr[i] > max) max = arr[i]; return max; 

        What a horror, well, you and pile up. The problem is nowhere easier.

         int ArrayMax(int* arr, int arrSize) { int retVal = INT_MIN; for (int i = 0; i < arrSize; ++i) { if (retVal < arr[i]) retVal = arr[i]; } return retVal; }