Making an array from n to 1

In my code I want to make an array from n to 1, so that the n (and thus the size of the array) can vary. I would like to have a user input to determine the n. But the code I have written gives an error in when using A[n]. (When replacing n by a value, for example 3, it does actually work.) What is the problem that is causing my error for n?

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
#include<iostream>

using namespace std;

int main()
{
    int n;
    
    cout << "Enter lower bound (n):" << endl;
    cin >> n;
    
    int A[n];
    
    // Setting array values
    for (int i = 0; i < n; i++)
    {
        A[i] = n - i;
    }
    
    // Getting array values
    for (int i = 0; i < n; i++)
    {
        cout << A[i] << endl;
    }
    
    return 0;
    
}
The problem is that declaring a variable-length array on the stack is illegal in C++. The size of the array must be known at compile-time.

One solution is to use dynamic allocation to create the array.

A much, much better solution would be to use a std::vector.
Like so ...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
#include <numeric>      // for iota
using namespace std;

int main()
{
   int n;

   cout << "Enter n: ";   cin >> n;

   vector<int> A(n);
   iota( A.rbegin(), A.rend(), 1 );

   for ( int e : A ) cout << e << ' ';
   cout << '\n';
}


Enter n: 10
10 9 8 7 6 5 4 3 2 1
Here is your own code using vector instead of an array.

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
#include<iostream>
#include<vector>

using namespace std;

int main()
{
    int n;
    
    cout << "Enter lower bound (n):" << endl;
    cin >> n;
    
    vector<int> A;
    
    // Setting array values
    for (int i = 0; i < n; i++)
    {
        A.push_back(n - i);
    }
    
    // Getting array values
    for (int i = 0; i < n; i++)
    {
        cout << A[i] << endl;
    }
    
    return 0;
    
}


@lastchance
When you use that shorthand crap, its awesome but to a beginner it does not even look like c++ any more.
Topic archived. No new replies allowed.