To find the sum of elements in a given array in C/C++/Java/Python

In C:

We create a loop for a user to enter the elements and then calculate the sum of each element using a loop. Print the elements stored in an array and the sum of each element in an array.

#include <stdio.h>
int main()
{int n,arr[n], sum,i;
sum=0;

printf("enter the length of an array");
scanf("%d",&n);
for (i=0;i<n;i++)
    {printf("enter element of an array");
     scanf("%d",&arr[i]);
     sum=sum+arr[i];
    }
for (i=0; i<n; i++)
    {printf("%d",arr[i]);
    printf(" ");
    }
printf(" \n ");
printf("the sum of elements  %d",sum);
return 0;
}

The Output:

enter the length of an array4

enter element of an array1

enter element of an array2

enter element of an array3

enter element of an array4

1 2 3 4 

 the sum of elements  10

In C++: 

We ask a user to input the array and using a loop, we calculate the sum of the elements in an array.

#include <iostream>
using namespace std;
int main ()
{  int n=7;int arr[7];
   for (int i=0; i<7 ; i++)
      {cout << "Type a number: "; 
       cin >> arr[i]; }
   int sum = 0;
   for(int i = 0; i<7 ; i++)
   {
      sum=sum+arr[i];
   }
   cout<<"The array sum is "<<sum;
   return 0;
}

The output:

Type a number: 1

Type a number: 2

Type a number: 3

Type a number: 4

Type a number: 5

Type a number: 6

Type a number: 7

The array sum is 28

In Python: 

We ask a user to input the length of an array and using a loop, we input the elements as well as calculate the sum of the elements in an array.

a=eval(input("enter an array"))
b=len(a)
c=0
for i in range(0,b):
   c=c+a[i]
print("the array is",a)
print("the sum of array is",c)

The output:

Enter an array:[1,2,3,4,5]

The array is [1,2,3,4,5]

The sum of array is 15

In Java:

We ask a user to input the length of an array and using a loop, we input the elements as well as calculate the sum of the elements in an array.

import java.util.Arrays;
import java.util.Scanner;
public class Sum {
   public static void main(String args[]){
      System.out.println("Enter the required size of the array :: ");
      Scanner s = new Scanner(System.in);
      int size = s.nextInt();
      int array[] = new int [size];
      int sum = 0;
      System.out.println("Enter the elements of the array one by one ");

      for(int i=0; i<size; i++){
         array[i] = s.nextInt();
         sum = sum + array[i];
      }
      System.out.println("Elements of the array are: "+Arrays.toString(array));
      System.out.println("Sum of the elements of the array ::"+sum);
   }
}

The Output:

Enter the required size of the array::

4

Enter the elements of the array one by one

1

4

6

7

Elements of the array are: [1, 4, 6, 7]

Sum of the elements of the array ::18

Time and Space Complexity

Time complexity– o(n) – depends on the number of n elements in an array

Space complexity– o(1) – it will be 1

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *