C Program to Compute the Sum of two One-Dimensional Arrays using Malloc


  1. /*
  2.  * C program to find the sum of two one-dimensional arrays using
  3.  * Dynamic Memory Allocation
  4.  */
  5. #include <stdio.h>
  6. #include <malloc.h>
  7. #include <stdlib.h>
  8. 
    
  9. void main()
  10. {
  11.     int i, n;
  12.     int *a, *b, *c;
  13. 
    
  14.     printf("How many Elements in each array...\n");
  15.     scanf("%d", &n);
  16.     a = (int *)malloc(n * sizeof(int));
  17.     b = (int *)malloc(n * sizeof(int));
  18.     c = (int *)malloc(n * sizeof(int));
  19.     printf("Enter Elements of First List\n");
  20.     for (i = 0; i < n; i++)
  21.     {
  22.         scanf("%d", a + i);
  23.     }
  24.     printf("Enter Elements of Second List\n");
  25.     for (i = 0; i < n; i++)
  26.     {
  27.         scanf("%d", b + i);
  28.     }
  29.     for (i = 0; i < n; i++)
  30.     {
  31.         *(c + i) = *(a + i) + *(b + i);
  32.     }
  33.     printf("Resultant List is\n");
  34.     for (i = 0; i < n; i++)
  35.     {
  36.         printf("%d\n", *(c + i));
  37.     }
  38. }

 

output:

How many Elements in each array...
5
Enter Elements of First List
23
45
67
12
90
Enter Elements of Second List
87
56
90
45
10
Resultant List is
110
101
157
57
100