C program to copy all elements of one array to another

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.

  1. Input size and elements in array, store it in some variable say size and source.
  2. Declare another array dest to store copy of source.
  3. 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++).

  4. 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;
}

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 😉

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>