
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 < 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
- Related Questions & Answers
- Program to print Sum Triangle of an array.
- C Program to print the sum of boundary elements of a matrix
- Adding elements to array to make its sum diverse in JavaScript
- Print the corner elements and their sum in a 2-D matrix in C Program.
- Minimum removals to make array sum even in C++
- Minimum removals to make array sum odd in C++
- C/C++ Program to find the sum of elements in a given array
- C# program to print all distinct elements of a given integer array in C#
- Program to find sum of elements in a given array in C++
- Python program to print the duplicate elements of an array
- Print array elements in alternatively increasing and decreasing order in C++
- C# Program to order array elements
- Program to find number of elements can be removed to make odd and even indexed elements sum equal in Python
- C program to print array of pointers to strings and their address
- Count and Sum of composite elements in an array in C++