Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrange given numbers in ascending order

Tags:

arrays

c

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?

like image 263
Jaskaranbir Singh Avatar asked Apr 15 '15 18:04

Jaskaranbir Singh


People also ask

How do you arrange numbers in ascending order?

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.

What are the following numbers in ascending order 847 9754 8320 571?

Ascending order:571, 847, 8320, 9754. Was this answer helpful?

What is the ascending number?

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.


1 Answers

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.

like image 75
Sourav Ghosh Avatar answered Sep 21 '22 01:09

Sourav Ghosh