The following program demonstrates how to Find the Sum of Specific Elements of an Array in Java.
In the following program, we have an array that we initialise with numbers. Now we have to find the sum of the array elements on the basis of the following condition:
When a 6 encounters, then look for a subsequent 7. If 7 also appears, then skip all the numbers between 6 and 7 (inclusive) from the sum. For example,
Array = (3, 1, 6, 2, 9, 8, 1, 7, 5, 7), sum=16
Another example, Array = (2, 1, 6, 2, 3), sum=14
Further, Array=(7,1,2,6), sum=16
Also, Array=(6,1,2,8,7), sum=0
public class Exercise8
{
public static void main(String[] args) {
//int[] myarray={10, 3, 6, 1, 2, 7, 9};
// int[] myarray={7, 1, 2, 3, 6};
int[] myarray={1, 6, 4, 7, 9};
System.out.println("Array Elements...");
for(int i=0;i<myarray.length;i++)
{
System.out.print(myarray[i]+"\t");
}
int sum1=0, sum2=0;
boolean found6=false, found7=false;
for(int i=0;i<myarray.length;i++)
{
int x=myarray[i];
if((x!=6) && !found6 && !found7)
{
sum1+=x;
continue;
}
if((x==6) && !found6 && !found7)
{
found6=true;
sum2+=x;
continue;
}
if((x!=6) && found6 && !found7)
{
sum2+=x;
if(x==7) found7=true;
continue;
}
if(found7)
{
sum1+=x;
}
}
if(!found7)
sum1+=sum2;
System.out.println("\nSum = "+sum1);
}
}
Output