Reputation: 1
My code uses a for Loop to copy and paste the contents of V1 -> V2. I would like to see the output of v2 using cout but i am unsure where to put that line of code.
void copy_fct();
int main()
{
copy_fct();
}
void copy_fct()
{
int v1[10] = {0,1,2,3,4,5,6,7,8,9};
int v2[10];
for (int i=0; i!=10; ++i){
v2[i]=v1[i];
}
}
Upvotes: 0
Views: 42
Reputation: 311038
In your program design the name of the function copy_fct
does not make great sense because it copies nothing passed to the function by the user. It deals with its local variables.
It seems you mean something like the following.
#include <iostream>
void copy_fct( const int a1[], size_t n, int a2[] )
{
for ( size_t i = 0; i < n; i++ ) a2[i] = a1[i];
}
int main()
{
const size_t N = 10;
int v1[N] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int v2[N];
copy_fct( v1, N, v2 );
for ( int item : v2 ) std::cout << item << ' ';
std::cout << '\n';
return 0;
}
The program output is
0 1 2 3 4 5 6 7 8 9
The same task can be done using standard algorithms.
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
const size_t N = 10;
int v1[N] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int v2[N];
std::copy( std::begin( v1 ), std::end( v1 ), std::begin( v2 ) );
std::copy( std::begin( v2 ), std::end( v2 ), std::ostream_iterator<int>( std::cout, " " ) );
return 0;
}
Upvotes: 0
Reputation: 889
#include <iostream>
void copy_fct();
int main()
{
copy_fct();
}
void copy_fct()
{
int v1[10] = {0,1,2,3,4,5,6,7,8,9};
int v2[10];
for (int i=0; i!=10; ++i){
v2[i]=v1[i];
std::cout << v2[i] << " ";
}
std::cout << std::endl;
}
Upvotes: 1