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 simple Array Sum function with the following parameter(s):
- ar[n] an array of integers
Returns
- int: the sum of the array elements
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 elements of the array.
Constraints
0 < n, ar[i] <= 1000
Sample Input
STDIN Function
----- --------
6 ar[] size n = 6
1 2 3 4 10 11 ar = [1, 2, 3, 4, 10, 11]
Sample Output
31
Explanation
Print the sum of the array's elements: 1 + 2 + 3 + 4 + 10 + 11 = 31
HackerRank Simple Array Sum Solution in C#
using System; using System.Collections.Generic; using System.IO; class Solution { static void Main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */ Console.WriteLine( ReadArray()); Console.ReadLine(); } static int ReadArray() { int sum = 0; string a; int count; string[] data; count = Convert.ToInt32(Console.ReadLine()); a = Console.ReadLine(); data = a.Split(' '); for (int i = 0; i < data.Length; i++) { if (data[i] != "") { sum += Convert.ToInt32(data[i]); } } return sum; } }
0 Comments