String Palindrome Program in C
Here you will know about Palindrome String and get the 3 different examples to check String Palindrome Program in C using 3 different ways in c language.
What is palindrome?
A word, phrase, or sequence that reads the same forward and backward is called a palindrome.
For Example:- malayalam, madam, racecar, noon, mam
Note:- Palindrome string program can check the palindrome number as input, but palindrome number program will give error if we input alphabets.
Algorithm of Palindrome
● Input a string
● Reverse string and store in another temp string variable
● Compare original and temp string
● If both string are same print message as “The String is Palindrome”
● Otherwise print message as “The String is not Palindrome”
String Palindrome Program in C using strrev
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <stdio.h> #include <string.h> int main() { char a[100], b[100]; printf("\n\n\t*** String Palindrome Program in C ***n"); printf("\n\n\tEnter the string to check palindrome :"); gets(a); strcpy(b, a); // to copy string strrev(b); // to reverse string // Comparing input string with the reverse string if (strcmp(a, b) == 0) printf("\n\tThe string is palindrome."); else printf("\n\tThe string isn't palindrome."); return 0; } |
Output
String Palindrome Program in C using for loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <stdio.h> int isPalindrome(char str[]) { int length = 0; // Calculate length of string while (str[length] != '\0') { length++; } int j = 0; int k = length - 1; // Check if string palindrome while (j < k) { if (str[j] != str[k]) { return 0; // Not a palindrome } j++; k--; } return 1; // Palindrome } int main() { char str[100]; printf("Enter a string: "); scanf("%s", str); if (isPalindrome(str)) { printf("%s is a palindrome.\n", str); } else { printf("%s is not a palindrome.\n", str); } return 0; } |
Output
Enter a string: racecar
racecar is a palindrome.
Enter a string: yamaha
yamaha is not a palindrome.
Palindrome Program in C using command line arguments
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <stdio.h> #include <string.h> // Function to palindrome string int isPalindrome(char *str) { int length = strlen(str); for (int i = 0; i < length / 2; i++) { if (str[i] != str[length - i - 1]) { return 0; // Not palindrome } } return 1; // It is Palindrome } int main(int argc, char *argv[]) { char *inputString = argv[1]; if (isPalindrome(inputString)) { printf("%s is a palindrome.\n", inputString); } else { printf("%s is not a palindrome.\n", inputString); } return 0; } |
Output
C:\CodeRevise\c_programs>”palindrome program in c using command line arguments.exe” rajan
rajan is not a palindrome.
C:\CodeRevise\c_programs>”palindrome program in c using command line arguments.exe” madam
madam is a palindrome.
Check out our other C programming Examples