I can't make it so that I can input data

I need to make a program so that i input 2 numbers then on the next line I input a line of number that is separated by spaces and find the pair of numbers that add up to the said 2 number at the beginning (the pairs must be unique)
example input
4 5
1 3 5 2 -1
and the output will be
2
since 1+3=4 5+(-1)=4
could any of you please give detailed instructions My English isn't that good and I have hard time following written instructions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 #include <bits/stdc++.h> 
using namespace std; 
int getPairsCount(int arr[], int n, int sum) 
{ 
    int count = 0; 
    for (int i=0; i<n; i++) 
        for (int j=i+1; j<n; j++) 
            if (arr[i]+arr[j] == sum) 
                count++; 
  
    return count; 
} 
int main() 
{ 
    int arr[] = {1, 5, 7, -1, 5} ; 
    int n = sizeof(arr)/sizeof(arr[0]); 
    int sum = 6; 
    cout << "Count of pairs is " 
         << getPairsCount(arr, n, sum); 
    return 0; 
} 
Last edited on
The first 2 numbers you can input like this:
1
2
int num1, num2;
cin >> num1 >> num2;

The second line you can read like this:
1
2
3
4
5
6
7
int num, index=0;
while (cin >> num)
{
   // store num in array[index];
   ++index;
}
// now you call the function getPairsCount and print its result 
I guess you are asking why your output is 3 not 2, right?

Well, the inner loop (line 7) is wrong. Remove it.

Since you need to calculate arr[i]+arr[i + 1] the loop needs to be for (int i=0; i<n - 1; i++) // Note - 1

Further more: you need to skip one element (i.e. i++) when you found a pair.
Could you please apply it to my code I have really hard to figuring out how thing should fit together especially when it comes to word instructions.
Actually, I was think about just consecutive pairs. But I see that all kinds of pair need to be found. Hence you need the loop. See:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int getPairsCount(int arr[], int n, int sum) 
{ 
    int count = 0; 
    for (int i=0; i<n - 1; i++)  // Note -1
        for (int j=i+1; j<n; j++)
        {
            if (arr[i]+arr[j] == sum) 
            {
                std::swap(arr[i + 1], arr[j]); // This is a trick to 'remove' the found pairs
                ++i; // Skip the paired value
                count++; 
                break; // The inner loop ends when a pair was found
            }
        }
  
    return count; 
}
Hello Nolancolin,


Sorry I came across this late.

Here is an a possibility worth considering:
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
41
42
43
44
45
46
47
48
49
#include <algorithm>
#include <iostream>

//using namespace std;  // <--- Best not to use.
// The most recent post that is worth reading. http://www.cplusplus.com/forum/beginner/258335/
using std::cin;
using std::cout;
using std::endl;
//using std::string;

constexpr int MAX_ARRAY_SIZE{ 5 };

int getPairsCount(int (&arr)[MAX_ARRAY_SIZE], const int MAX_ARRAY_SIZE, const int sum)
{
	int count = 0;

	for (int index = 0; index < MAX_ARRAY_SIZE - 1; index++)
		for (int j = index + 1; j < MAX_ARRAY_SIZE; j++)
		{
			if (arr[index] + arr[j] == sum)
			{
				std::swap(arr[index], arr[j]); // This is a trick to 'remove' the found pairs
				//++index; // Skip the paired value
				count++;
				break; // The inner loop ends when a pair was found
			}
		}

	return count;
}

int main()
{

	int arr[MAX_ARRAY_SIZE]{ 1, 5, 7, -1, 5 };
	//int n = sizeof(arr) / sizeof(arr[0]);  // <--- Call it "arraySize" or anything other then just "n". Can be avoided with "MAX_ARRAY_SIZE".
	int sum = 6;

	//for (size_t index = 0; index < MAX_ARRAY_SIZE; index++)  // <--- Commented out for testing. Otherwise it would overwrite the initialized array.
	//{
	//	std::cout << ' ' << " Enter number " << index + 1 << ": ";
	//	std::cin >> arr[index];
	//}

	cout << "\n\n Count of pairs is "
		<< getPairsCount(arr, MAX_ARRAY_SIZE, sum) << endl;

	return 0;  // <--- Not required, but makes a good break point.
}

The only part of coder777's code I had a problem with is the "++i". This skipped to many elements of the array and returned a count 1 less than it should. I do like the idea of swapping what matched to avoid counting it a second time.

