C program to copy an array to another array; Through this tutorial, we will learn how to copy the elements present in one array to another using for loop, function and recursion in c programs.
Programs to Copy an Array to another in C
To copy the elements present in one array to another using for loop, function and recursion in c programs:
- C Program to Copy an Array to another using For Loop
- C Program to Copy an Array to another using Function
- C Program to Copy an Array to another using Recursion
C Program to Copy an Array to another using For Loop
/* c program to copy one array to another array */ #include<stdio.h> int main() { int i, Size, a[20], b[20]; printf("\n Please Enter the Array Size :- "); scanf("%d", &Size); printf("\n Please Enter the Array Elements :- "); for(i = 0; i < Size; i++) { scanf("%d", &a[i]); } /* copying one array to another */ for(i = 0; i < Size; i++) { b[i] = a[i]; } printf("\n Elements of Second Array are: \n"); for(i = 0; i < Size; i++) { printf("\n Value Inside Array b[%d] = %d", i, b[i]); } return 0; }
The output of the above c program; as follows:
Please Enter the Array Size :- 5 Please Enter the Array Elements :- 1 2 23 4 5 Elements of Second Array are: Value Inside Array b[0] = 1 Value Inside Array b[1] = 2 Value Inside Array b[2] = 23 Value Inside Array b[3] = 4 Value Inside Array b[4] = 5
C Program to Copy an Array to another using Function
#include <stdio.h> copy(int *a,int *b,int n) { int i; for(i=0; i<n; i++) { b[i]=a[i]; } } print(int a[],int n) { int i; for(i=0; i<n; i++) { printf("%d ",a[i]); } } int main() { int a[1000],b[1000],i,n; printf("Enter size of the array : "); scanf("%d", &n); printf("Enter elements in array : "); for(i=0; i<n; i++) { scanf("%d", &a[i]); } copy(a,b,n); printf(" first array : "); print(a,n); printf("\nsecond array : "); print(b,n); }
The output of the above c program; as follows:
Enter size of the array : 5 Enter elements in array : 5 6 1 4 8 first array : 5 6 1 4 8 second array : 5 6 1 4 8
C Program to Copy an Array to another using Recursion
#include <stdio.h> copy(int a[],int b[],int n,int i) { if(i<n) { b[i]=a[i]; copy(a,b,n,++i); } } print(int a[],int n) { int i; for(i=0; i<n; i++) { printf("%d ",a[i]); } } int main() { int a[1000],b[1000],i,n; printf("Enter size of the array : "); scanf("%d", &n); printf("Enter elements in array : "); for(i=0; i<n; i++) { scanf("%d", &a[i]); } copy(a,b,n,0); printf(" first array : "); print(a,n); printf("\nsecond array : "); print(b,n); }
The output of the above c program; as follows:
Enter size of the array : 5 Enter elements in array : 1 3 5 4 8 first array : 1 3 5 4 8 second array : 1 3 5 4 8