frequency

hello every body...i am making a program that counts each number in an array...the code is the following...

#include<iostream.h>
#include<conio.h>
#include<math.h>
main()
{
int x[10]={1,2,3,2,1,3,4,5,4,3};


for(int i=0;i<10;i++)
{
int count=0;

for(int j=0;j<10;j++)
{
if(x[j]==x[i])
{
count=count+1;
}


}

cout<<x[i]<<" comes "<<count<<" times \n ";
}


getch();
}


the problem in the code is this it counts the number again and again...i know what is the mistake but i dont know how to resolve it...please help...thanks
This is what I get when your program runs with the changes shown.

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
#include<iostream>
//#include<conio.h>
//#include<math.h>
int main()
{
int x[10]={1,2,3,2,1,3,4,5,4,3};


for(int i=0;i<10;i++)
{
int count=0;

for(int j=0;j<10;j++)
{
if(x[j]==x[i])
{
count=count+1;
}


}

std::cout<<x[i]<<" comes "<<count<<" times \n ";
}


std::cin.get();
}
/*
1 comes 2 times
2 comes 2 times
3 comes 3 times
2 comes 2 times
1 comes 2 times
3 comes 3 times
4 comes 2 times
5 comes 1 times
4 comes 2 times
3 comes 3 times
*/
If you want to avoid the duplicate results make your i loop start at 1 and end at 5....I think
it diddnt work.....and if it works, i wont be chaning this as changing range of i mean if i change the array, the numbers, then i need to change i accordingly....
use std::count from the header <algortihm>
Try this:-

#include<iostream>

using namespace std;

int main()
{
int x[10]={1,2,3,2,1,3,7,5,74,3};
int y[10][2],i,j,countY=0;
bool matchFound;

for(i=0;i<10;i++)
{
matchFound=false;
y[i][1]=0;
for(j=0;j<countY;j++)
{
if(x[i]==y[j][0])
{
y[j][1]++;
matchFound=true;
break;
}
}
if(matchFound==false)
{
y[countY][0]=x[i];
y[countY][1]++;
countY++;
}
}

for(j=0;j<countY;j++)
cout<<"Count of "<<y[j][0]<<" : "<<y[j][1]<<"\n";

return 0;
}

Let me know if it doesn't work.

P.S - I compiled and ran this program using g++
Topic archived. No new replies allowed.