0

Beginner programmer here can someone please explain to me how this loop works. How can the loop detect the duplicate element in the array? sorry for the simple question.

#include <iostream>


using namespace std;
int main()
{
    int num[5];
    int numSize = sizeof(num) / sizeof(num[0]);


    for(int i = 0; i < numSize; i++)
    {
        cout << "Enter number : ";
        cin >> num[i];

        if(i >= 0)
        {

            for(int j = 0 ; j < numSize; j++)
            {
                if(num[i] == num[j] && (i != j))
                {
                    i--;
                    j++;
                }
            }
        }
    }

    for(int p = 0; p < numSize; p++)
        cout << num[p] << " ";
}
Karl
  • 5
  • 2
  • 4
    This code seems to cause undefined behavior. Namely, `num[j]` for `j>i` is read before it was written. – Daniel Langr Aug 04 '20 at 06:09
  • 1
    Why don't you put print statements or debug it and see what is going on? – karastojko Aug 04 '20 at 06:09
  • The code is bugged, if it works its a lucky accident. – john Aug 04 '20 at 06:12
  • 2
    While it sometimes can be useful to read other peoples code to learn, reading undocumented and uncommented code is *hard*, and sometimes impossible to learn something useful from. Before attempting to check other peoples code (especially people who you can't communicate with) I suggest you learn the basics some other way. Perhaps get and read [some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282), or take a couple of classes. – Some programmer dude Aug 04 '20 at 06:14

1 Answers1

0

Avoid indexing when it is possible. It is not final solution but it may show you right direction.

#include <iostream>
#include <algorithm>

int main()
{
    int num[] = { 0, 5, 6, 8, 0, 2, 5, 8 };
    std::sort(std::begin(num), std::end(num));   
    
    auto it = std::begin(num);        
    while(1) {
        it = std::adjacent_find(it, std::end(num));
        if(it != std::end(num)) {
            std::cout << "Double pairs " << *it << " and " << *(it+1) << std::endl;
            ++it;
        }
        else {
            break;
        }        
    }
    
    return 0;
}

Output:
Double pairs 0 and 0                                                                                                                                                               
Double pairs 5 and 5                                                                                                                                                               
Double pairs 8 and 8 
Amir Kadyrov
  • 1,253
  • 4
  • 9