array program

using one dimension array,make and run a program that will allow a user to input 20 numbers and sort them to highest to lowest.
I recommend you reading tutorial on sorting from this site:

http://www.cplusplus.com/forum/articles/24830/

I hope it helps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# include <iostream>
using namespace std;

int main ()
{
    const int arraySize = 20;
    int array[arraySize];

    cout << "Enter 20 number " << endl;
    for(int i=0;i<arraySize;i++)
        cin >> array[i];

    for(int i=0;i<arraySize-1;i++)
    {
        for(int j=i;j<arraySize;j++)
        {
            if(array[i]<array[j])
            {
                int tmpVar = array[i];
                array[i] = array[j];
                array[j] = tmpVar;
            }
        }
    }

    for(int i=0;i<arraySize;i++)
    {
        cout << array[i] << endl;
    }

    return 0;
}


hope that helps
sort to highest to lowest...how to determine..
what , My program does not works for you?
I am not sure if I understand your problem it seem to me that you want to know how the program organize from the highest numbers to the lowest ones
am I right?
YES ..
@JHEN18: Could you, as an exercise, explain each line of Techno01's code? That should help you to learn.
well lets say that this program will input only 3 numbers by changing the arraySize from 20 to 3

int array[3];// means that we declare an array ,that can holds three number

1
2
3
cout << "Enter 20 number " << endl;
    for(int i=0;i<arraySize;i++)
        cin >> array[i];


here we ask the using to enter those three numbers for example the user enters 4,9 and 3;
those numbers now inside this array like this

array[0] = 4;
array[1] = 9;
array[2] = 3;

1
2
3
4
5
6
7
8
9
10
11
12
for(int i=0;i<arraySize-1;i++)
    {
        for(int j=i;j<arraySize;j++)
        {
            if(array[i]<array[j])
            {
                int tmpVar = array[i];
                array[i] = array[j];
                array[j] = tmpVar;
            }
        }
    }

This code is technic of sorting called bubble sort
The first for loop will goes from 0 to 1(because we have only 3 numbers remember)
this means that array[i] will take either 4 or 9;
the first for's period array[i] takes number 4 ,then compare it with 4,9 and 3
array[i]=4 < array[j]=4 skeeps the if statement
array[i]=4 < array[j]=9 this time the content of if statement will be excuted
array[i] exchange its value with array[j] mean that array[i] = 9 and array[j] = 4
array[i]=9 < array[j]=3 skeeps the if statement

the second for's period array[i]=4;
array[i]=4 < array[j]=4 skeeps the if statement
array[i]=4 < array[j]=3 skeeps the if statement

well now
array[0] = 9;
array[1] = 4;
array[2] = 3;

the last code just shows those number by order
1
2
3
4
 for(int i=0;i<arraySize;i++)
    {
        cout << array[i] << endl;
    }


hope I express well
Last edited on
Topic archived. No new replies allowed.