I hope you can help. I am trying to write a program that ‘given a list(array) of 10 integers, find the one with the smallest absolute value and swap its position with the last one and output the new list.
Here’s what I have coded but its not swaping..
#include stdio.h
#include math.h
int main() {
int array[10];
int arraynew[10];
int absmallest = 0;
int index = 0;
int i;
for (i = 0; i < 10; i++) {
scanf("%d", &array[i]);
}
absmallest = array[0];
for (i = 0; i < 10; i++) {
if (abs(array[i]) < absmallest)
absmallest = array[i];
index = i;
}
int temp;
temp = array[9];
array[9] = array[index];
array[index] = temp;
for (i = 0; i < 10; i++) {
printf("%d", array[i]);
}
}
You need to update your
indexinside theif-statement.should be
Otherwise, you update your
indexon each loop.EDIT: As @amit noted, you also need to store the absolute value, not the real one. In other words
should be
And the same for the initialization of
absmallest