How do I make this code to run if I do not know how many index I will have, before the user inputs the index value. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How do I make this code to run if I do not know how many index I will have, before the user inputs the index value.

#include<iostream> using namespace std; void printmyArr(int Arr[], int size) { for (int x = 0; x < size; x++) { cout << Arr[x] << endl; } } int main() { int myArr[] = {}; int index; cout << "Please enter the number of iterations: "; cin >> index; for (int x = 0; x < index; x++) { cout << "Please enter the value for index '" << x << "' :"; cin >> myArr[x]; } printmyArr(myArr, index); system("pause"); return 0; }

18th May 2017, 3:35 PM
Santiago Restrepo Serna
Santiago Restrepo Serna - avatar
3 Answers
+ 3
18th May 2017, 4:43 PM
เคฆเฅ‡เคตเฅ‡เค‚เคฆเฅเคฐ เคฎเคนเคพเคœเคจ (Devender)
เคฆเฅ‡เคตเฅ‡เค‚เคฆเฅเคฐ เคฎเคนเคพเคœเคจ (Devender) - avatar
+ 1
You use dynamic arrays or a vector. Example: cin >> size; int* arr = new int[size]; arr[0] = 55; //example usage When you are done with it make sure to delete it and make the pointer null. We delete it because you allocated memory that you now no longer need. If you dont delete it you will have memory leaks. We make the pointer null so that it isnt pointing to memory that doesnt exist anymore. delete[] arr; arr = nullptr; I suggest learning vectors as they are easier and safer to use.
18th May 2017, 3:39 PM
aklex
aklex - avatar
- 1
Make the cin << to cout exp int test; cin >> test_1; cout << "blalalblalbalbalblbla" << test_1 << endl;
18th May 2017, 3:40 PM
kellen
kellen - avatar