-4

Write the code which gets two equal size integer arrays and number of elements as parameters and calculates and displays the sum of parallel elements of both arrays in C language? Size of the array and elements of the array have to be given by the user

#include <stdio.h>
int main()
{
    int n, i;
    printf("Enter size of array \n");
    scanf("%d", &n);

    int arr1[n], arr2[n], sum[n];


    for(i = 0; i < n; i++)
        {
           printf("enter number %d for array 1 ", i+1);
           scanf("%d", &arr1[i]);
        }

     for(i = 0; i < n; i++)
        {
           printf("enter number %d for array 2 ", i+1);
           scanf("%d", &arr2[i]);
        }

     for (i=0; i<n; i++)
        {
            sum[i]=arr1[i]+arr2[i];
        }
 printf("The total is  ");
     for (i=0; i<n; i++)
     printf(" %d " , sum[i]);

return 0;
}


Mesi
  • 13
  • 5
  • What is your question? – kaylum Apr 04 '20 at 05:22
  • @kaylum C code for the above problem – Mesi Apr 04 '20 at 05:23
  • 3
    Stack Overflow is not intended to be a place to ask for code to be written for you. It's meant to help you write your own code. So make an attempt, show your code and ask a specific question about the code or concept that you are having trouble with. – kaylum Apr 04 '20 at 05:28
  • @kaylum thank you for letting me know :), I'm just new here. I just mentioned a code below. – Mesi Apr 04 '20 at 05:31
  • Just call `scanf` to get the number of elements from the user and then use `malloc` to dynamically allocate memory for the array of given size. – kaylum Apr 04 '20 at 05:38
  • @kaylum I mean I want to let the user decide the number of elements in the array, not just 10 elements :( – Mesi Apr 04 '20 at 05:43
  • I know. `scanf` to ask the user for number of elements. And then `malloc` to allocate memory for the array based on the user's input. I will search for an answer for you or write one if I can't find. – kaylum Apr 04 '20 at 05:43
  • This has what you need: [Size of an Array by user](https://stackoverflow.com/questions/32364521/size-of-an-array-by-user) – kaylum Apr 04 '20 at 05:48
  • @kaylum appreciate your help. – Mesi Apr 04 '20 at 12:59

1 Answers1

1

this way you are taking size of array from user and define an array with that size , though it's is possible and might work in many compilers ,has many risk. Check this answer for more information here

the best way to do so , is to scan that size and then allocate memory for it.

    int n;
    scanf("%d", &n);
    int* arr1, * arr2, * sum;
    arr1 = malloc(n * sizeof(int));
    arr2 = malloc(n * sizeof(int));
    sum = malloc(n * sizeof(int));


hanie
  • 1,863
  • 2
  • 7
  • 19