I've used this loop before. It is supposed to count up to whatever number I enter. All of a sudden, the output stops at 6.I enter 1. The program returns 1. Two? Two. All the way until 7. I enter 7, and it stops at 6.
I am using Bloodshed Dev C++, running on Vista Home Premium.
My code:
#include <iostream>
using namespace std;
int main()
{
int i;
int upperRange;
int testArray[0];
cout << "Please enter a number: ";
cin >> upperRange;
//Create array
for (i = 1; i <= upperRange; i++)
{
testArray[i] = i;
}
//Test array
for (i = 1; i <= upperRange; i++)
{
cout << testArray[i] << endl;
}
#include <iostream>
usingnamespace std;
int main()
{
int size; //variable to store the size of array
int *testArray; // an integer pointer variable to store
// address of first cell of array
cout << "Enter size of array, that is the amount of numbers you have" << endl;
cin >> size;
testArray = newint [size]; //dynamically assign memory to an
//array of integer elements containing
//'size' elements
int i=0, count=1; //i is initialized to zero because in c++
//the index of first element of an array is zero.
while (i < size) //you can use the for loop if you like
{
testArray[i] = count;
cout << "testArray[" << i << "]\t" << testArray[i] << endl;
++count;
++i;
}
return (0);
}
What you need to know is that the first element of an array can be accessed using an index of 0.
For example, if i say my_array[0] = 34 , i'm referring to the
first element of the array and storing 34 there.
If i say my_array[1] = 27 i'm referring to the second element of the array and storing the number 27 in there.
That's why, i think, when you are using the for loop with i initialised to 1 instead of 0,
you tend to get 1 count in less!
Arun1390,
Thank you. That did the trick. I know that C++ starts counting at 0. I'm just using 1 as a starting place out of simplicity. It's playing loose with memory allocation, I know, but hey, beginners begin somewhere.
Arun1390,
Thank you. That did the trick. I know that C++ starts counting at 0. I'm just using 1 as a starting place out of simplicity. It's playing loose with memory allocation, I know, but hey, beginners begin somewhere.