Reputation: 2034
I've just started learning C, and today I was given a question in which one of the parts was to accept the array of numbers from user and arrange them in ascending order. The array size was also to be specified by user. I used the following code for this purpose->
for (i = 0; i <= y - 1; ++i) {
for (ii = i + 1; ii <= y - 1; ++ii) {
if (x[i] > x[ii]) {
temp = x[i];
x[i] = x[ii];
x[ii] = temp;
}
}
}
int k;
printf("\nNumbers arranged in ascending order:\n");
for (k = 0; k < y; ++k) {
printf("%d\n", x[i]);
}
Here, variable y is the size of array, x is name of array variable (So the variable defining goes like this-> int x[y];
But the problem is, it just prints out the final value of array. To elaborate problem:
Suppose I entered 3 as my array size. Then program asks me for 3 numbers which I chose 34,45,22.
Now after this whole code is executed, it displays x[3] (now x[3] doesn't even exist! Since x[2] is final value in array. So it gives me memory location of variable.)
Where am I going wrong?
Upvotes: 5
Views: 1013
Reputation: 892
In your last for loop, you are doing
printf("\nNumbers arranged in ascending order:\n");
for (k = 0; k < y; ++k) {
printf("%d\n", x[i]);
}
but you print x[i]
, but do not increment i
. Remember, i
and k
are just array variables, not the actual VALUES in the array. Just change the printf
to printf("%d\n", x[k]);
and it should work fine.
Upvotes: 0
Reputation: 134316
You need to change
printf("%d\n", x[i]);
to
printf("%d\n", x[k]);
in the printing loop as you're using k
as the loop counter variable.
Upvotes: 5