This post will discuss how to initialize an integer array with the range 1 to n in C++.

1. Using std::iota

The std::iota function can be used to assign successive values to every element in the specified range. For example, the following solution fills an integer array with consecutive values starting from 1.

Download  Run Code

Output:

1 2 3 4 5 6 7 8 9 10

 
Before C++ 11, do like:

Download  Run Code

Output:

1 2 3 4 5 6 7 8 9 10

 
If you’re using std::array, the usage remains similar:

Download  Run Code

Output:

1 2 3 4 5 6 7 8 9 10

2. Using std::generate_n

Alternatively, you can use the std::generate_n function to generate consecutive values with successive calls to a generator function and assign them to an array. A typical implementation of this approach would look like:

Download  Run Code

Output:

1 2 3 4 5 6 7 8 9 10

 
The usage remains similar for std::array with class.

Download  Run Code

Output:

1 2 3 4 5 6 7 8 9 10

3. Using for loop

Finally, you can use a regular for loop to fill the array with consecutive numbers, as shown below:

Download  Run Code

Output:

1 2 3 4 5 6 7 8 9 10

That’s all about initializing an integer array with the range 1 to n in C++.