Write a C program to input elements in array and copy all elements of first array into second array. How to copy array elements to another array in C programming. Logic to copy array elements in C program using loop.
Example
Input
Input array1 elements: 10 1 95 30 45 12 60 89 40 -4
Output
Array1: 10 1 95 30 45 12 60 89 40 -4 Array2: 10 1 95 30 45 12 60 89 40 -4
Required knowledge
Basic Input Output, For loop, Array
Logic to copy array elements to another array
Step by step descriptive logic to copy an array.
- Input size and elements in array, store it in some variable say
size
andsource
. - Declare another array
dest
to store copy ofsource
. - Now, to copy all elements from
source
todest
array, you just need to iterate through each element ofsource
.Run a loop from 0 to
size
. The loop structure should look likefor(i=0; i<size; i++)
. - Inside loop assign current array element of
source
todest
i.e.dest[i] = source[i]
.
Program to copy array elements to another array
/**
* C program to copy one array to another array
*/
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int source[MAX_SIZE], dest[MAX_SIZE];
int i, size;
/* Input size of the array */
printf("Enter the size of the array : ");
scanf("%d", &size);
/* Input array elements */
printf("Enter elements of source array : ");
for(i=0; i<size; i++)
{
scanf("%d", &source[i]);
}
/*
* Copy all elements from source array to dest array
*/
for(i=0; i<size; i++)
{
dest[i] = source[i];
}
/*
* Print all elements of source array
*/
printf("\nElements of source array are : ");
for(i=0; i<size; i++)
{
printf("%d\t", source[i]);
}
/*
* Print all elements of dest array
*/
printf("\nElements of dest array are : ");
for(i=0; i<size; i++)
{
printf("%d\t", dest[i]);
}
return 0;
}
Learn how to copy array elements using pointers.
Output
Enter the size of the array : 10 Enter elements of source array : 10 20 30 40 50 60 70 80 90 100 Elements of source array are : 10 20 30 40 50 60 70 80 90 100 Elements of dest array are : 10 20 30 40 50 60 70 80 90 100
Happy coding 😉