简体   繁体   中英

How to create an array to scale from 0 until user input

I am trying to create a program that prints out an array based on user input. The array needs to start from 0 and scale to the number enter by user. So if user inputs 5 the the array values will be [0][1][2][3][4][5]. For some reason my code just prints out 0.

#include <iostream>
using namespace std;

int main() {
cout << "Enter the value of n: ";
int n;
cin >> n;
int *arr1 = new int[n];

for(int i = 0; i < n; i ++){
    arr1[i] = 0;

}
cout << *arr1 << endl;

delete [] arr1;
return 0;
}

There are few bugs in your code.

You expect the output to be [0][1][2][3][4][5] when the n = 5. Therefore your output has (n + 1) elements. So your array should also have (n + 1) elements.

int *arr1 = new int[n + 1];

In your code you assign 0 to each element in your array. But you expect the array to contain 0, 1, 2, .., n

for(int i = 0; i < n + 1; i++){
  arr1[i] = i;
}

In your code, you only print the first element. *arr1 is same as arr1[0]. So another for loop is required to print the each element in your array.

for(int i = 0; i < n + 1; i++){
  cout << "[" << arr1[i] << "]" << endl;
}

Then you will get the output [0][1][2][3][4][5] when the n = 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM