#include<iostream>
usingnamespace std;
int number;//why it only seems to compile when initialized here.
int main()
{
int sum=0;
//had it initialized as int arr[]; and int number;
//also had int arr[]={number};
//could someone explain these differences to me?
int arr[number];
cout << "Please enter number." << endl;
cin >> number;
cout << "Please enter " << number << "numbers" << endl;
for(int i=1; i<number; i++)
{
cout << "Enter number" << i << endl;
}
sum += sum;
cout << "Your sum is" << sum;
return 0;
}
Please enter number.
Please enter 0numbers
Your sum is0
[codeint arr[number]][/code] is wrong number isn't initialized declaring an array especially a static
array would require you to provide its size during it's declaration you can als use a constant expression for declaration of the array size
1 2 3 4 5 6 7 8 9 10
int array [10]; /// an array of size 10
constexpr size_t size=10;
int array [size]; ///an array of ten ints
If you want to request thr array size from the use then you can't use a static array
Use dynamic arrays instead
size_t size;
cout <<"enter size"; cin>> size;
int *arr= new int [size];
you will need to add values to your array after that ; calculate the sum but not as you have done above coz your sum+=sum is doing the wrong thing and is also outside the loop. then free the array storage
Do I have to always set a [size] of an array or set the elements in the array when initializing an array? But in the case of the user inputting the size of an array, we first start off with putting a random number of array size for it, then changing it later in the code depending on the user input?
When using static arrays it is only safe to intialize its size o declaration we first start off with putting a random number of array size for it, then changing it later in the codeĀ these is as dangerous as it sounds, you can never change the size of a static array it size must remain constant , the size is also part of its type hence changing it size might mean you are also changing the arry type
1 2 3 4
int arr [10] // arr have the type int [10] to
//change the array size you will need to make another array of the new size and copy the
// elements of the older array into the new array
which is costly since you cant delete the older array.
If you want to ddetermine the array size at runtime please use dynamic arrays or other containers such as vectors that are capable of efficient dynamic growth
int *array = newint [size]; is an int pointer , it points to a dynamic array of the size specified by the user. '*' show that the variable array is a pointer, * is called a dereference operator
Check here
http://www.cplusplus.com/doc/tutorial/pointers/
http://www.cplusplus.com/doc/tutorial/dynamic/
http://www.cplusplus.com/reference/new/operator%20new[]/