Find a pair adding up to an exact number

Hi. I'm learning C++ by myself and I have stuck with this problem. Can anyone provide me some idea?

You have a file of 10 integers. Write a program that inputs a number from the keyboard and determines if any pair of the 10 integers in the text file adds up to exactly the number typed in from the keyboard. If so, the program should output the pair of integers. It no pair of integers add ups to the number, then the program should output "No pair found." (Using loop)

I have no idea with the main point. How to use loop to determine a pair that adds up to the input number? This code is the only thing I have finished so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>
#include <fstream>


using namespace std;

int main( )
{
  	int num, input;

 	inputStream.open("list.txt");
 	cout<<"Input a number ";
 	cin>> input;
 	
 	//loop
 	
 	inputStream.close();
 	return 0;
}
Last edited on
subtract the input value from the first value in the list. Search the list for the resuting value.



for example if the user puts in 20, and the file has 1, 5, 7 15, 25, 40, you take user input (20) - first value in list (1) is 19. Search list for 19, its not there. Move to next value (5), 20-5 is 15, search for it, find 15, success.

you can hash the original list to search in O(1) for the computed value.

Last edited on
Well, there are two main parts to the problem.

Forget about the file "list.txt" for now. Imagine your program looked like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>

using namespace std;

int main( )
{
    // values here don't mean anything, just made-up
    int array[10] = {1, 2, 4, 7, 18, 39, 5, 11, 29, 77 };
  
    int input;
    cout << "Input a number ";
    cin >> input;
 
    // now write some code to test if any 
    // two numbers from the array add up to the input number 	

}


That's an outline of what you need to do.

The other part is is simply to use a loop to read 10 numbers from the input file into the array.

edit: corrected syntax error in array initialisation
Last edited on
@jonnin I got your idea but I dont know how to write the code.
@Chervil Sorry, I'm really a beginner. Can you show me how to use the loop in this case?
@Chervil Sorry, I'm really a beginner. Can you show me how to use the loop in this case?

If you're not sure how to read from the file, them here's an example. Reading from the inputStream is very similar to getting input using cin. But I put some checking in, it's always a good idea to verify that reading from the file actually worked.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <fstream>

using namespace std;

int main( )
{
    int array[10] = { 0 };
    
    ifstream inputStream("list.txt");
    if (!inputStream)
    {
        cout << "could not open input file\n";
        return 1;
    }
    
    for (int i=0; i<10; ++i)
    {
        inputStream >> array[i];
    }
    // check everything went ok
    if (!inputStream)
    {
        cout << "error reading 10 numbers from file into array\n";
        return 1;        
    }
    
    
    // for information purposes, see what is in the array
    cout << "numbers stored in array are:\n";
    for (int i=0; i<10; ++i)
    {
        cout << array[i] << "  ";
    }
    cout << '\n';
  
    //----------   now proceed with rest of program  ------------
    
}

If all of this is puzzling to you then you might want to read the tutorial on
Loops http://www.cplusplus.com/doc/tutorial/control/
Arrays http://www.cplusplus.com/doc/tutorial/arrays/
Files http://www.cplusplus.com/doc/tutorial/files/
leave off the complex tweaks and stuff ...

for(i = 0; i < maxarraysize; i++) //max is 10,here, but best to abstract it
{
int diff = array[i] - input;
for(i = 0; i < maxarraysize; i++)
if(diff == array[i])
cout << input << " " << array[i] << endl;
}

which does a brute force search but it should be close to what you needed, though the N*N effort is way overkill.

what do you do if

user = 10,
array has 1,3,5,7,9 ?

5+5 is valid but only 1 copy of 5. What is the desired output? Mine would give the answer as 5 + 5 found...



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <fstream>
#include <set>
using namespace std;

int main()
{
   set<int> values;                                        // sorted set of distinct values read from file
   int target;
   int num, ber;                                           // number bonds to the target

   cout << "Enter a number: ";
   cin  >> target;

   ifstream in( "list.txt" );
   while ( in >> num )                                     // read from file while data still available
   {
      ber = target - num;                                  // the corresponding number bond
      if ( values.find( ber ) != values.end() )            // search for it in the set read so far
      {
         cout << "BINGO!   " << num << " + " << ber;       // if found, great!
         return 0;
      }
      else
      {
         values.insert( num );                             // if not, add to the set of distinct values
      }
   }
   cout << "No pair found";
}


list.txt:
-5    12   -14    7    6
 2   -10    12    8    0



Enter a number: 23
No pair found


Enter a number: -12
BINGO!   2 + -14
I would try to be as less complex as I can. Right now it doesn't affect you so much but in the future, as programs is getting bigger, any complexity might lead you to suffer from errors that are hard to detect later. You can use some programs, such as checkamrx if you need help with it. Just make sure to keep it simple.
Thanks to you guys, I can make the loop like this. However, how should I put cout << "No pair found";?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <fstream>
using namespace std;
int main( )
{
    int array[10] = { 0 },num, input;
    ifstream inputStream("list.txt");

    for (int i=0; i<10; ++i)
        {
        inputStream >> array[i];
        }

    cout << "Input a number. ";
    cin >> input;

    for (int n=0; n<10; n++)
    {
        num=input-array[n];
        for (int m=n+1; m<10; m++)
        {
            if (num==array[m])
                {cout << "The pair collected is "<< array[n] << " and " << array[m]<< endl;
                }
        }
    }

    return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <fstream>

int main()
{
    const int N = 10 ;
    int array[N] = { 0 } ;

    {
        std::ifstream inputStream( "list.txt" );
        for( int i = 0 ; i<N ; ++i ) inputStream >> array[i];
    }

    std::cout << "Input a number. ";
    int input ;
    std::cin >> input;

    for( int i = 0 ; i<N ; ++i )
    {
        const int required_number = input-array[i] ;
        for( int j = i+1; j<10; ++j )
        {
            if( required_number == array[j] )
            {
                std::cout << "The pair collected is "<< array[i]
                          << " and " << array[j] << '\n' ;
                return 0 ; // found a pair; we are done
            }
        }
    }

    // if we reach here, we have failed to find any pair
    std::cout << "No pair found\n" ;
}
I got it. Thank you. I should change the position of return 0;
you can have 2 return 0 statements, one after finding, one after not finding, and that feels correct to ME here.
> and that feels correct to ME here.

An explicit return 0 ; at the end of main is mere verbiage; it does not change anything.
Topic archived. No new replies allowed.