Sort given numbers in ascending order

I was just starting to learn C, and today I was asked a question in which one of the parts was to take an array of numbers from the user and arrange them in ascending order. The size of the array must also be user-defined. For this, I used the following code β†’

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, the variable y is the size of the array, x is the name of the array variable (Thus, the definition of the variable looks like this β†’ int x[y]; But the problem is that it just prints the final value of the array. To develop the problem: Suppose I entered 3 as the size of the array. Then the program asks me the 3 numbers that I selected 34,45,22. Now, after executing all this code, it displays x [3] (now x [3] does not even exist! Since x [ 2] is the final value in the array, this gives me the location of the variable's memory). Where am I bayus?

+5
source share
2 answers

You need to change

  printf("%d\n", x[i]); 

to

 printf("%d\n", x[k]); 

in the print loop since you are using k as the loop counter variable.

+5
source

In the last for loop you do

  printf("\nNumbers arranged in ascending order:\n"); for (k = 0; k < y; ++k) { printf("%d\n", x[i]); } 

but you type x[i] but you don't increment i . Remember that i and k are just array variables, not real values ​​in the array. Just change printf to printf("%d\n", x[k]); and it should work fine.

0
source

All Articles