C program to copy all elements of one array to another

Write a C program to read elements in array and copy all elements of first array into second array. C program to copy elements of array. Logic to copy array elements to another array using C program.

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 C programming, For loop, Array

Logic to copy array elements to another array

Below is the step by step descriptive logic to make copy of an array.

  1. Input size and elements in array, store it in some variable say size and first.
  2. Declare another to store copy of the first array, say second.
  3. Now, to copy all elements from first to second array, you just need to run loop through each elements of first array.
    Run a loop from 0 to size of the array. The loop structure should look like for(i=0; i<size; i++).
  4. Inside the loop assign the current element value of first array to second i.e. second[i] = first[i].

Program to copy all array elements to another array

/**
 * C program to copy one array to another array
 */

#include <stdio.h>
#include MAX_SIZE 100

int main()
{
    int first[MAX_SIZE], second[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 first array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &first[i]);
    }

    /*
     * Copy all elements from first array to second array
     */
    for(i=0; i<size; i++)
    {
        second[i] = first[i];
    }

    /* 
     * Print all elements of first array
     */
    printf("\nElements of first array are : ");
    for(i=0; i<size; i++)
    {
        printf("%d\t", first[i]);
    }

    /*
     * Print all elements of second array
     */
    printf("\nElements of second array are : ");
    for(i=0; i<size; i++)
    {
        printf("%d\t", second[i]);
    }

    return 0;
}

Output

Enter the size of the array : 10
Enter elements of first array : 10 20 30 40 50 60 70 80 90 100

Elements of first array are : 10        20        30        40        50        60        70        80        90        100
Elements of second array are : 10        20        30        40        50        60        70        80        90        100

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>