If you want to count how many letters repeat and how many times, we can use an auxiliary array as an occurrence counter to help. Here is 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] = '#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] = '%pre%';
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");
}
';
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");
}
This repeticoes
array is the hit counter. The type char
occupies one byte, and therefore allows 256 different combinations. Then 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 that value of char
appears in the word.
In the first for
, the repeticoes[palavra[i]]++;
statement works first with palavra[i]
that will map the character of the word directly to one of the positions of the repeticoes
array, which position will have its value increased. This loop will go through the whole typed word (or phrase) and counting the characters will mount the occurrence counter.
The second for
only traverses the values of the occurrence counter, showing them on the screen. Zero positions are characters that do not exist in the word, which is why they are not shown.
The last for
traverses the string palavra
back-to-front and prints the characters one at a time, then showing the back-to-front string.
Also note that I put tamanho < TAM - 1 &&
in while
. The reason for this is to avoid being able to type more characters than it fits in the palavra
array. Using only tamanho < TAM
is not sufficient because you still need space for tamanho < TAM - 1
, and therefore &&
is used. This is before %code% because the size has to be checked before any extra characters are read.