C Program to Copy an Array to another

How to write a C Programming Program to Copy an Array to another array with an example and detail explanation?.

C Program to Copy an Array to another array

This C program allows the user to enter the size of an Array and then elements of an array. Using For Loop, we are going to copy each element to the second array.

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

#include<stdio.h>

int main()
{
 int i, Size, a[20], b[20];
  
 printf("\n Please Enter the Array Size \n");
 scanf("%d", &Size);
 
 printf("\n Please Enter the Array Elements \n");
 for(i = 0; i < Size; i++)
  {
     scanf("%d", &a[i]);
   
  }
 
 /* copying one array to another */  
 for(i = 0; i < Size; i++)
  {
    b[i] = a[i];
   
  }

 printf("\n Elements of Second Array are: \n");
 for(i = 0; i < Size; i++)
  {
    printf("\n Value Inside Array b[%d] = %d", i, b[i]);
  }
 
return 0;
}

C array copy output

Copy an Array to Another

In this C Program to Copy an Array to another, the below for loop will help to iterate each cell present in a[5] array. Condition inside the for loops (i < Size) will ensure the compiler, not to exceed the Array limit.

scanf statement inside the For Loop will store the user entered values in every individual array element such as a[0], a[1], a[2], a[3], a[4]

for(i = 0; i < Size; i++)
 {
   scanf("%d", &a[i]); 
 }

In the next line, We have one more C Programming for loop to copy an array to another array.

 /* copying one array to another */  
 for(i = 0; i < Size; i++)
  {
    b[i] = a[i];
  }

Above For loop is used to copy each element present in a[5] array into b[5] array. From the above C program screenshot
User inserted values are: a[5] = {10, 25, 45, 75, 95}

First Iteration
The value of i will be 0, and the condition (i < 5) is True. So, it will start executing the statements inside the loop until the condition fails.
b[i] = a[i];
b[0] = a[0]
b[0] = 10

Second Iteration
The value of i will be 1, and the condition (1 < 5) is True.
b[1] = a[1]
b[1] = 25

Third Iteration
i = 2, and the condition (2 < 5) is True.
b[2] = a[2]
b[2] = 45

Fourth Iteration
i = 3, and the condition (3 < 5) is True.
b[3] = a[3]
b[3] = 75

Fifth Iteration
i = 4, and the condition (4 < 5) is True.
b[4] = a[4]
b[4] = 95

After incrementing the value of i, i will become 5. So, the condition (i < Size) will fail, and the compiler will exit from the loop.

Next for loops, Will traverse as we explained above. But instead of copying the elements, it will display the values one by one using the printf statement inside it.

for(i = 0; i < Size; i++)
 {
    printf("\n Value Inside Array b[%d] = %d", i, b[i]);
 }

The final output of the C Program to Copy an Array to another is:
b[5] = {10, 25, 45, 75, 95}