C Online Compiler
Example: Palindrome Check by Reversing String in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Palindrome Check by Reversing String #include <stdio.h> #include <string.h> // Required for strlen(), strcpy(), strcmp() // Function to check if a string is a palindrome // Returns 1 if palindrome, 0 otherwise int isPalindromeReverse(const char *str) { // Step 1: Handle null or empty string if (str == NULL || strlen(str) == 0) { return 1; // Empty string is considered a palindrome } // Step 2: Get the length of the original string int length = strlen(str); // Step 3: Create a buffer for the reversed string // +1 for the null terminator char reversed_str[length + 1]; // Step 4: Reverse the string int i, j; for (i = 0, j = length - 1; i < length; i++, j--) { reversed_str[i] = str[j]; } reversed_str[length] = '\0'; // Null-terminate the reversed string // Step 5: Compare the original string with the reversed string // strcmp returns 0 if strings are identical if (strcmp(str, reversed_str) == 0) { return 1; // Strings are identical, so it's a palindrome } else { return 0; // Strings are different } } int main() { char str1[] = "madam"; char str2[] = "racecar"; char str3[] = "hello"; char str4[] = ""; // Empty string char str5[] = "a"; // Single character string char str6[] = "Madam"; // Case sensitive example printf("'%s' is a palindrome: %d\n", str1, isPalindromeReverse(str1)); printf("'%s' is a palindrome: %d\n", str2, isPalindromeReverse(str2)); printf("'%s' is a palindrome: %d\n", str3, isPalindromeReverse(str3)); printf("'%s' is a palindrome: %d\n", str4, isPalindromeReverse(str4)); printf("'%s' is a palindrome: %d\n", str5, isPalindromeReverse(str5)); printf("'%s' is a palindrome: %d\n", str6, isPalindromeReverse(str6)); // Will be 0 due to case sensitivity return 0; }
Output
Clear
ADVERTISEMENTS