Array

how to insert a variable for the size of array and prompt user to insert the elements for the array?
If you mean declare a variable with size of array and the aim is to get n number of elements then you can do something like

1
2
3
4
const int arraySize = 10;
//declare array and other code
std::cout << "enter " << arraySize << "elements" << std::endl; 
//other code 
Last edited on
What I want is arraySize=x
x is to be inserted by user. After that prompt user to insert the elements.
Last edited on
1
2
3
4
5
6
int arraySize = 0;
//some code
std::cout << "enter number of elements" << std::endl;
std::cin >> arraySize;
//declare and define array 
//read each elem using loop for arraySize - 1 times 
Then how do you input the array?
Is this correct?

cout<<"Enter the total number of workers:"<<end;//Prompt user to input the array size

cin>>workers;//User will input the data

int n[workers]=

After int n[workers]= , what should I do to prompt user to input the number of elements according to the array size?
this should help

1
2
3
4
5
6
7
8
9
int arraySize = 0;
cout<<"Enter array size"<<endl; //prompts user for number of workers
cin>>arraySize; //number of workers

int arrayElement[arraySize]; //declairs the array with the input size
cout<<"Enter array value"<<endl; //prompts user for value in the array
for (i=0;i<arraySize;i++) //loops the array from 0 to < arraySize for value of array
{
cin>>arrayElement[i];}
Last edited on
It does not work. From int arrayElement[arraySize] onwards. The arraySize will be in red
try this 1 ..dynamic array

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
26
27
#include <iostream>
#include <new>
using namespace std;

int main ()
{
  int i,n;
  int * p;
  cout << "How many numbers would you like to type? ";
  cin >> i;
  p= new (nothrow) int[i];
  if (p == 0)
    cout << "Error: memory could not be allocated";
  else
  {
    for (n=0; n<i; n++)
    {
      cout << "Enter number: ";
      cin >> p[n];
    }
    cout << "You have entered: ";
    for (n=0; n<i; n++)
      cout << p[n] << ", ";
    delete[] p;
  }
  return 0;
}
Something is wrong with your code. There is an error. :(
i am using VS 2008
I am using VS 2010
There is no error I'm using CodeBlocks
Variable sized arrays are not kosher C++ -- they're a C99 feature that GCC's compiler allows you to use if you don't ask it to enforce ANSI compliance.

Andy
Last edited on
Thanks for helping guys :)
Topic archived. No new replies allowed.