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?
source share