You are here : Home / Core Java Tutorials / Interview Programs (beginner to advanced) in java / Level1 programs for (beginner)
In this core java programming tutorial we will Find set of two consecutive numbers who have highest sum and their index as well in java.
Example 1 in java>
Input > { 1, 9, 8, 3, 6, 9, 9, 5, 4, 9 };
Output > numbers= 9,9 and index=5,6
Example 2 in java>
Input > { 1, 5, 8, 3, 6, 8, 7, 5, 4, 9 };
Output > numbers= 8,7 and index=5,6
Example 3 in java>
Input > { 1, 2, 8, 3, 6, 1, 7, 5, 4, 7 };
Output > numbers= 7,5 and index=6,7
Program/ example to Find set of two consecutive numbers who have highest sum and their index as well in java >
public class FindSetOfTwoConsecutiveNumbersWithHighestSum {
public static void main(String[] args) {
int ar[] = { 1, 9, 8, 3, 6, 9, 9, 5, 4, 9 };
//int ar[] = { 1, 5, 8, 3, 6, 8, 7, 5, 4, 9 }; //Test array
//int ar[] = { 1, 2, 8, 3, 6, 1, 7, 5, 4, 7 }; //Test array
findSetOfNumber(ar);
}
static void findSetOfNumber(int ar[]) {
int sum = 0;
int maxSum = 0;
int temp1 = 0,
temp2 = 0;
for (int i = 1; i < ar.length; i++) {
sum = ar[i - 1] + ar[i];
if (sum > maxSum) {
maxSum = sum;
temp1 = i - 1;
temp2 = i;
}
}
System.out.println("numbers= "
+ ar[temp1] + "," + ar[temp2] + " & index=" + temp1 + ", " + temp2 );
}
}
/*OUTPUT
numbers= 9,9 & index=5, 6
*/
|
So in this core java programming tutorial we Found set of two consecutive numbers who have highest sum and their index as well.
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
Related >
Labels:
Core Java
Level1 programs (beginners)