×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to add two dynamic arrays

Here, we are going to learn how to add two dynamic arrays in C programming language?
Submitted by Nidhi, on July 10, 2021

Program statement

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.

Add two dynamic arrays in C

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

// 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.

C One-Dimensional Array Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.