I'm new to c++ so please take things slow with me. I heard in class that dynamic arrays like in java aren't supported so I thought as an exercise I would make a program that sort of acts like a dynamic array. I'm using a mac btw. For some reason it repeats the last number:
here is the code:
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
void intake(int a);
int n;
int* num;
int main()
{
int sum, average, i, a;
cout << "this program takes in an indeterminate amount of numbers\n";
cout << "enter a letter to stop\n";
i = 0;
sum = 0;
average = 0;
num = new int[1];
while (!cin.fail())
{
i++;
cout << "Enter number " << i << ": ";
if (!cin.fail())
{
cin >> a;
intake(a);
sum = sum + a;
}
}
average = sum / i;
for(int i = 0; i<n;i++)
{
cout << num[i] << " ";
if ((i%10) == 0)
cout << endl;
}
cout << "\nAverage: " << average << endl;
return 0;
}
void intake(int a)
{
int* numa;
numa = new int[n];
for(int i = 0; i<n; i++)
numa[i] = num[i];
num = new int[n+1];
for(int i = 0; i<n; i++)
num[i] = numa[i];
num[n] = a;
n++;
}
and here's what the output was:
this program takes in an indeterminate amount of numbers
enter a letter to stop
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Enter number 4: 4
Enter number 5: 5
Enter number 6: 6
Enter number 7: 7
Enter number 8: 8
Enter number 9: 9
Enter number 10: 10
Enter number 11: 11
Enter number 12: 12
Enter number 13: 13
Enter number 14: 14
Enter number 15: 15
Enter number 16: 16
Enter number 17: a
1
2 3 4 5 6 7 8 9 10 11
12 13 14 15 16 16
Average: 8