C Online Compiler
Example: Palindrome Check using Manual Reversal in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Palindrome Check using Manual Reversal #include <stdio.h> // Function to manually calculate string length int calculate_length(char* str) { int length = 0; while (str[length] != '\0' && str[length] != '\n') { // Account for newline from fgets length++; } return length; } // Function to check if a string is a palindrome by reversing it int is_palindrome_manual_reverse(char* original_str) { char cleaned_str[100]; // To store the string without newline int clean_len = 0; // Step 1: Clean the string (remove newline) and calculate effective length int i = 0; while (original_str[i] != '\0' && original_str[i] != '\n') { cleaned_str[clean_len++] = original_str[i]; i++; } cleaned_str[clean_len] = '\0'; // Null-terminate the cleaned string // If the string is empty or has one character, it's a palindrome if (clean_len <= 1) { return 1; } char reversed_str[100]; // Buffer for the reversed string int j; // Step 2: Manually reverse the cleaned string for (j = 0; j < clean_len; j++) { reversed_str[j] = cleaned_str[clean_len - 1 - j]; } reversed_str[clean_len] = '\0'; // Null-terminate the reversed string // Step 3: Manually compare the original (cleaned) string with the reversed string for (j = 0; j < clean_len; j++) { if (cleaned_str[j] != reversed_str[j]) { return 0; // Not a palindrome } } return 1; // It is a palindrome } int main() { char input_string[100]; // Buffer to store the input string // Step 1: Prompt user for input printf("Enter a string: "); // Step 2: Read string safely using fgets if (fgets(input_string, sizeof(input_string), stdin) == NULL) { printf("Error reading input.\n"); return 1; } // Step 3: Check if it's a palindrome and print result if (is_palindrome_manual_reverse(input_string)) { // For printing, we need to handle the newline possibly in input_string int len = calculate_length(input_string); if (len > 0 && input_string[len] == '\n') { input_string[len] = '\0'; // Temporarily null-terminate for clean printing } printf("'%s' is a palindrome.\n", input_string); } else { int len = calculate_length(input_string); if (len > 0 && input_string[len] == '\n') { input_string[len] = '\0'; } printf("'%s' is not a palindrome.\n", input_string); } return 0; }
Output
Clear
ADVERTISEMENTS