I wanted to know how I can use one array in one function that this array has gotten from another function . all of these functions are in one program .
void InputArray(int n, int A[n])
{
for (int i=0; i<n; i++)
{
cout<<"A["<<i<<"]=";
cin>>A[i];
}
}
int SumArray(int n, int A[n])
{
int S = 0;
for (int i=0; i<n; i++)
S+=A[i];
return S;
}
int main()
{
int n;
cin>>n;
int A[n];
InputArray(n, A);
SumArray(n, A);
return 0;
}
micheal... that won't work on every compiler. It might be better if you take n from between the brackets...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int SumArray(int n, int A[])
{
int S = 0;
for (int i=0; i<n; i++)
S+=A[i];
return S;
}
int main()
{
int n;
cin>>n;
int A[n];
InputArray(n,A); // fine
return 0;
}
That should fix your code for most compilers...
If you want to go farther, you could also template the size and have two separate functions so if you have a set size (the example you have would have to call the second function with A)... I saw this somewhere and have been using it ever since... It seems to work on every compiler I've found...
void InputArray( int *A, size_t n )
{
for (size_t i=0; i<n; i++)
{
cout<<"A["<<i<<"]=";
cin>>A[i];
}
}
template<size_t n>
void InputArray(int (&A)[n] )
{
InputArray(A,n);
}
int main()
{
int n;
cin>>n;
int A[n];
int B[10];
InputArray(B); // fine
InputArray(A,n); // fine
//InputArray(A); // error, too few arguments... it's calling the nontemplate function
return 0;
}
oh, I wanted to add int A[n]; should probably be int *A = newint[n]; because it's dynamic... I'm not sure what people think of the using the first one...