Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning the value of a specific array[index] – C

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading