Create arrays A, B of size 3, C of size 6, merge A and B into C.
Learn how to merge two arrays into a third array in C
๐งพ Step-by-Step Explanation
๐น Step 1: Include Header File
#include <stdio.h>
This header provides:
printf()
for output displayscanf()
for user input- Standard I/O functions
๐น Step 2: Declare Arrays and Variable
int A[3], B[3], C[6];
int i;
- A[3] and B[3]: Input arrays (3 elements each)
- C[6]: Output array for merged result
- i: Loop counter for array operations
๐น Step 3: Input Elements in Array A
for(i = 0; i < 3; i++) {
printf("A[%d]: ", i);
scanf("%d", &A[i]);
}
- Prompts user for 3 values
- Stores them in array A
- Uses
%d
format for integers
๐น Step 4: Input Elements in Array B
for(i = 0; i < 3; i++) {
printf("B[%d]: ", i);
scanf("%d", &B[i]);
}
- Same process as Step 3
- Stores values in array B
- Maintains parallel indexing
๐น Step 5: Merge Array A into C
for(i = 0; i < 3; i++) {
C[i] = A[i];
}
- Copies A[0] to C[0]
- Copies A[1] to C[1]
- Copies A[2] to C[2]
๐น Step 6: Merge Array B into C
for(i = 0; i < 3; i++) {
C[i + 3] = B[i];
}
- Copies B[0] to C[3]
- Copies B[1] to C[4]
- Copies B[2] to C[5]
- Uses index shifting (i + 3)
๐น Step 7: Display Merged Array C
for(i = 0; i < 6; i++) {
printf("C[%d] = %d\n", i, C[i]);
}
- Prints all 6 elements of C
- Shows index and value for each
- Uses
\n
for newlines
๐งช Sample Output
Enter 3 elements of array A:
A[0]: 10
A[1]: 20
A[2]: 30
Enter 3 elements of array B:
B[0]: 40
B[1]: 50
B[2]: 60
Merged array C:
C[0] = 10
C[1] = 20
C[2] = 30
C[3] = 40
C[4] = 50
C[5] = 60
๐ Key Concepts Covered
int arr[size]
C[i + 3]
to place elements after existing onesprintf()
and scanf()
for console interaction