Given an array of integers, find the sum of its elements.
For example, if the array ar = [1, 2, 3], 1 + 2 + 3 = 6, so return 6.
Function Description
Complete the simpleArraySum function in the editor below. It must return the sum of the array elements as an integer.
simpleArraySum has the following parameter(s):
- ar: an array of integers
Input Format
The first line contains an integer, n, denoting the size of the array.
The second line contains n space-separated integers representing the array’s elements.
Constraints
0 < n, arr[i] < 1000
Output Format
Print the sum of the array’s elements as a single integer.
Sample Input
6
1 2 3 4 10 11
Sample Output 31
ExplanationWe print the sum of the array’s elements: 1 + 2 + 3 + 4 + 10 + 11 = 3
Solution:
Code in C
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define N 1000
int main() {
int x[N],n,i,t;
scanf("%d",&n);
for(i=0;i<n;i++)
if(i==0)
{scanf("%d",&x[i]);t=x[i];}
else
if(getchar()==' ')
{scanf("%d",&x[i]);t=t+x[i];}
printf("%d",t);
return 0;
}
Code in C++
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
long long sum = 0, x;
while (n--) {
cin >> x;
sum += x;
}
cout << sum << endl;
return 0;
}
Tags:
Advanced
Algorithms
Arrays
C
C++
Data Structures
hacker solution
HackerRank
Java
Linked List
Miscellaneous
python
Queues
Recursion
Search
Sorting
String Manipulation
Warm-Up Challenges