daily pastebin goal
9%
SHARE
TWEET

Untitled

a guest Oct 12th, 2017 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Sum all elements of array in Java
  2. import java.util.Scanner;
  3. class test
  4. {
  5. public static void main(String ar[])
  6. {    
  7.     Scanner scan = new Scanner(System.in);
  8.     System.out.println("Enter the size of array:");
  9.     int size = scan.nextInt();
  10.     int array[] = new int[size];
  11.     for(int i=0;i<array.length;i++)
  12.     {
  13.         System.out.println("Enter "+i+" element:");
  14.         array[i] = scan.nextInt();
  15.     }
  16.     //To sum: As zero is additive constant, initialize a variable ans to 0 and keep on adding all the array values to this ans variable.
  17.     int ans=0;
  18.     for(int i=0;i<array.length;i++)
  19.     {
  20.         ans = ans+array[i];
  21.     }
  22.     System.out.println("Sum is: "+ans);
  23. }
  24. }
  25. /* OUTPUT
  26. Enter the size of array:
  27. 5
  28. Enter 0 element:
  29. 10
  30. Enter 1 element:
  31. 20
  32. Enter 2 element:
  33. 30
  34. Enter 3 element:
  35. 40
  36. Enter 4 element:
  37. 50
  38. Sum is: 150
  39. */
RAW Paste Data
Top