C Online Compiler
Example: Palindrome Check using Two Pointers in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Palindrome Check using Two Pointers #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 int is_palindrome_two_pointers(char* str) { int length = calculate_length(str); int start = 0; int end = length - 1; // Remove potential trailing newline if it's there if (length > 0 && str[end] == '\n') { str[end] = '\0'; // Replace newline with null terminator length--; // Adjust length end--; } // If the string is empty or has one character, it's a palindrome if (length <= 1) { return 1; } while (start < end) { if (str[start] != str[end]) { return 0; // Not a palindrome } start++; end--; } 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 // fgets reads up to size-1 characters or until a newline, storing the newline 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_two_pointers(input_string)) { printf("'%s' is a palindrome.\n", input_string); } else { printf("'%s' is not a palindrome.\n", input_string); } return 0; }
Output
Clear
ADVERTISEMENTS