I am very new to the C programming language, and I have, again, found myself in a bit of a predicament.
I need to find the largest and smallest values (and their respective indeces) in an array that generates random numbers. I was able to display the values on the screen but not their specific indexes. How should I proceed to have it work.
Here are my attempts:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
#define MIN 100
#define MAX 990
int main(void) {
int index;
float array[SIZE];
float largestValue, smallestValue;
srand(time(NULL));
for (index = 0; index < SIZE; index++) {
array[index] = (rand() % (MAX - MIN + 1) + MIN) / 10.0;
printf("Index [%i]: %.1f\n", index, array[index]);
}
maiorValor = array[0];
smallestValue = array[0];
for (index = 0; index < SIZE; index++){
if (array[index] > largestValue)
largestValue = array[index];
if (array[index] < smallestValue)
smallestValue = array[index];
}
/*
printf("This is the smallest value: [%i] %.1f\n", index, smallestValue);
printf("This is the largest value: [%i] %.1f\n", index, largestValue);
OR
printf("This is the smallest value: [%f] %.1f\n", array[smallestValue], smallestValue);
printf("This is the largest value: [%f] %.1f\n", array[largestValue], largestValue);
*/
return 0;
}
>Solution :
If you need to know the indices, then simply save them along with the largest and smallest values you’re already finding.
For instance:
int index;
float array[SIZE];
float largestValue, smallestValue;
int largestIndex, smallestIndex;
Then when searching for the largest and smallest values:
largestValue = array[0];
largestIndex = 0;
smallestValue = array[0];
smallestIndex = 0;
for (index = 1; index < SIZE; index++){ //You can start at index 1 instead of 0
if (array[index] > largestValue){
largestValue = array[index];
largestIndex = index;
}
if (array[index] < smallestValue){
smallestValue = array[index];
smallestIndex = index;
}
}