I hope the changes I made will give you a better idea on using what you already have. Also notice how a good variable name makes the code easier to follow.

Andy
@Handy Andy I love the improvements you did for my code. But sadly it didn't answer my original problem being that I can't input any user data such as the array or the sum so I would really appreciate it if you could help me with that issue.
Last edited on
Hello ZZEZ73,

1
2
3
4
5
6
7
8
9
10
11
12
int sum{};

// Prompt for inputting "sum".
// std::cin >> sum;

std::cout<<'\n';  // <--- A blank line before the for loop runs.

for (size_t index = 0; index < MAX_ARRAY_SIZE; index++)  // <--- Commented out for testing. Otherwise it would overwrite the initialized array.
{
	std::cout << ' ' << " Enter number " << index + 1 << ": ";
	std::cin >> arr[index];
}

For line 3 you can word this any way that you like, but be accurate in what you need with the wording. It is a simple "cout" statement.

The for loop handles the input for the array.

Since the array was initialized commenting out the for loop allows you to test the rest of the program without having to input numbers every time you run the program. Just a little trick you can do once you know the input is working.

I just noticed that I passed the array by reference in the function. This is not necessary, but OK if you leave it. I did this when debugging the program, so I could see what happens to the whole array.

Andy
Last edited on
Handy Andy wrote:
This skipped to many elements of the array and returned a count 1 less than it should.
Nope, ++i is necessary. Otherwise the result of
4 5
1 3 5 2 -1
would be 3 not 2 as required because it would count the numbers 3 and 2 as a pair as well.

This:
1
2
3
constexpr int MAX_ARRAY_SIZE{ 5 }; // As a constant

int getPairsCount(int (&arr)[MAX_ARRAY_SIZE], const int MAX_ARRAY_SIZE, const int sum) // Parameter and constant? 
isn't the best idea.
@coder777,

coder777 wrote:

This:
1
2
3
constexpr int MAX_ARRAY_SIZE{ 5 }; // As a constant

int getPairsCount(int (&arr)[MAX_ARRAY_SIZE], const int MAX_ARRAY_SIZE, const int sum) // Parameter and constant?  


isn't the best idea.

Instead of telling telling me it "isn't the best idea", tell me what I did wrong or what is better. Sometimes I use what works even if it is not the best. And I did say that passing the array by reference is what I did for debugging the program. I did not mean to leave that part.

Maybe I am misunderstanding something when it comes to the result expected. I was believing it should be 3, but using the "++i" only returned 2. This could be my misunderstanding. And maybe I could have explained it better. Sorry.

Andy
What I mean with "not the best idea" is having the same name i.e. MAX_ARRAY_SIZE twice in the parameter list of getPairsCount(...) with different meaning. int (&arr)[MAX_ARRAY_SIZE] and const int MAX_ARRAY_SIZE. That's confusing. So what I'm suggest would be e.g.:

int getPairsCount(int (&arr)[MAX_ARRAY_SIZE], const int used_size, const int sum) // Note: used_size instead of MAX_ARRAY_SIZE

Maybe I am misunderstanding something when it comes to the result expected. I was believing it should be 3, but using the "++i" only returned 2.
Yes, see op:
example input
4 5
1 3 5 2 -1
and the output will be
2 <-----------------------------
since 1+3=4 5+(-1)=4
But the output would be 3 when you omit ++i
Last edited on
@coder777,

Thank you. It is better to know what I did wrong so I know what to fix and watch out for.

For the function parameters I missed that one completely. I did not mean to be confusing. What I should have done is int getPairsCount(int arr{], const int sum) and make use of the global variable "MAX_ARRAY_SIZE". Which is what I was think of in the beginning.

The second part it was my misunderstanding. Somewhere I thought the final answer should be 3 and it kept coming up 2.

I am starting to better understand your code now.

Andy
> What I should have done is int getPairsCount(int arr{], const int sum)
> and make use of the global variable "MAX_ARRAY_SIZE"
please don't.
MAX_ARRAY_SIZE seems to mean .capacity(), not .size()
using a parameter is more generic and flexible than a global
int getPairsCount(int array[], int size, int sum);


@OP:
http://cplusplus.com/forum/beginner/269140/#msg1158144
¿what's the problem with that?
Topic archived. No new replies allowed.