I have to write a program where the user will input integer numbers. How many numbers they enter is unknown, therefor you should use a repetition structure for the input. When the user is done, they will enter -1 to exit.
Create a dynamic array if the size=2( the initial size must be 2)
Repeat until user enters -1.
I have to do this without using vectors.
This is what i have, I cannot figure out what to put in main. I was thinking of a do-while?
#include <iostream>
usingnamespace std;
void resize(int *[], int);
int main()
{
int *listDyn;
int size=2;
listDyn=newint[size];
for (int i=0; i<size; i++)
{
cout << "Enter as many integers as you'd like or enter -1 to exit" ;
cin >> listDyn[i];
}
void resize(int *listDyn, int size)
{
int *listDynNew=newint[size*2];
for (int i=0; i<size; i++)
listDynNew[i]=listDyn[i];
size++;
listDyn=listDynNew;
delete[] listDynNew;
}
}
create initial dynamic array with size 2
do
get input
get input count //the number of inputs
if(input count == sizeof(array))
resize array by any amount you want
while(input != -1)
You need to keep track of both the size of the array ( the number of valid elements in it) and the capacity (the number that it is currently capable of holding. When you run out of space, you double the capacity, and add 1 to the size.
Although malloc/realloc will work for arrays of integers, they won't work right for arbitrary classes because they don't call the constructors/destructors, so you should probably do it with new[] and delete[] as you already have it.
usingnamespace std;
int resize(int *, int);
int main()
{
int *listDyn;
int size=2;
listDyn=newint[size];
int input;
cout << "Please enter a number or enter -1 to exit" << endl;
cin >> input;
while(input != -1)
{
for (int i=0;i<size;i++)
{
listDyn[i]=input;
}
if()
}
for (int i=0;i<size;i++)
cout << listDyn[i] << endl;
system("pause");
}
int resize(int *listDyn, int size)
{
int *listDynNew=newint[size*2];
for (int i=0; i<size; i++)
{
listDynNew[i]=listDyn[i];
}
listDyn=listDynNew;
size++;
delete[] listDyn;
return listDynNew;
}
Im not sure what to put in the if statement and idk where to include my resize function.
Do you see anything else wrong with my program?
Your resize function looks correct to me but the main loop isn't right. For one thing, you only let the user input a single number. The input loop should be something like this:
1 2 3 4 5 6
for (i=0; true; ++i) {
cout << "Please enter a number or enter -1 to exit" << endl;
cin >> input;
if (!cin || input == -1) break;
listDyn[i] = input;
}
This doesn't resize listDyn yet. You'll have to add that code.
Note that when you exit the loop, i contains the number of items in listDyn.