Given an array of integers, find the sum of its elements.
Write a program to find the sum of the array elements.
Write a program to find the sum of the array elements.
Example:
Input: n=6, arr[n]={1,2,3,4,10,11}
Output: 31
Approach
Java
public class SimpleArraySum {public static void main(String[] args) {int arr[] = { 1, 2, 3, 4, 10, 11 };System.out.println(simpleArraySum(arr));}static int simpleArraySum(int[] arr) {int n = arr.length;int sum = 0;for (int i = 0; i < n; i++) {sum += arr[i];}return sum;}}
C++
#include <bits/stdc++.h>using namespace std;int main(){int n = 6;int arr[n] = {1, 2, 3, 4, 10, 11};int sum = 0;for (int i = 0; i < n; i++){sum += arr[i];}cout << sum << "\n";return 0;}
No comments:
Post a Comment