473,670 Members | 2,425 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

write a program to count occurence of each element in an array

Hello frends i am learning c language, I want to make a program which
count occurence of each element in an array .I write following code
for it but ity is not giving me desired result.pls help me.
#include<stdio. h>
#include<conio. h>
void main()
{
int A[10],f,a,b,c;
printf("enter 10 elements");
for(a=0;a<=9;a+ +)
scanf("%d",&A[a]);
for(a=0;a<=9;a+ +)
{
f=0;
c=0;
for(b=0;b<9;b++ )
{
if(A[a]==A[b])
{
f=1;
break;
}
}
if(f==0)
{
for(b=a;b<=9;b+ +)
{
if (A[a]==A[b])
c++;
}
printf("%d=%d\n ",A[a],c);
}
}
getch();
}
Jun 27 '08 #1
4 16274
sahil wrote:
Hello frends i am learning c language,
Consider comp.lang.c.
I want to make a program which
count occurence of each element in an array .I write following code
for it but ity is not giving me desired result.pls help me.
#include<stdio. h>
#include<conio. h>
void main()
{
int A[10],f,a,b,c;
printf("enter 10 elements");
for(a=0;a<=9;a+ +)
scanf("%d",&A[a]);
for(a=0;a<=9;a+ +)
{
f=0;
c=0;
for(b=0;b<9;b++ )
{
if(A[a]==A[b])
{
f=1;
break;
}
}
if(f==0)
{
for(b=a;b<=9;b+ +)
{
if (A[a]==A[b])
c++;
}
printf("%d=%d\n ",A[a],c);
}
}
getch();
}
Really: consider comp.lang.c.
Best

Kai-Uwe Bux
Jun 27 '08 #2
"sahil" wrote:
Hello frends i am learning c language, I want to make a program which
count occurence of each element in an array .
What does it *mean* to count occurrence of each element in an array?

I don't know what it looks like on your end but by the time it gets to me
the parenthesizing is a nightmare. After parenthesizing, and not having the
foggiest notion of what this program should do, I made the observation
embedded later.
/I write following code
for it but ity is not giving me desired result.pls help me.
#include<stdio. h>
#include<conio. h>
Don't use non-standard <conio.hif you don't need it. This program does
not need it. Replace getch() with getchar().
void main()
That will not work with a lot of comiplers. use int main()
{
int A[10],f,a,b,c;
printf("enter 10 elements");
for(a=0;a<=9;a+ +)
scanf("%d",&A[a]);
for(a=0;a<=9;a+ +)
{
f=0;
c=0;
for(b=0;b<9;b++ )
{
if(A[a]==A[b])
How can that test ever fail? The very first iteration checks to see if A[0]
== A[0] , the loop is exited and the program is exited. End of story.
{
f=1;
break;
}
}
if(f==0)
{
for(b=a;b<=9;b+ +)
{
if (A[a]==A[b])
c++;
}
printf("%d=%d\n ",A[a],c);
}
}
getch();
}

Jun 27 '08 #3
sahil <ja*********@gm ail.comwrites:
Hello frends i am learning c language, I want to make a program which
count occurence of each element in an array .I write following code
for it but ity is not giving me desired result.pls help me.
So, let's take an example.

You have something like:

typedef int element_type;
typedef struct
unsigned int size;
element_type elements[];
} element_vector;

/* element_vector data={9,{1,2,3, 1,2,3,1,2,1}}; */

and you want to get something like:

typedef struct {
element_type element;
unsigned int count;
} unique_element;
typedef struct {
unsigned int size;
unique_element elements[];
} unique_element_ vector;

/* unique_element_ vector counts[]={3,{{1,4},{2,3 },{3,2}}}; */
This will be a simple iterative processus.

Assume that you have processed data[] from 0 to i-1, and therefore
you have a vector counts filled from 0 to number_of_uniqu e_elements-1
with unique elements, and their counts.

The iteration step will consist in processing data[i]. You have
basically two cases: either data[i] is already in counts[], then you
will have to find where, and increment counts[w].count, or it is not,
and then you will have to add it to counts. This is an alternative
processus:

unsigned int w=findInUniqueE lements(counts, data.elements[i]);
if(w<counts.siz e){
/* already in */
counts.elements[w].count++;
}else{
/* insert the first one */
w=counts.size;
counts.size++;
counts.elements[w].element=data.e lements[i];
counts.elements[w].count=1;
}

and finally we increment the index:

i++;
Now the question is what will be the stop condition of this loop.
Obviously, when we've processed all the data, that is, the stop
condition is:

i>=data.size
Finally, what will be the initial conditions? When we've not
processed anything, and therefore the counts vector is empty:

i=0;
counts.size=0;

Now, since you've not specified any limit for the vector sizes, and
we're programming in C, we will have to allocate them space for the
elements dynamically, and therefore use pointers:
typedef int element_type;
typedef struct
unsigned int size;
element_type* elements;
} element_vector;

