array help

can someone help me with this,the user suppose to input 5 number but the out come is long different numbers why?

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
 // Number Sorter
#include <iostream>


using namespace std;

char menu()
{
    char choice;
    cout<< "\nNumber Sorter - Created By Ben Tickle";
    cout<< "\n\n**************************************\n";
    cout<< "\n\n Please choose one of the following:\n";
    cout<< "\n\n 1 - Ascending order ";
    cout<< "\n 2 - Descending order ";
    cout<< "\n 3 - Exit";
    cout<< "\n\n\n**************************************\n";
    cout<< "\n\n Enter you choice and press return: ";
    cin >> choice;
    return choice;
}

int main()
{
    int a1,a2,a3,a4,a5;
    
    
    char choice;
    
    do
    {
        choice = menu();
        
        switch (choice)
        {
            case '1':
                cout << "\n\nAscending order"
                     << "\n\n\nPlease enter 5 numbers include spaces:";
                int a[5];
                cin >> a1; 
                cin >> a2; 
                cin >> a3; 
                cin >> a4; 
                cin >> a5; 

                for(int i=0;i<5;++i)
                cout<<a[i]<< ' '; 

                
                // Pause for user
                system("pause");
            break;             
            case '2':
                cout<< "\n\nDescending order"
                    << "\n\n\nPlease enter 5 numbers include spaces:";
                
                
                // Pause for user
                system("pause");
            break;
            case '3':
                cout<< "Exit"; 
                break;
            default:
                cout<< "\nNot a valid choice.";
        }
    } while (choice != '3');

    return 0;
} 
on line 46 the output is from the uninitialize/unused array a hence no valid numbers
so how can i change it?
38
39
40
41
42
43
                int a[5];
                cin >> a1; 
                cin >> a2; 
                cin >> a3; 
                cin >> a4; 
                cin >> a5; 

should be instead:
38
39
40
41
42
                cin >> a[0]; 
                cin >> a[1]; 
                cin >> a[2]; 
                cin >> a[3]; 
                cin >> a[4]; 

and delete line 24:
 
    int a1,a2,a3,a4,a5;

and replace it with
 
    int a[5];
Last edited on
thank you it shows the correct numbers now but does not ascend them?
Well, if you want the numbers in a different order, you have to sort them. Either write your own code to do that, or make use of the built-in std::sort.
http://www.cplusplus.com/reference/algorithm/sort/
Topic archived. No new replies allowed.