Q:

C program to add two dynamic arrays

0

C program to add two dynamic arrays

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Here, we will allocate space for three integer arrays dynamically using the malloc() function and then read values for two arrays. After that, add the elements of both arrays and assign the result to the third array.

Program:

The source code to add two dynamic arrays is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to add two dynamic arrays

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

int main()
{
    int i = 0;
    int size = 0;

    int* dynamicArray1;
    int* dynamicArray2;
    int* dynamicArray3;

    printf("Enter the size for dynamic arrays: ");
    scanf("%d", &size);

    dynamicArray1 = (int*)malloc(size * sizeof(int));
    dynamicArray2 = (int*)malloc(size * sizeof(int));
    dynamicArray3 = (int*)malloc(size * sizeof(int));

    printf("Enter Elements of First Array: ");
    for (i = 0; i < size; i++)
        scanf("%d", dynamicArray1 + i);

    printf("Enter Elements of Second Array: ");
    for (i = 0; i < size; i++)
        scanf("%d", dynamicArray2 + i);

    //Now add both arrays
    for (i = 0; i < size; i++)
        *(dynamicArray3 + i) = *(dynamicArray1 + i) + *(dynamicArray2 + i);

    printf("Result of Addition: \n");
    for (i = 0; i < size; i++)
        printf("%d ", *(dynamicArray3 + i));

    printf("\n");
    return 0;
}

Output:

Enter the size for dynamic arrays: 3
Enter Elements of First Array: 10 20 30
Enter Elements of Second Array: 40 50 60
Result of Addition: 
50 70 90

Explanation:

Here, we created three dynamic arrays using the malloc() function then add the elements of two arrays and assigned the result to the third array. After that, we printed the resulted array on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

One Dimensional Array Programs / Examples in C programming language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to find the sum of the largest contiguou... >>
<< C program to calculate the sum of array elements u...