typedef struct {
element_type element;
unsigned int count;
} unique_element;
typedef struct {
unsigned int size;
unique_element* elements;
} unique_element_ vector;
The maximum number of unique elements is actually the number of input
elements, so we can preallocate this space:

counts.elements =malloc(data.si ze * sizeof(counts.e lements[0]));
And finally we can wrap the iterative processus up:

initialization
while(not(stop_ condition)){
iteration;
}

which gives the following function:

unique_element_ vector* countElements(e lement_vector* data){
unique_element_ vector* counts=check_ma lloc_result(mal loc(sizeof(uniq ue_element_vect or)));
unsigned int i=;
counts->size=0;
counts->elements=check _malloc_result( malloc(data.siz e * sizeof(counts.e lements[0])));
while(not(i>=da ta->size)){
unsigned int w=findInUniqueE lements(counts, data->elements[i]);
if(w<counts->size){
/* already in */
counts->elements[w].count++;
}else{
/* insert the first one */
w=counts->size;
counts->size++;
counts->elements[w].element=data->elements[i];
counts->elements[w].count=1;
}
}
return(counts);
}

Of course, now you have to implement

unsigned int findInUniqueEle ments(unique_el ement_vector* counts,element_ type element);

but this is a simplier problem.

--
__Pascal Bourguignon__
Jun 27 '08 #4
In article <01dfc185-fb73-472d-ab7f-246ada526127
@u36g2000prf.go oglegroups.com> , ja*********@gma il.com says...
Hello frends i am learning c language, I want to make a program which
count occurence of each element in an array .I write following code
for it but ity is not giving me desired result.pls help me.
Since you're posting in comp.lang.c++, I'm going to guess that a
solution in C++ is usable:

#include <iostream>
#include <vector>
#include <map>

typedef std::pair<int, intp;

// Cheating...
namespace std {
std::ostream &operator<<(std ::ostream &os, p const &data) {
return os << data.first << "\t" << data.second;
}
}

int main() {
std::vector<int A;
std::cout << "Enter elements";

std::copy(std:: istream_iterato r<int>(std::cin ),
std::istream_it erator<int>(),
std::back_inser ter(A));

std::map<int, intcounts;

for (int i=0; i<A.size(); i++)
++counts[A[i]];

std::cout << "Counts:\n" ;

std::copy(count s.begin(), counts.end(),
std::ostream_it erator<p>(std:: cout, "\n"));
return 0;
}

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3932
by: Roland | last post by:
hi all having designed my schema to use repeating groups of elements, I found that some applications (eg. Microsoft InfoPath) refused to recognised that element as a repeating element. I subsequently found that out of the three possible ways (that I know of) of declaring repeating elements in xsd, only one of these was understood:
6
1953
by: Buck Rogers | last post by:
Hi guys! Love your work! The below program is from K&R2, p22. ================================= #include <stdio.h> /* count digits, white space, others */ main() {
2
3982
by: RadiationX | last post by:
How does this program work? // fig06_07.c -- COP2220 Example -- 040209 (sjd) // Student poll program #include <stdio.h> #include <stdlib.h> #define RESPONSE_SIZE 40 // number of survey responses
2
3500
by: pchahar | last post by:
Write a program to process a text file. The program will determine how many unique words there are in the text file that begin with each letter of the alphabet. The text file name will be given as a command line argument to the program. You will use an array of pointers to implement this program. There will be one pointer for each letter of the alphabet. The array will be indexed by each letter. To do so, subtract the ASCII value for ‘a’...
4
2846
by: vadrama | last post by:
takes a list of grades and counts the amount A's, B's, C's etc... I am using a while statement to count the total number of grades which works great, but my if and else statements to count how many A's, B's, etc...it seems the program is going through the While statement totally ignoring my if and else if statements. I tried doing muliple while statements but that gives unpredictable results. It seems I am missing one or two lines. Here...
5
3031
by: MJK | last post by:
Suppose I have the following function in my program: void ExtractData(Ind *AM) { int i,j; char str; char c; FILE *ext=fopen("test.out","r"); //suppose I have N line each with M digits (in here M=5) like: 1 2 2
6
18293
by: globalrev | last post by:
i ahve a program that takes certain textsnippets out of one file and inserts them into another. problem is it jsut overwrites the first riow every time. i want to insert every new piece of text into the next row. so: 1. how do i write to a new line every time i write to the file? 2. if i dont want to write to a new line but just want to insert it
4
1691
by: clrockwell | last post by:
Hey all, I could use some help with solving problem. Any suggestions are welcome and very appreciated. I have two arrays, $feeds and $feedDays. If they both have the same count, or $feeds has only one value than there is not a problem. In this situation
1
1714
by: sadpony | last post by:
Ok, so I wrote a program and it is supposed to let the user set the size of an array, input the numbers, find the subscript and value of the highest and lowest values, and then ask the user to input a value which the program will then check for it in the array and tell the user if it is in the array and how many times. So, I wrote it all, and I thought that it should be working. It compiles fine, but once I run it, it just hangs up and...
0
8466
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8384
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8591
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8659
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7412
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5683
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4208
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4388
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2799
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.