For loop with boolean flag variable won't differentiate

Viewed 64

I need the output for b = a[i] + a[j] if any part of the statement is true, to be a set of numbers ex: (2, 5) that add up to b and not spit out anything else. Then if no part of it is true, the output should be "not found." listed only once. I can't seem to figure out what I'm missing.

'''

    #include<iostream>

    using namespace std;

    int main() {

      int a[10];
      int b;
      int i = 0, j = 0;
      bool pair;

      cout<<"Enter 10 unique integers: ";
      cin>>a[0]; cin>>a[1]; cin>>a[2]; cin>>a[3]; cin>>a[4]; cin>>a[5]; cin>>a[6]; cin>>a[7]; cin>>a[8]; cin>>a[9];

      cout<<"Enter an integer: ";
      cin>>b;

      for (int i = 0; i < 10; i++){
        for (int j = 0; j < 10; j++){
              if (b==(a[i]+a[j]) && a[i] < a[j] && a[i] != a[j]){
                pair = true;
                cout<<"("<<a[i]<<", "<<a[j]<<")\n";
              }
            }      
          }
      if (b!=a[i]+a[j]) {
        pair = false;
        cout<<"not found.\n";  
      }
  

    return 0;
    }

'''

1 Answers

The issue is that you are not using the pair variable to determine if a pair was not found.

The following code shows the usage of pair:

#include<iostream>

int main() 
{
  int a[10];
  int b;
  bool pair = false; // Assume we haven't found a pair
  for (int i = 0; i < 10; ++i) 
     std::cin>>a[i];
  std::cin>>b;
      
  for (int i = 0; i < 10; i++)
  {
     for (int j = 0; j < 10; j++)
     {
        if (b==(a[i]+a[j]) && a[i] < a[j] && a[i] != a[j])
        {
          pair = true; // Found a pair
          std::cout<<"("<<a[i]<<", "<<a[j]<<")\n";
        }
      }      
   }

   if (!pair) // Pair was not found
   {
      std::cout<<"not found.\n";  
   }
 }

Input:
    1 2 3 4 5 6 7 8 9 10 1
Output:
    not found.

Input: 
    1 2 3 4 5 6 7 8 9 10 6
Output:
    (1, 5)
    (2, 4)

Note that all that was done was to check the value of pair to determine if the "not found" message is printed.

Related