Write a program to find the sum of the array elements.
Input: [1, 6, 4]
Output: 11
ApproachJava
public class ArraySum {public static void main(String[] args) {int arr[] = { 1, 6, 4 };int sum = simpleArraySum(arr);System.out.println("Sum of the array "+sum);}static int simpleArraySum(int[] ar) {int sum = 0;for (int i : ar) {sum += i;}return sum;}}// Time Complexity: O(n)
C++
#include <bits/stdc++.h>using namespace std;int main(){vector<int> arr = {1, 6, 4};int sum = 0;for (int i = 0; i < arr.size(); i++){sum += arr[i];}cout << sum << "\n";return 0;}
C
#include <stdio.h>int main(){int n = 3, i, sum = 0;int arr[] = {1, 6, 4};for (i = 0; i < n; i++){sum += arr[i];}printf("%d\n", sum);return 0;}
No comments:
Post a Comment