Write Program to find sum of elements in an array

25 May 2022

Write Program to find sum of elements in an array


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

Description

Get an array as the input from the user and find the sum of the elements.

Input

Enter the size of array

3

Enter the elements of array

5 10 15

Output

30

 

C Program

#include<stdio.h>

int Sum(int arr[], int n)

{

    int sum = 0;

    for(int i = 0; i < n; i++)

        sum = sum + arr[i];

    return sum;

}

int main()

{

    int n;

    printf("Enter the size of array: ");

    scanf("%d",&n);

    int arr[n];

    printf("Enter the elements of array: ");

    for(int i=0;i<n;i++)

    scanf("%d",&arr[i]);

    printf("Sum: %d",Sum(arr, n));;

}

 

C++ Program

#include<iostream>

using namespace std;

int Sum(int arr[], int n)

{

    int sum = 0;

    for(int i = 0; i < n; i++)

        sum = sum + arr[i];

    return sum;

}

int main()

{

    int n;

    cout<<"Enter the size of array: ";

    cin>>n;

    int arr[n];

    cout<<"Enter the elements of array: ";

    for(int i=0;i<n;i++)

    cin>>arr[i];

    cout<<"Sum: "<<Sum(arr, n);

}

 

Java Program

import java.util.Scanner;

 

public class Main

{

   public static void main(String args[])

   {

 

    int n;

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter the size of the array: ");

    n = sc.nextInt();

    int[]arr = new int[n];

    System.out.println("Enter the array elements: ");

    for(int i = 0; i < n; i++)

    {

        arr[i] = sc.nextInt();

    }

       int sum = 0;

 

       for(int i=0; i<arr.length; i++)

       {

         sum = sum + arr[i];

       }

 

       System.out.print("Sum: "+sum);

   }

}

 

Python Program

n = int(input("Enter size of array: "))

arr = []

print("Enter array elements: ")

for i in range(0,n):

                temp = int(input())

                arr.append(temp)

Sum = 0

for i in range(len(arr)):

   Sum = Sum + arr[i]

print("Sum: ",Sum)


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023
Related Articles

Ask Us Anything !