Aug 29, 2014 at 10:46pm Aug 29, 2014 at 10:46pm UTC
Good Morning Coders,
I need a quick help with my while loop, I have a dynamically allocated array that increases with each input of an integer value, I wish to exit the loop once the user enters -1 and not have that value in the array. I've tried a combination of ideas but I'm stumped. Here is what i have so far
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
int main(int argc, char const *argv[])
{
int index = 1;
int * iptr = new int [index];
int count = 0;
do //input will continue till -1 is entered
{
cout << "Enter Integer Value: " ;
cin >> iptr[index];
cout << "1" << endl;
if (iptr[index] != -1)
{
cout << "2" << endl;
count++;
if (count >= index)
{
cout << "3" << endl;
index++; //increase by 1
int * temp = new int [index];//create a new bigger array
for (int i = 0; i < index; i++)//copy old array to new array
{
temp[i] = iptr[i];
cout << "4" << endl;
}
delete [] iptr;//free up old array memory
iptr = temp;//points to new array
cout << "5" << endl;
}
}
cout << "6" << endl;
}while (iptr[index] != -1);
Last edited on Aug 29, 2014 at 10:46pm Aug 29, 2014 at 10:46pm UTC
Aug 29, 2014 at 11:52pm Aug 29, 2014 at 11:52pm UTC
tried that the other day, for some reason it hangs before entering the loop
Aug 30, 2014 at 12:09am Aug 30, 2014 at 12:09am UTC
If that were true, your code would never reach line 13 where it outputs "1".
Aug 30, 2014 at 5:02am Aug 30, 2014 at 5:02am UTC
On line 12 you dynamically create an array of size 0. Line 21 is then guaranteed undefined behavior.
Aug 30, 2014 at 6:08am Aug 30, 2014 at 6:08am UTC
sorry but what do you mean?
weve only just started learning this
Aug 30, 2014 at 6:44am Aug 30, 2014 at 6:44am UTC
Line 10 index has a value of 0 then on line 12 when you create your dynamic array of size index you are creating an empty array.
Aug 30, 2014 at 7:49am Aug 30, 2014 at 7:49am UTC
oh ok I see what you mean, if i change the value to 1 will that solve the issue?
when i cout my sort as well im getting some random values. what is the cause of that?
this is with the input 15 -9
1 2 3 4 5 6 7 8 9 10 11
Enter next integer: -1
X9
X11
X12
X13
X14
X15
X10098048
X117242368
The Mean of the Numbers Entered is : 1.59176e+00
Last edited on Aug 30, 2014 at 7:56am Aug 30, 2014 at 7:56am UTC
Aug 30, 2014 at 9:22am Aug 30, 2014 at 9:22am UTC
ok im going to have go back over pointers