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?
Ascending order is a method of arranging numbers from smallest value to largest value. The order goes from left to right. Ascending order is also sometimes named as increasing order. For example, a set of natural numbers are in ascending order, such as 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8… and so on.
Ascending order:571, 847, 8320, 9754. Was this answer helpful?
In maths, ascending order means the process of arranging numbers from smallest to largest from left to right. It can also mean arranging letters or words in alphabetical order from A to Z. Ascending means “going up”, so ascending order means that the numbers are going up.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With