Reputation: 19
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;
}
Upvotes: 0
Views: 158
Reputation: 979
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
Upvotes: 1