How to add 2 array in C
×


How to add 2 array in C

261

 Adding two arrays in C involves adding corresponding elements of the arrays together to create a new array with the sum of each pair of elements.

Steps for adding two arrays in C

1Input:

 First, we need to have two arrays of the same size.

 These arrays represent the elements we want to add together.

2Addition Operation:

 We iterate through each element of the arrays and add the corresponding elements together.

For example, if we have arrays A and B, and we want to add them to create array C, then C[i] = A[i] + B[i] for each index i.

3Output:

 After performing the addition operation for each pair of elements, we obtain a new array C containing the sum of the corresponding elements from arrays A and B.

Example:

// Program for Adding two arrays in C
#include<stdio.h> 

// Function to add two arrays and store the result in a third array
void addArrays(int arra1[], int arra2[], int result[], int size) {
    for (int A = 0; A < size; A++) {
        result[A] = arra1[A] + arra2[A];
    }
}

// Function to print an array
void printArray(int arr[], int size) {
    for (int A= 0; A < size; A++) {
        printf("%d ", arr[A]);
    }
    printf("\n");
}

int main() {
    int array1[] = {1, 2, 3, 4, 5};
    int array2[] = {6, 7, 8, 9, 10};
    int size = sizeof(array1) / sizeof(array1[0]);

    int result[size];

    // Add the arrays
    addArrays(array1, array2, result, size);

    // Print the result
    printf("Resultant Array: ");
    printArray(result, size);

    return 0;
}

Output:

Resultant Array: 7 9 11 13 15

In this program:

We define a function printArray to print the elements of an array.

In the main function, we create two arrays array1 and array2, and then call the addArrays function to add them together, storing the result in the result array.

Finally, we print the resulting array.

This program demonstrates the process of adding two arrays in C, producing the sum of corresponding elements in a new array.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments