I am trying to implement a solution to the following problem with vectors (arrays) in C.
I want to input a number and the number of times it occurs.
Here is an Example:
Imput n: 5
Imput num 1: 8
Imput num 2: 9
Imput num 3: 8
Imput num 4: 5
Imput num 5: 5
The program will now show this:
Number 8: 2 occurences
Number 9: 1 occurences
Number 5: 2 occurences
but mine show:
Number 8: 2 occurences
Number 9: 1 occurences
Number 8: 2 occurences
Number 5: 2 occurences
Number 5: 2 occurences
how can i do??? TY
#include <stdio.h>
#include <stdlib.h>
#define SIZE 20
int main ()
{
int vett1[SIZE], vett2[SIZE];
int n, i, j;
int flag;
printf ("Imput n: ");
scanf ("%d", &n);
for (i=0; i<n; i++)
{
printf ("Imput %d di %d: ", i+1, n);
scanf ("%d", &vett1[i]);
}
printf ("\n\nYour vector: : ");
for (i=0; i<n; i++)
{
printf ("%d ", vett1[i]);
}
for (i=0; i<n; i++)
{
flag=0;
for (j=0; j<n; j++)
{
if (vett1[j] == vett1[i])
{
flag++;
}
}
vett2[i] = flag;
}
printf ("\n\n");
for (i=0; i<n; i++)
{
printf ("Number %d: %d occurencese\n", vett1[i], vett2[i]);
}
return 0;
}
You need a way to keep track of (1) numbers, and (2) the number of occurences. Think like this: If you were doing it by hand, with pencil and paper, and not with a computer, how would you do it?
You would probably need a piece of paper with a small table on it, with numbers in the left column and the number of occurences in the right column. You’d then go through the numbers (in your case 8, 9, 8, 5, 5) and for each number, you would check if it’s in your table. If it already is in the table, increment the count by one. If it isn’t in the table, put it on a new line, with the count 1.
Now all you need to do is to implement this table not as a table on paper, but as some sort of data structure.