Subtract Elements in Array in Java

An example code on subtracting elements in array in Java in decreasing order in 3 main steps. This simple logic can also be used on any programming language.


Subtract Elements




import java.util.*;
class SubArray
{
public static void main(String args[])
{


// Create Scanner object for taking input from cmd
Scanner s=new Scanner(System.in);


// Read no.of elements for array and store it in n
int n=s.nextInt();


// Create array of n elements
int[] a=new int[n];


// Loop n times
for(int i=0;i<a.length;i++)
{

// Take input from user and store in each element
a[i]=s.nextInt();

}


// Modify the array, arrange it in increasing order
Arrays.sort(a);


// Initialize sub value to 0
int sub=0;


// Loop from end to start (decreasing order)
for(int i=a.length-1;i>=0;i--)
{


// Subtract old value from new value
sub=sub-a[i];

// For the first time, the value is -ve so make it +ve
if(i==(a.length-1))
// To do that, multiply with -1
sub=-1*sub;

// Print every element in array in decreasing order
System.out.println("array "+a[i]);


}


// Print the result
System.out.println("Difference of all elements in array in decreasing order "+sub);


}


}


Sample Output



5
5
4
3
8
1
array 8
array 5
array 4
array 3
array 1
Difference of all elements in array in decreasing order -5

Analysis


Loop from end to start: So that i could arrange those elements in decreasing order as the Arrays.sort() was called previously, all the elements in the array are arranged in increasing order.

n=5, sub=0, a[0]=5, a[1]=4, a[2]=3, a[3]=8, a[4]=1 (before sorting). In increasing order, a[0]=1, a[1]=3, a[2]=4, a[3]=5, a[4]=8 (after Arrays.sort(a))

sub=sub-a[i]:

In decreasing order, i is initially equal to 4, so

0=0-8 = -8 => sub=-8

i==a.length-1 => i==4? true -> sub= -1*sub => -8=-1*-8 = 8 => sub=8

8=8-5=3 => sub=3

3=3-4=-1 => sub=-1

-1=-1-3=-4 => sub=-4

-4=-4-1=-5 => sub=-5

-5 will be printed. The if condition is satisfied for the first time only. Still more efficient logic is appreciated in the comments.
Also see my other posts on Adding elements in array in Java and sorting array elements in increasing order in Java

No comments: