Make The User Input Values That is To Be Stored In an Array

Hey I am an Noob in C++ Programming ( I admit it) , I am Making a program in which the User should Enter some Numbers and the numbers should be stored in an array.

I want to make the User Enter as much as He / She wants , and stop the Input by entering 0 . Is there any way to do it using Loop ?

Help Me Guys :)

Have you studied do/while loops?

1
2
3
4
5
6
7
8
9
10
11
12
13
int prompt_for_array (int arr[], int maxnum)
{   int cnt = 0;
    int val;

    cout << "Enter numbers: " << endl;
    do 
    {   cout << "?";
        cin >> val;
        arr[cnt++] = val;
        cout << endl;
    } while (cnt < maxnum && val > 0);
    return cnt;  //Number of valid entries in array
}

Don't you need to initialize the array with a size? i.e. The size of the array must be known... I guess as long as you make the array size 1000, you won't likely have the user inputting that many variables...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// set_union example
#include <iostream>     // std::cout
#include <algorithm>    // std::set_union, std::sort
#include <vector>       // std::vector

int main () {
  int first[] = {5,10,15,20,25};
  int second[] = {50,40,30,20,10};
  std::vector<int> v(10);                      // 0  0  0  0  0  0  0  0  0  0
  std::vector<int>::iterator it;

  std::sort (first,first+5);     //  5 10 15 20 25
  std::sort (second,second+5);   // 10 20 30 40 50

  it=std::set_union (first, first+5, second, second+5, v.begin());
                                               // 5 10 15 20 25 30 40 50  0  0
  v.resize(it-v.begin());                      // 5 10 15 20 25 30 40 50

  std::cout << "The union has " << (v.size()) << " elements:\n";
  for (it=v.begin(); it!=v.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}


I just want The User to enter The Numbers

1
2
int first[] = {5,10,15,20,25};
  int second[] = {50,40,30,20,10};


is there any Way to do that using Loop ? AbstractionAnon (2143) appreciate the Help !!
Don't you need to initialize the array with a size?

No. Where the array is defined, it needs to be defined with a size (or allocated dynamically). I did not show the above function being called, so therefore left out the definition of the array.

In the above function, arr is declared as an array of unknown size. The routine only needs to know the base address of the array. The maxnum argument makes sure the function does not write past the end of the array (assuming the caller passes the correct size of the array).
Topic archived. No new replies allowed.