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> #include <string.h> // Required for strlen() // Function to check if a string is a palindrome // Returns 1 if palindrome, 0 otherwise int isPalindromeTwoPointers(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: Initialize two pointers int left = 0; int right = strlen(str) - 1; // Step 3: Iterate while left pointer is less than right pointer while (left < right) { // Step 4: Compare characters at current pointers if (str[left] != str[right]) { return 0; // Mismatch found, not a palindrome } // Step 5: Move pointers towards the center left++; right--; } // Step 6: If loop completes, string is a palindrome return 1; } 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, isPalindromeTwoPointers(str1)); printf("'%s' is a palindrome: %d\n", str2, isPalindromeTwoPointers(str2)); printf("'%s' is a palindrome: %d\n", str3, isPalindromeTwoPointers(str3)); printf("'%s' is a palindrome: %d\n", str4, isPalindromeTwoPointers(str4)); printf("'%s' is a palindrome: %d\n", str5, isPalindromeTwoPointers(str5)); printf("'%s' is a palindrome: %d\n", str6, isPalindromeTwoPointers(str6)); // Will be 0 due to case sensitivity return 0; }
Output
Clear
ADVERTISEMENTS