#include<iostream>
usingnamespace std;
int main()
{
int arr[100];
// Setting values
for (int i = 0; i < 100; i++)
{
arr[i] = i + 1;
}
// Getting values
for (int i = 0; i < 100; i++)
{
cout << arr[i] << endl;
}
return 0;
}
I want to modify this program now, so that it asks for user input. The input will be the upper bound in the range. In other words the lower bound will be fixed at 1 and the user will be able to tell the program to list all integers from 1 to 234, or any other number.
It's essentially a list I want. The length of the list will be defined by the user. I thought of something like this:
#include<iostream>
usingnamespace std;
int main()
{
int lowerBound = 1;
int upperBound;
cout << "Enter upper bound: " << endl;
cin >> upperBound;
int arr[upperBound];
// Setting array values
for (int i=0; lowerBound < upperBound; i++)
{
arr[i] = i+1;
lowerBound++;
}
// Getting array values
for (int i = 0; i < upperBound; i++)
{
cout << arr[i] << endl;
}
return 0;
}
Does this make any sense? It appears to be working but there is something off when I get the last index. If I input 5 for example, I get the numbers 1, 2, 3, 4, and then 16 instead of 5.
I almost had the solution. I just made a single edit and now I have it working. But let me give you my paper debug table first. (I debug my programs with a pen and paper... for now.)
I used 3 as input here so I don't have to work all night with this. You can see that the second table has a question mark. This is to indicate that index 2 had no value assigned to it in the first loop. So what can I possibly get by reading from it? I get some random number that just happened to be at that location in memory. In my first example above with 5 as input that number happened to be 16. For input of 3 this time I actually got a huge number...
1
2
7012072
Now that I look at it I see two edits. Anyway! Here is the solution:
The pointer syntax is only used when creating the array and when you are done with the array.
1 2 3 4 5
int *arr = newint[size]; //size can now come from an earlier cin! :)
//use arr as you usually would
delete[] arr; //just after you are done with arr
With vectors this pointer syntax is completely masked behind the implementation of vector.
1 2 3 4 5 6 7 8 9 10
#include <vector>
usingnamespace std;
//eventually in int main
vector<int> arr;
//declare/cin size
arr.resize(size);
//use arr as normal now
//also arr.size() would be the same as the variable size at this point