As I understand it, your task on the ability to work with arrays and loops and to standard containers and algorithms is not yet reached.
The program may look like this. Only in the presented demo program, I do not enter the elements of the array from the keyboard. and generate their random values. You yourself will have to change the program so. so that the user sets the dimension of the array himself, so that the array is allocated dynamically, and then the user enters the elements of the array. Don't forget to delete this array at the end of the program with the operator delete []
#include <iostream> #include <cstdlib> #include <ctime> int main() { const size_t N = 10; int a[N]; std::srand( ( unsigned int )std::time( nullptr ) ); for ( auto &x : a ) x = std::rand() % N; for ( auto x : a ) std::cout << x << ' '; std::cout << std::endl; for ( size_t i = 0; i < N; i++ ) { size_t j = 0; while ( j != i && a[j] != a[i] ) j++; if ( j++ == i ) { while ( j < N && a[j] != a[i] ) j++; if ( j != N ) std::cout << a[i] << ' '; } } std::cout << std::endl; return 0; }
The output of the program may look something like this.
1 2 9 5 0 5 2 4 1 8 1 2 5
The principle of operation is as follows. If there is another element of the array with the index i , then we look at it we had already dealt with its value, considering the elements in the range [0, i) . If you already had a deal with its value, then just skip it. Otherwise, we look if there is another element with the same value in the range [i+1, N) . If so, then output it to the console.
If it is allowed to change the order of the elements in the array after they have been entered, then you can sort the array using the standard std::sort algorithm as follows
std::sort( a, a + N );
include pre-header
#include <algorithm>
and then output successively the elements that coincide in value with the adjacent elements. for example
#include <iostream> #include <cstdlib> #include <ctime> #include <algorithm> int main() { const size_t N = 10; int a[N]; std::srand( ( unsigned int )std::time( nullptr ) ); for ( auto &x : a ) x = std::rand() % N; for ( auto x : a ) std::cout << x << ' '; std::cout << std::endl; std::sort( a, a + N ); for ( size_t i = 0; i < N; ) { size_t j = i + 1; while ( j < N && a[i] == a[j] ) j++; if ( j - i > 1 ) { std::cout << a[i] << ' '; } i = j; } std::cout << std::endl; return 0; }
As for the code you have presented, at least this cycle
for (int i = 0; i < N; i++) { if (p[i] == p[i + 1]||p[i]==p[i+i]) { mas[i] = p[i]; } }
leads to indefinite program behavior, as in the condition
if (p[i] == p[i + 1]||p[i]==p[i+i])
which, moreover, does not make sense, going beyond the array boundary, addressed by the pointer p , with i equal to N-1 , and also not all the elements of the array addressed by the pointer mas will be assigned values. And this array was not initially initialized, and therefore contains undefined values ..