user83869
user83869

Reputation: 35

How to print desired amount of elements in an array?

If I want to print a single dimensional array with n number of elements. Can I initialize the array as array[n] ?

#include "pch.h"
#include <iostream>

using namespace std;

int main()
{
    int n;

    std::cout << "Please enter the number of elements (n): ";
    std::cin >> n;

    int array[n];

    for (int i = 0; i <= n; i++) {
        std::cin >> array[n];
    }
    return 0; 
}

Upvotes: 0

Views: 363

Answers (2)

francesco
francesco

Reputation: 7539

In C++ you cannot initialize an array with a variable length. Either you:

  • dynamically allocate memory

    int *array = new int[n];

    in which case you should not forget to deallocate later with

    delete[] array;

  • Or you can use a std::vector

    std::vector<int> array(n);

    which will be deallocated when it exits the scope.

Additional mistakes are:

  • The for loop should be like

    for (int i = 0; i < n; i++)

    because with n elements the array indexes go from 0 to n - 1.

  • To read the input you can simply use

    std::cin >> array[n]

    The code you wrote with a combination of >> and << cannot work.

Upvotes: 1

Swordfish
Swordfish

Reputation: 13134

As C++ does not support Variable Length Arrays (VLAs) contrary to C99, you'll have to use some other means of allocating memory of arbitrary size in C++ like std::vector:

#include <iostream>

int main()
{
    int n;

    std::cout << "Please enter the number of elements (n): ";
    std::cin >> n;

    std::vector<int> foo(n);

                    // valid indexes range form 0 to size - 1: < n instead of <= n
    for (int i = 0; i < n; ++i)
        std::cin >> foo[i];
}

Also you mixed up i and n in your for-loop.

std::cin >> array[n] << " ";
                     ^^^^^^

won't work either.

Upvotes: 2

Related Questions