Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
C program to dynamically make array and print elements sum
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
take an input and store it to arr[i]
-
for initialize i := 0, when i
sum := sum + arr[i]
return sum
Example
Let us see the following implementation to get better understanding −
#include#include int main(){ int *arr; int n; int sum = 0; scanf("%d", &n); arr = (int*) malloc(n*sizeof(int)); for(int i = 0; i Input
6 9 8 7 2 4 3Output
33
