Undeclared Identifier error for TwoSum C++ solution

Viewed 28

I am trying to create my own solution for TwoSum leetcode problem. I am assigning the array with random numbers in between 0, 20. I'm trying to write a function to find all unique number pairs of the array that adds up to the target number. Then I just want to print the pairs and their indices.

I am getting an undeclared error when I try to add the index of j to my array but I dont know why.

Here is my code, I appreciate any help or advice.

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
 
int getPairsCount(int arr[], int n, int sum)
{
  int indices[10];
     
    // Consider all possible pairs and check their sums
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            if (arr[i] + arr[j] == sum)
                indices[0] = i;
                indices[1] = j; //error is caused by this line
 
    cout << indices;
}

int main()
{
   int sz = 20;
   
   int randArray[sz];
   for(int i=0;i<sz;i++)
      randArray[i]=rand()%20;  //Generate numbers between 0 to 20
  
  int n = sizeof(randArray) / sizeof(randArray[0]);
  int sum = 6;
   
    cout << "The indices that add up to the target sum is: " << endl;
    cout << getPairsCount(randArray, n, sum) << endl;    
    
    
    return 0;
 
}```
1 Answers

Here is your code with some brackets:

for (int i = 0; i < n; i++)
{
    for (int j = i + 1; j < n; j++)
    {
        if (arr[i] + arr[j] == sum)
        {
            indices[0] = i;
        }
    }
    indices[1] = j; //error is caused by this line
}

See the issue? You've indented indices[1] = j; which makes you think it's part of the "for j" loop, but it isn't. In older versions of the C++ this would have worked.

Related