If what you want is to count how many letters repeat and how many times, we can use an auxiliary array as an occurrence counter to help. Here’s the code:
#include <stdio.h>
#include <stdlib.h>
#define TAM 100
#define MAX_CHARS 256
int main() {
char palavra[TAM];
int repeticoes[MAX_CHARS];
int i, tamanho = 0;
printf("Digite uma palavra: \n" );
while (tamanho < TAM - 1 && (c = getchar()) != '\n') {
palavra[tamanho] = c;
tamanho++;
}
palavra[tamanho] = '\0';
for (i = 0; i < tamanho; i++) {
repeticoes[palavra[i]]++;
}
for (i = 0; i < MAX_CHARS; i++) {
if (repeticoes[i] > 0) {
printf("%c = %d\n", (char) i, repeticoes[i]);
}
}
for (i = tamanho - 1; i >= 0; i--) {
printf("%c", palavra[i]);
}
printf("\n");
}
That array repeticoes
is the occurrence counter. The type char
occupies one byte, and therefore allows 256 different combinations. So this will be the size of the array and there will be a position in the array for each possible value of char
, each representing how many times this value of char
appears in the word.
In the first for
, the instruction repeticoes[palavra[i]]++;
works first with the palavra[i]
that will map the word character directly to one of the array positions repeticoes
, position that will have its value increased. This loop will traverse the entire typed word (or phrase) and when counting the characters, will mount the occurrence counter.
The second for
just scroll through the values of the occurrences counter, showing them on the screen. Positions with zeros are characters that do not exist in the word, which is why they are not shown.
The last for
traverse the string palavra
back-to-front and print the characters one at a time, then showing the string back-to-front.
Note also that I put one tamanho < TAM - 1 &&
in the while
. The reason for this is to avoid being able to type more characters than it fits in the array palavra
. Use only tamanho < TAM
is not sufficient because space is still needed for the \0
, and therefore is used tamanho < TAM - 1
. That’s before the &&
because the size has to be checked before some more character is read.
It is obvious that: if(word[i]==word[i]){ will always be true. I believe that it is not this comparison that you wish to make.
– Anonimo
Would you not want to check whether each character occurs at other srting positions?
– Anonimo
Regex wouldn’t solve the problem?
– Fabricio
When you say how many repeated elements is how many letters are repeated? Or how many times each is repeated ? Give some examples to be clearer
– Isac
How often each element repeats. For example, the word arara. The letter a repeats three times and the letter r two times.
– french kote.
I edited your question to try to make the description of the problem clearer. Tell me what you thought, whether I got it right or not.
– Victor Stafusa