Gaarsin
Gaarsin

Reputation: 23

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);

Upvotes: 0

Views: 3217

Answers (2)

shamba
shamba

Reputation: 107

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);

Upvotes: 1

Farzad Salimi Jazi
Farzad Salimi Jazi

Reputation: 760

You mean like this !

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

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

Upvotes: 0

Related Questions