Grupo
Estructuras Condicionales Avanzadas en C++
Ojetivo
1. Solicitar al usuario que introduzca una palabra.
2. Comprobar si la palabra se lee igual de derecha a izquierda.
3. Mostrar un mensaje indicando si la palabra es un palíndromo.
Escribir un programa que compruebe si una palabra es un palíndromo.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include for input and output
#include <string> // Include for using std::string
using namespace std;
int main() {
string word; // Variable to store the user's input
bool isPalindrome = true; // Boolean flag to determine if the word is a palindrome
// Ask the user to enter a word
cout << "Enter a word: ";
cin >> word; // Read the word from user input
int length = word.length(); // Get the length of the word
// Loop to compare characters from the beginning and end
for (int i = 0; i < length / 2; i++) {
if (word[i] != word[length - i - 1]) { // Compare characters from opposite ends
isPalindrome = false; // If mismatch, set flag to false
break; // No need to continue if already not a palindrome
}
}
// Output the result
if (isPalindrome) {
cout << word << " is a palindrome." << endl;
} else {
cout << word << " is not a palindrome." << endl;
}
return 0; // End of program
}
Salida
Enter a word: radar
radar is a palindrome.
Comparte este ejercicio C++