C (programming language)
C Program to Copy the Elements of one Array into Another Array
Understanding the Task
- Goal: Create a C program that replicates elements from one array into another, ensuring independent storage.
- Key Concepts:
- Arrays: Data structures for storing multiple elements of the same type.
- Loops:
for
loop for iterating through array elements. - Array indexing: Accessing individual elements using their indices.
Step-by-Step Guide
1. Header Inclusion
C
#include <stdio.h>
- Explanation: Includes the standard input/output library for functions like
printf
.
2. Main Function
C
int main() {
// Code statements here
return 0;
}
3. Declare Arrays
C
int arr1[100], arr2[100]; // Declare arrays of size 100 (adjust as needed)
int size;
- Explanation: Declares two integer arrays
arr1
andarr2
, each with a capacity of 100 elements. Adjust the size as required.
4. Get Number of Elements
C
printf("Enter the number of elements: ");
scanf("%d", &size);
5. Get Elements of the First Array
C
printf("Enter elements of the first array:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &arr1[i]);
}
6. Copy Elements to the Second Array
C
for (int i = 0; i < size; i++) {
arr2[i] = arr1[i]; // Copy each element from arr1 to arr2
}
7. Print the Copied Array
C
printf("Elements of the second array:\n");
for (int i = 0; i < size; i++) {
printf("%d ", arr2[i]);
}
printf("\n");
8. Complete Code
C
#include <stdio.h>
int main() {
int arr1[100], arr2[100];
int size;
printf("Enter the number of elements: ");
scanf("%d", &size);
printf("Enter elements of the first array:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &arr1[i]);
}
for (int i = 0; i < size; i++) {
arr2[i] = arr1[i];
}
printf("Elements of the second array:\n");
for (int i = 0; i < size; i++) {
printf("%d ", arr2[i]);
}
printf("\n");
return 0;
}
9. Executing the Program
- Save the code as a
.c
file (e.g.,array_copy.c
). - Compile using a C compiler (e.g.,
gcc array_copy.c -o array_copy
). - Run the executable (e.g.,
./array_copy
).
Key Points
- The two arrays are now independent, meaning changes to one won’t affect the other.
- Ensure the second array has sufficient space to accommodate the copied elements.
- Consider using functions for better organization and reusability when working with more complex array operations.