Lets write a c program to copy all the elements of one array to another array of same size.
Related Read:
Basics of Arrays: C Program
Page Contents
Example: Expected Output
Enter 5 integer numbers
5
2
6
4
3
Copying elements of array a to b
Original(a[5]) –> Copy (b[5])
5 –> 5
2 –> 2
6 –> 6
4 –> 4
3 –> 3
Video Tutorial: C Program To Copy Elements of One Array To Another
Source Code: C Program To Copy Elements of One Array To Another
- #include<stdio.h>
- #define N 5
- int main()
- {
- int a[N], b[N], i;
- printf("Enter %d integer numbers\n", N);
- for(i = 0; i < 5; i++)
- scanf("%d", &a[i]);
- printf("\n\nCopying elements of array a to b\n");
- for(i = 0; i < N ; i++)
- b[i] = a[i];
- printf("\nOriginal(a[%d]) --> Copy (b[%d])\n", N, N);
- for(i = 0; i < N; i++)
- printf("%4d\t\t-->%6d\n", a[i], b[i]);
- return 0;
- }
Output:
Enter 5 integer numbers
5
4
3
2
1
Copying elements of array a to b
Original(a[5]) –> Copy (b[5])
5 –> 5
4 –> 4
3 –> 3
2 –> 2
1 –> 1
Logic To Copy Elements of One Array To Another
We ask the user to enter N integer numbers. N is macro which is used to define size of the array. We store the user entered numbers inside array variable a. Since both array variables a and b has same size we copy individual elements of array variable a to array variable b at same index position.
At the end we print / display the content of both original array(a[5]) and the array to which the elements are copied to(b[5]).
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert