To copy all the elements of one array to another in C language using three approaches.
Example:
Input:
First Array: a[5] = {3, 6, 9, 2, 5}
Output:
First Array : a[5] = {3, 6, 9, 2, 5}
Second Array : b[5] = {3, 6, 9, 2, 5}
Explanation: Copy elements from array a to b and then print the second array elements
Approach 1: Simple copying of elements from one array to another
C
#include <stdio.h>
int main()
{
int a[5] = { 3, 6, 9, 2, 5 }, n = 5;
int b[n], i;
for (i = 0; i < n; i++) {
b[i] = a[i];
}
printf ( "The first array is :" );
for (i = 0; i < n; i++) {
printf ( "%d " , a[i]);
}
printf ( "\nThe second array is :" );
for (i = 0; i < n; i++) {
printf ( "%d " , b[i]);
}
return 0;
}
|
Output
The first array is :3 6 9 2 5
The second array is :3 6 9 2 5
Approach 2: Using functions
C
#include <stdio.h>
int copy_array( int * a, int * b, int n)
{
int i;
for (i = 0; i < n; i++) {
b[i] = a[i];
}
for (i = 0; i < n; i++) {
printf ( "%d " , b[i]);
}
}
int first_array( int * a, int n)
{
int i;
for (i = 0; i < n; i++) {
printf ( "%d " , a[i]);
}
}
int main()
{
int k[5] = { 3, 6, 9, 2, 5 }, n = 5;
int l[n];
printf ( "The first array is : " );
first_array(k, n);
printf ( "\nThe second array is : " );
copy_array(k, l, n);
return 0;
}
|
Output
The first array is : 3 6 9 2 5
The second array is : 3 6 9 2 5
Approach 3: Using Recursion
C
#include <stdio.h>
int copy_array( int a[], int b[], int n, int i)
{
if (i < n) {
b[i] = a[i];
copy_array(a, b, n, ++i);
}
}
int array( int a[], int n)
{
int i;
for (i = 0; i < n; i++) {
printf ( "%d " , a[i]);
}
}
int main()
{
int k[5] = { 3, 6, 9, 2, 5 }, n = 5;
int l[n], i;
copy_array(k, l, n, 0);
printf ( "first array : " );
array(k, n);
printf ( "\nsecond array : " );
array(l, n);
return 0;
}
|
Output
first array : 3 6 9 2 5
second array : 3 6 9 2 5
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Aug, 2022
Like Article
Save Article