Gaarsin Gaarsin - 11 days ago 5
C Question

How to print the position of a value in an array in C

I'm using a for loop to search for the smallest value present within an array and printing that value out. I want to print out what position that value is in in the array (0-9), how would I do this?

int smallest = array[0];

for (counter = 0; counter < 10; counter++) {
if (smallest > array[counter]) {
smallest = array[counter];
}
}

printf("The smallest value stored within the array is %d", smallest);

Answer

You just need another variable (initialized "0") in which you store the value of "counter" each time the if condition is true like below:

int smallest = array[0];

int position = 0;

for (counter = 0; counter < 10; counter++) {
     if (smallest > array[counter]) {
       smallest = array[counter];
       position = counter;
  }
}

printf("The smallest value stored within the array is %d and position = %d", smallest, position);