I am using Visual Studio 2013, c++, console application. I have been struggling with a question for quite some time now. I want to know if there is a way to initialise an array, with input from the user, for example:
I have an array: int arr[] = { 3, 7, 5, 9, 1};
. Therefore, I want the initialised values to be a user input.
Is there a way I can do it? All help and comments will be appreciated.
This is my code: cout << "Enter the number of array elements: "; cin >> elements;
cout << "Enter the difference value: ";
cin >> difference;
cout << "Enter the sequence of elements: ";
vector<int> arr(elements);
for (int i = 0; i < elements; i++)
{
cin >> arr[i];
}
//the following needs to have an array
//in their respective functions.
sorter(arr[], elements);
elementsDifference(arr[], elements, difference);
this program has to loop through an array and find pairs with the given difference.
How about
int arr[10] , i;
for ( i = 0 ; i < 10 ; i++ )
std::cin >> a[i];
This simple code fragment will take 10 inputs from the user and store them in the array.
If you want to change the number of input, you can just change the condition in the for loop ( also make sure that your array has enough size to store all the values ).
You can try it like this
int size;
cin >> size;
int a[size],i;
for ( i = 0 ; i < size ; i++ )
cin >> a[i];
for ( i = 0 ; i < size ; i++ )
cout << a[i] << endl;
Normally, people would just make the size of the array very large ( like a[100000]
or so ) and then accept the size, and fill up the array using a code similar to the one I gave above.
But an even better way would be to use vector
. You should learn about using vector