2

I am making a program, in which I need to iterate the numbers, starting from 1 to num then put the value of that array {1...num} to a variable that can be called in the for loop.

This is where I am at.

int main()
{
    int num = 0;
    cin >> num;

    for (int i = 1; i <= num; i++)
    {
        procnum[i];
    }
}

I need procnum[num] to have a value like ...

int procnum[num] = {1,2,3...num};
JeJo
  • 30,635
  • 6
  • 49
  • 88
Gian
  • 41
  • 3

3 Answers3

3

If you can use std::vector and std::iota, this is just two line code.

No need to for(index) loop the array. See live example here

#include <vector>   // std::vector
#include <numeric>  // std::iota

std::vector<int> procnum(some_size);
std::iota(procnum.begin(), procnum.end(), 1);
JeJo
  • 30,635
  • 6
  • 49
  • 88
2

In C++11, no need to even write a loop, unless you need to do error checking (e.g. check that reading input succeeded, or that the input value is valid).

#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm> 

int main()
{
     int size;
     std::cin >> size;

     std::vector<int> procnum(size);

     std::iota(procnum.begin(), procnum.end(), 1);    // starting value is 1

     //  output vector to demonstrate it is populated

     std::copy(procnum.begin(), procnum.end(), std::ostream_iterator<int>(std::cout," ");
     std::cout << "\n";
}

Before C++11, there was no algorithm std::iota(), but it is possible to use std::generate() and a simple functor to achieve the same effect.

Peter
  • 35,646
  • 4
  • 32
  • 74
  • *no need to even write a loop* : well *range based loops* are not that much bad to use. At least you sure about no out of bound UB happens, like in index-based iteration. – JeJo Feb 22 '19 at 10:57
  • @JeJo - I'm not suggesting loops are bad. Just that they are not needed in this case. There are also often benefits in using standard algorithms instead of writing loops to achieve the same effect. – Peter Feb 22 '19 at 11:06
1

you can use std::vector to create dynamic arrays:

#include <iostream>
#include <vector>

int main() {
    int size;
    std::cin >> size;

    std::vector<int> procnum(size);
    for (int i = 0; i < size; ++i) {
        procnum[i] = i + 1;
    }
}

you shouldn't use namespace std; - read here why.

Stack Danny
  • 7,754
  • 2
  • 26
  • 55
  • Using namespaces in source files is not a bad idea at all, as some answers clearly stated. However, the most upvoted answers could be miss-interpreted ... – user1810087 Feb 22 '19 at 10:43
  • for me personally I really like saying `std::` as it clearly says that I'm using some utility from the STL. Besides, this can be more time saving than not typing `std::` if that is someones arguing. – Stack Danny Feb 22 '19 at 11:38