0

I am trying to improve a program I have, but there is one thing I cannot figure out to do... so, trying to make this short, this is what I'd like to accomplish:

Is there a way for C to count how many variables are equal to a particular value?
For example, say I have integers a,b,c,d and assign them like this:
a=4;
b=2;
c=4;
d=4;

Is there a way to save the amount of variables that equal a? (which would be 2.. or 3 if you count a).

I just really want to save a single numerical value that tells how many variables I have equal to something.

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by Dream2code
0

There is not a short and easy way to do that. If you need to search your variables for matching values, then they're related enough to put in an array:

int a[] = {4, 2, 4, 4};

And if you need to keep the names, it's only slightly more complex:

struct Variable
{
    char *name;
    int value;
};

struct Variable a[] =
{
    {"a", 4},
    {"b", 2},
    {"c", 4},
    {"d", 4},
};

An array makes the whole process of looking for matches much easier because you can throw everything in a loop:

for (int x = 0; x < sz; ++x)
{
    if (a[x] == key) ++matches;
}
0

I do agree with TOM GUNN.Its a nice way to do things using structure.

Still u can use simple variables.

int  *a={2,3,4,5,6,7};

int no_of_variables=6;
int value_to_match=2;
int counter=0;

for(i=0;i<no_of_variables;i++)
{
if(a[i]==value_to_match) counter++;
printf("match variable is a_%d",i);
}
printf("Total mathch variales found is %d",counter);

}

NOTE:
Here variable are refered by a_0,a_1,a_2 like this in the output screen.
internaly a_1 means a[1] and so on.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.