C PROGRAM
Program to append two array |C program|
Introduction
Arrays are fundamental in programming, and operations like combining or appending arrays are common tasks. In this blog post, we will explore a simple C program that appends two arrays. The program takes user input for two arrays, combines them, and displays the result.
Code
#include<stdio.h>
#include<conio.h>
void main() {
int i, j, k, m, n, total, a[10], b[10], c[30];
clrscr();
// Input for Array A
printf("Enter the size of an array A: ");
scanf("%d", &n);
printf("Enter the elements of array A:\n");
for (i = 0; i <n; i++) {
scanf("%d", &a[i]);
}
// Input for Array B
printf("Enter the size of an array B: ");
scanf("%d", &m);
printf("Enter the elements of array B:\n");
for (j = 0; j <m; j++) {
scanf("%d", &b[j]);
}
// Appending Arrays
total = m + n;
for (i = 0; i <n; i++) {
c[i] = a[i];
}
for (j = 0; j < m; j++, n++) {
c[n] = b[j];
}
// Displaying Appended Array
printf("Appended array C:\n");
for (k = 0; k < total; k++) {
printf("%d\n", c[k]);
}
getch();
}
Output
Enter the size of an array A: 3
Enter the elements of array A:
1
2
3
Enter the size of an array B: 2
Enter the elements of array B:
4
5
Appended array C:
1
2
3
4
5
In this example, the program takes two arrays, A and B, with sizes 3 and 2, respectively. After appending, the resulting array C contains elements from both arrays, resulting in the output shown above.
You can try running the program with different input values to see how it accurately appends the arrays and displays the combined result.
Explanation
1. Header Files:
The program includes the standard input/output header <stdio.h> and the console input/output header <conio.h>.
2. Main Function:
Serves as the entry point of the program.
3. Input:
Users input the size and elements of two arrays, A and B.
4. Array Appending:
The program appends array B to the end of array A, creating a new array C.
The total variable keeps track of the combined size of arrays A and B.
5. Output:
Displays the elements of the appended array C
Conclusion
This C program showcases a straightforward method of combining two arrays. Understanding array manipulation is crucial for handling data in programming. Run the program with different inputs to observe how it accurately appends the two arrays, creating a new combined array.
Feel free to experiment with various array sizes and element values to see the flexibility of this array appending approach. Happy coding!
Post a Comment
0 Comments