Question
Write a program that uses a function to find the highest number in an array containing 5 numbers.
In the main()
, you must ask the user to enter 5 numbers and store these in the array.
Pass the array to a function and your function must find the highest number.
Return this number to your main()
and display it.
Further
This is all I have written so far. Stuck on the operation to determine the highest number within the function. Any help would be appreciated.
#include <stdio.h>
#include <math.h>
#define SIZE 5
//function signatures
int getHighestNumber(int[]);
//main function
int main()
{
//main variables
int array[SIZE];
int highest_number;
int i;
printf("\nPlease enter 5 numbers into an array.\n");
for (i = 0; i < SIZE; i )
{
scanf("%d", &array[i]);
}
int getHighestNumber(int array[SIZE]);
return 0;
}
int getHighestNumber(int array[])
{
//function variables
int highest_number;
int i;
for (i = 0; i < SIZE; i )
{
if (array[i] > highest_number)
{
highest_number = array[i];
}
}
return highest_number;
}
CodePudding user response:
For starters this line
int getHighestNumber(int array[SIZE]);
is not a function call. It is a function declaration.
You need to write
highest_number = getHighestNumber( array );
The function itself should be declared at least like
int getHighestNumber( const int[]);
Within the function the variable highest_number
was not initialized. So the function invokes undefined behavior. The function can be defined the following way
int getHighestNumber( const int array[])
{
//function variables
int highest_number = array[0];
for ( int i = 1; i < SIZE; i )
{
if (array[i] > highest_number)
{
highest_number = array[i];
}
}
return highest_number;
}
Or for a documentation purpose you could declare the function parameter like
int getHighestNumber( const int array[SIZE])
{
//...
}
CodePudding user response:
Another way to get max without loop using recursion :
#include <stdio.h>
#define SIZE 5
//function signatures
int getHighestNumber(int[],int);
//main function
int main()
{
// main variables
int array[SIZE];
int highest_number;
int i;
printf("\nPlease enter 5 numbers into an array.\n");
for (i = 0; i < SIZE; i )
{
scanf("%d", &array[i]);
}
int max = getHighestNumber(array,SIZE);
printf("%d\n",max);
return 0;
}
int getHighestNumber(int array[], int size)
{
// if size of array is 1 the max is the only
// of the array
if (size == 1) return array[0];
// else max is the max between first element and the next element
int max = getHighestNumber(&array[1],size-1);
if (max > array[0])
return max;
return array[0];
}