query

//print repeated elements from an array
#include<iostream>
using namespace std;

int main()
{
int p,n;
int a[n],b[n];
int z=0;
cout<<"enter no. of elements in array: "<<endl;
cin>>n;
cout<<"enter elements of array:"<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{
if(j==k)
{
continue;
}
else if(a[j]==a[k])
{
b[z]=a[j];
++z;
break;
}
}
}
cout<<"repeated elements are: "<<endl;
for(p=0;p<z;p++)
{
cout<<b[p];
}
return 0;
}


o/p- segmentation error

Whats wrong in this program?
int a[n],b[n];

What value does n have at this point in the program? This is before you get a value for n from cin, so what value does n have?
thanks got the error, have to get value of 'n' before I declare the array. As 'n' initially has some garbage value.
Am I correct?

one more query in this -
this program gives the repeated digits of the array
how to refine this program in a sense i.e- repeated digits doesnt repeat in output?
Your program works fine. I mean it doesn't give any segmentation error.
Last edited on
It works fine but as you will see in the output that the digits which are repeated appear according to the no. of times they have appeared in the array. I just want to write the singular elements repeated.

e.g.--
o/p window--
file:///home/srijan/Pictures/error.jpg
the output repeats itself for every element that repeats itself as many times it in the array
contactsrijan wrote:
have to get value of 'n' before I declare the array. As 'n' initially has some garbage value. Am I correct?

Partially. The array size must be a constant expression. Your n is a variable of type int, thus the program cannot be compiled as a C++ program:

test.cc: In function ‘int main()’:
test.cc:7: error: ISO C++ forbids variable-size array ‘a’
test.cc:7: error: ISO C++ forbids variable-size array ‘b’


If you need a non-constant array, use vector<int>:

1
2
3
4
5
cout << "enter no. of elements in array: \n";
int n;
cin >> n;
vector<int> a(n);
vector<int> b(n);

Last edited on
Yes, got it.
thanks man..

the output repeats itself for every element that repeats itself as many times it in the array - any suggestions on this end?
suggestions?


Help me out fellows need to get it right ... am trying to do this without using pointers.... all the changes that I make fine tunes it but some other like When entering three similar numbers again it displays twice in fanal output...
What to do?
Last edited on
Topic archived. No new replies allowed.