Advertisement
GabrielHr00

04. Sum of Two Numbers

Feb 8th, 2025
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.20 KB | None | 0 0
  1. package nestedLoops_Lab;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class SumOfTwoNumbers {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.         int startNumber = Integer.parseInt(scanner.nextLine());
  9.         int stopNumber = Integer.parseInt(scanner.nextLine());
  10.         int magicNumber = Integer.parseInt(scanner.nextLine());
  11.  
  12.         int combinationsCount = 0;
  13.         boolean isMagicNumberFound = false;
  14.  
  15.         for (int x1 = startNumber; x1 <= stopNumber; x1++) {
  16.  
  17.             for (int x2 = startNumber; x2 <= stopNumber; x2++) {
  18.  
  19.                 int result = x1 + x2;
  20.                 combinationsCount++;
  21.  
  22.                 if (result == magicNumber) {
  23.                     System.out.printf("Combination N:%d (%d + %d = %d)",
  24.                             combinationsCount, x1, x2, magicNumber);
  25.                     isMagicNumberFound = true;
  26.                     break;
  27.                 }
  28.             }
  29.  
  30.             if (isMagicNumberFound) {
  31.                 break;
  32.             }
  33.         }
  34.  
  35.         if (!isMagicNumberFound) {
  36.             System.out.printf("%d combinations - neither equals %d", combinationsCount, magicNumber);
  37.         }
  38.     }
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement