Im trying to write a function that prints out the index of the largest number in
ID: 3557932 • Letter: I
Question
Im trying to write a function that prints out the index of the largest number in an array of float numers. I then have to test it in the main function. For some reason nothing is printing out when i run it!
Heres what i have:
#include <stdio.h>
int find_index_of_max(float array[], int x);
int main()
{
float array[5];
array[0] = 1.6;
array[1] = 2.3;
array[2] = 2.2;
array[3] = 9.2;
array[4] = 8.5;
for (int i = 0; i < 5; i++)
{
printf("%d ", find_index_of_max(array, 5));
}
}
int find_index_of_max(float array[], int x)
{
int max, temp;
int index = 0;
temp = index;
max = array[index];
while(index < x)
if (max < array[index])
{
max = array[index];
temp = index;
}
index++;
return temp;
}
Explanation / Answer
// Im trying to write a function that prints out the index of the largest number in an array of float numers.
//I then have to test it in the main function. For some reason nothing is printing out when i run it!
#include <stdio.h>
int find_index_of_max(float array[], int x);
int main()
{
float array[5];
array[0] = 1.6;
array[1] = 2.3;
array[2] = 2.2;
array[3] = 9.2;
array[4] = 8.5;
printf("Largest Element located at index %d ", find_index_of_max(array, 5));
}
int find_index_of_max(float array[], int x)
{
int max, temp;
int index = 0;
temp = index;
max = array[index];
while(index < x) // here is bug.
{
if (max < array[index])
{
max = array[index];
temp = index;
}
index++;
}
return temp;
}