i need help on how can i display the number of times a value appear in array

ex:
number[3][3]={{1,2,3},{2,3,4},{3,4,5}}

1 appeared 1 time(s)
2 appeared 2 time(s)
4 appeared 2 time(s)

simple tips would do....thanks

2
Contributors
1
2
Views
13 Years
Discussion Span
Last Post by Dave Sinkula

One way:

``````#include <stdio.h>

int main()
{
int number[3][3] = { {1,2,3}, {2,3,4}, {3,4,5} };
struct
{
int value, times;
} result [ sizeof number / sizeof **number ] = {0};
size_t i, j, k;
for ( i = 0; i < sizeof number / sizeof *number; ++i )
{
for ( j = 0; j < sizeof *number / sizeof **number; ++j )
{
for ( k = 0; k < sizeof result / sizeof *result; ++k )
{
if ( number[i][j] == result[k].value )
{
result[k].times++;
goto next;
}
}
if ( k == sizeof result / sizeof *result ) /* not found -- new entry */
{
for ( k = 0; k < sizeof result / sizeof *result; ++k )
{
if ( !result[k].value )
{
result[k].value = number[i][j];
result[k].times++;
break;
}
}
}
next:
;
}
}
for ( k = 0; k < sizeof result / sizeof *result; ++k )
{
if ( result[k].value )
{
printf("%d appeared %d time(s)\n", result[k].value, result[k].times);
}
}
return 0;
}

/* my output
1 appeared 1 time(s)
2 appeared 2 time(s)
3 appeared 3 time(s)
4 appeared 2 time(s)
5 appeared 1 time(s)
*/``````

Post your own attempt if you don't understand this.

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.