Array Exercises
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.
Required knowledge
Basic C programming, If else, c-Arrays, C Loops
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 and source.
- Declare another array dest to store copy of source.
- Now, to copy all elements from source to dest array, you just need to iterate through each element of source.
Run a loop from 0 to size. The loop structure should look like for(i=0; i<size; i++). - Inside loop assign current array element of source to dest 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;
}
