Using the FOR command

Asked

Viewed 82 times

-1

I am developing solving issues in Language C. The question asks:

A palindrome is a word or phrase that has the property that can be read from right to left and from left to right. For example, the strings "Aaaaa", "1221", "bbaabb" are palindromes, however the string "chef" is not a palindrome because if we read from right to left, we get "fehc" which is not the same thing as "chef".

Ignore differences between upper and lower case.

For cases where a sentence is given, you should ignore the spaces. By example, the phrase "The base of the ceiling collapses" is considered a palindrome. When reading it from right to left, you will get: "abased otet od esab To".

Note that, with the exception of space, the string is a same as the original phrase. Make a script that specifies whether a string given is a palindrome or not.

When choosing 3, my code allows me to enter only 2 times and emits 1 result

Erro da quantidade de casos analisados

And my code is this:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main() {
char nome[255], inversa[255];
int i, qtd, resultado;

scanf( "%i", &qtd );
    for ( i = 0; i < qtd; i++ )

        gets (nome);

        strcpy (inversa, nome);

        strrev(inversa);

        resultado = strcmp (nome, inversa);

        if (resultado == 0) {
            printf("SIM");
        } else {
            printf("NAO");
        }
    return 0;
}

The site gives an example of the input and its output:

Exemplo da entrada e saída

Where is the error of my program and could give a brief explanation?

  • In addition to the error is a very inefficient code, and the posted response is also inefficient.

1 answer

1

As the statement itself says, you need to ignore both the spaces, and the differences between uppercase and minuscule, so before comparing the strings you could normalize them:

char nome[255], normalizado[255], inversa[255];
int i, j, k, tam, qtd, resultado;

// ...

gets(nome);

// Encontra o tamanho da string de entrada
tam = strlen(nome);

// Percorre o nome para gerar uma nova string normalizada
for (j = 0, k = 0; j < tam; j++) {
    // Se o caractere for diferente de um espaço...
    if (nome[j] != ' ') {
        // Converte para maiúsculo e o adiciona a nova string
        normalizado[k++] = toupper(nome[j]);
    }
}
// Adiciona um null terminator ao fim da string
normalizado[k] = '\0';

Now just reverse the normalized string and compare.


Also note that in your code you forgot to open the keys in your loop for.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.