Click here to Skip to main content
15,913,467 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
import java.util.Scanner;
import java.util.*;
public class B_MentalWarmUp {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //nth element input
        System.out.print("Enter the Trio of Elements: ");
        int n = sc.nextInt();
        //Initialize array
        int [] myArray= { 10, 20, 10, 40, 50, 60, 70};
        int sum = 0;
        //Loop through the array to calculate sum of elements  
        for(int i = 0; i < myArray.length; i++)
        {
            n = myArray[i];
            sum = sum + n;
        }
        System.out.println("Sum of all the elements of an array: " + sum);
        // If we reach here, then it is out of range
        {
        System.out.println("Your input is out of range, TRY AGAIN!");
        return;
    }
}
}



Here is the instruction:
Write a Java program that finds a trio of elements (i.e. indices of the three numbers) from a given array A whose sum equals a specific target number B as the output. If the user puts a number that is not within the size of the array. The system should respond "Your input is out of range, TRY AGAIN


What I have tried:

I tried to code one by one the index so that when it is called/input it will will be added. But that made it only difficult and it also didn't work
Posted
Updated 6-Feb-22 21:12pm

1 solution

A brute force approach would use three loops (pseudocode, say N is the length of the array and S the target number):
success = false
i=0,..N-3
 j=i+1,..N-2
  k=j+1,..,N-1
   if a[i]+a[j]+a[k] = S then success = true, exit all the loops
 
Share this answer
 
Comments
Myth23192810 7-Feb-22 3:28am    
can you correct my code? please
CPallini 7-Feb-22 3:37am    
It is not difficult, just add the needed loops. Try to make the changes, then I could try to fix them for you.
Myth23192810 7-Feb-22 3:41am    
It's difficult for me cause we just started the basics and I couldn't understand it
Myth23192810 7-Feb-22 3:45am    
also pseudocode wasn't taught to us
CPallini 7-Feb-22 3:47am    
https://en.wikipedia.org/wiki/Pseudocode
The actual code would be very similar, e.g.
for(int i = 0; i < myArray.length-2; i++)
  for(int j = i+1; j < myArray.length-1; j++)
    // ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900