-2

I tried to fill up an array with 'n' numbers, but i got stuck. So here is my code:

#include <iostream>

using namespace std;

int main(){
    int n;
    cin>>n;
    int arr[n]={};

    for (int i = 0;i <= n; i++) {
        for(int k = 1; k <= n; k++) {
            cout << arr[i] = k;
        }
    }
    return 0;

}

So if u will input 3, it will output 1,2,3; In my code I tried to make a loop, that does the filling up array starting from 0 to n,and fill up with numbers from 1 to n. Help me pls!

WhozCraig
  • 65,258
  • 11
  • 75
  • 141
  • 1
    `int arr[n]` is not valid C++ (VLA extension), use `std::vector` instead. – Jarod42 Nov 15 '19 at 09:38
  • 4
    You need only one loop. – Jarod42 Nov 15 '19 at 09:40
  • 1
    And avoid complex expressions such as `cout << arr[i] = k`. – Jarod42 Nov 15 '19 at 09:41
  • [`std::iota`](https://en.cppreference.com/w/cpp/algorithm/iota) might help. – Jarod42 Nov 15 '19 at 09:42
  • 1
    [`std::vector arr(n);`](https://en.cppreference.com/w/cpp/container/vector) then [`std::iota(arr.begin(), arr.end(), 1);`](https://en.cppreference.com/w/cpp/algorithm/iota) - done. – WhozCraig Nov 15 '19 at 09:44
  • You really ought to avoid `using namespace std` - it is a bad habit to get into, and [can silently change the meaning of your program](/q/1452721) when you're not expecting it. Get used to using the namespace prefix (`std` is intentionally very short), or importing *just the names you need* into the *smallest reasonable scope*. – Toby Speight Nov 15 '19 at 14:12

3 Answers3

0

You should make it like this:

int main()
{
    int n = 0;
    cin>>n;
    int* arr =  new int[n];

    for (int i = 0;i < n; i++) //only `<` not `<=`
    {
        cout << arr[i] = i+1;
    }

    delete[] arr ;
    return 0;
}

Or you can use std::vector.

Raffallo
  • 651
  • 8
  • 19
0

You can try this method to complete your code

  • You don't need two for loops one is enough.

method(array start from 0 to n)

int k = 1;
for (int i = 0 ; i < n ; i++) { //i = 0 and i < n
       arr[i] = k;
       cout << arr[i];
       k++;
}

Hope this will fulfill your question

Kalana
  • 5,631
  • 7
  • 30
  • 51
  • I have corrected it. when I run that part it didn't give me any error and output is also correct – Kalana Nov 15 '19 at 13:40
0

If you want to use the standard algorithms you can use std::iota(first, last, value) which fills the range [first, last) with sequentially increasing values, starting with the given value then incrementing by one each time. Then use std::for_each(first, last, function) to print the vector out. For the function, you can use a lambda function

#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

int main()
{
  int n;
  std::cin >> n;
  std::vector<int> arr(n);
  std::iota(arr.begin(), arr.end(), 1);

  std::for_each(arr.begin(), arr.end(), [](int elem) -> void {
    std::cout << elem << std::endl
  });

  return EXIT_SUCCESS;
}
Philip Nelson
  • 1,027
  • 12
  • 28