C program to dynamically make array and print elements sum

CServer Side ProgrammingProgramming

Suppose we have a number n. We shall have to make an array of size n dynamically and take n numbers one by one, then find the sum. To make the array we can use malloc() or calloc() function which is present inside the stdlib.h header file. The value of n is also provided as input through stdin.

So, if the input is like n = 6, and array elements 9, 8, 7, 2, 4, 3, then the output will be 33 because sum of 9 + 8 + 7 + 2 + 4 + 3 = 33.

To solve this, we will follow these steps −

  • sum := 0

  • take one input and store it to n

  • arr := dynamically create an array of size n

  • for initialize i := 0, when i < n, update (increase i by 1), do:

    • take an input and store it to arr[i]

  • for initialize i := 0, when i < n, update (increase i by 1), do:

    • sum := sum + arr[i]

  • return sum

Example

Let us see the following implementation to get better understanding −

#include <stdio.h>
#include <stdlib.h>
int main(){
    int *arr;
    int n;
    int sum = 0;
    scanf("%d", &n);
    arr = (int*) malloc(n*sizeof(int));
    for(int i = 0; i < n; i++){
        scanf("%d", (arr+i));
    }
    for(int i = 0; i < n; i++){
        sum += arr[i];
    }
    printf("%d", sum);
}

Input

6 9 8 7 2 4 3

Output

33
raja
Published on 08-Oct-2021 11:09:20

Advertisements