- Write a C program to copy all elements from one array to another array.
- How to copy elements of one array to another array.
Required Knowledge
- C printf and scanf functions
- For loop in C
- Accessing Array Elements in C
Algorithm to copy elements of one array to another array
Let inputArray is an integer array having N elements and copyArray is the array where we want to copy all N elements of inputArray. Size of copyArray is >= size of inputArray.
- Using for loop, we will traverse inputArray from array from index 0 to N-1.
- We will copy the ith(0 <= i <= N-1) element of inputArray to ith index of copyArray.
copyArray[i] = inputArray[i];
C program to copy all elements of an array to another array
/* * C Program to copy all elements of one array to another array */ #include <stdio.h> #include <conio.h> int main(){ int inputArray[100], copyArray[100], elementCount, counter; printf("Enter Number of Elements in Array\n"); scanf("%d", &elementCount); printf("Enter %d numbers \n", elementCount); /* Read array elements */ for(counter = 0; counter < elementCount; counter++){ scanf("%d", &inputArray[counter]); } /* Copy array elements form inputArray to copyArray */ for(counter = 0; counter < elementCount; counter++){ copyArray[counter] = inputArray[counter]; } /* Print duplicate Array(copyArray) elements */ printf("Duplicate Array\n"); for(counter = 0; counter < elementCount; counter++){ printf("%d ", copyArray[counter]); } getch(); return 0; }
Output
Enter Number of Elements in Array 5 Enter 5 numbers 5 3 8 1 -3 Duplicate Array 5 3 8 1 -3