Jorge Ldg Jorge Ldg - 8 months ago 56
C Question

Variable scope in a nested for loop in c (cs50)

In this code, where I'm applying a selection sort, why can't I use the variable i at the line that has the comment? Thanks

void sort(int values[], int n)
for (int i = 0; i < (n-2); i++){
int iSmallest = i;
for(int j = i + 1; j < (n-1); j++){
if(values[j] < values[iSmallest])/*Why can't I use values[i] instead of values[iSmallest]?*/
iSmallest = j;

int temp = values[i];
values[i] = values[iSmallest];
values[iSmallest] = temp;


In the inner loop, you need to keep track of the index of the smallest element you've found so far.

At the start of the inner loop, you take the index of the first element you look at, i.e. i, and initialize iSmallest with that. When you find an element after that one which is smaller, you update iSmallest to the index of that element.

Then when you finish the inner loop, you use that index to swap the smallest element with the element at i. That puts the smallest element at index i. Then you increment i and repeat, finding the next smallest element.

The variable i is not out of scope in the line you commented on. It's syntactically legal to have if(values[j] < values[i]) at that line, but the sort won't work properly.