String Palindrome Program in C: A palindrome is a word, phrase or sentence that reads the same backward or forward. A string is said to be a palindromic string when we traverse it from start to end or end to start then we get the same result.
Examples: ada, malayalam, racecar, mom, etc.
In simple words, A string is said to be palindrome if the reverse of the string is the same as the
string.
Examples:
Let us take a few examples to understand the problem.
Example 1:
Input: String = “ABEEBA”
Output: ABEEBA is a Palindrome
Explanation: The reverse of the given string is equal to the (ABEEBA) is equal to the given string. Therefore, the given string is a palindromic string.
Example 2:
Input: String = “SANFOUNDRY”
Output: SANFOUNDRY is not a Palindrome
Explanation: The reverse of the given string is equal to the (YRDNUOFNAS) which is not equal to the given string. Therefore, the given string is not a palindromic string.
Write a C program that accepts a string and checks whether a given string is a palindrome or not.
1. Take a string as input and store it in the array.
2. Reverse the string and store it in another array.
3. Compare both the arrays.
There are several ways to check whether a string is Palindrome or not in C. Let’s look at all different approaches to program this function:
- String Palindrome Program in C using For Loop
- String Palindrome Program in C using Recursion
- String Palindrome Program in C using Naive Approach
- String Palindrome Program in C using Optimized Approach
- String Palindrome Program in C using Stack
In this approach, we will check whether given string is palindrome or not using for loop.
Here is source code of the C program to check a given string is palindrome using for loop. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to read a string and check if it's a palindrome, without
* using library functions. Display the result.
*/
#include <stdio.h>
#include <string.h>
void main()
{
char string[25], reverse_string[25] = {'\0'};
int i, length = 0, flag = 0;
fflush(stdin);
printf("Enter a string: \n");
gets(string);
/* keep going through each character of the string till its end */
for (i = 0; string[i] != '\0'; i++)
{
length++;
}
for (i = length - 1; i >= 0; i--)
{
reverse_string[length - i - 1] = string[i];
}
/*
* Compare the input string and its reverse. If both are equal
* then the input string is palindrome.
*/
for (i = 0; i < length; i++)
{
if (reverse_string[i] == string[i])
flag = 1;
else
flag = 0;
}
if (flag == 1)
printf("%s is a palindrome \n", string);
else
printf("%s is not a palindrome \n", string);
}
1. Take a string as input and store it in the array string[].
2. Store the same string into the another array reverse_string[] in the reverse fashion.
3. Using for loop compare the elements of both the arrays.
4. If all the elements of the array are same, then it is a palindrome. Otherwise it is not a palindrome.
Time Complexity: O(n)
The above program for checking palindrome string has a time complexity of O(n) because it uses a reverse function which has a time complexity of O(N).
Space Complexity: O(n)
In the above program, space complexity is O(n), as we use another string to store the reverse of our given string.
Testcase 1: In this case, we enter the string “sanfoundry” as input to check whether it is a palindrome string or not.
Enter a string: sanfoundry sanfoundry is not a palindrome
Testcase 2: In this case, we enter the string “malayalam” as input to check whether it is a palindrome string or not.
Enter a string: malayalam malayalam is a palindrome
In this approach, we check whether a given string is palindrome or not using recursion.
Here is source code of the C program to check a given string is palindrome using recursion. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C Program to Check whether a given String is Palindrome or not * using Recursion */ #include <stdio.h> #include <string.h> void check(char [], int); int main() { char word[15]; printf("Enter a word to check if it is a palindrome\n"); scanf("%s", word); check(word, 0); return 0; } void check(char word[], int index) { int len = strlen(word) - (index + 1); if (word[index] == word[len]) { if (index + 1 == len || index == len) { printf("The entered word is a palindrome\n"); return; } check(word, index + 1); } else { printf("The entered word is not a palindrome\n"); } }
1. In this C program, we are reading the value of string using word character array variable.
2. The check() function is used to check the string is a palindrome or not. A palindrome is a word, phrase or sentence that reads the same backward or forward.
3. Compute the difference between the lengths of the word by the index variable value by increments one value.
4. Then nested-If else condition statement is used to check the value of ‘word[]’ varaible with base index as index variable value is equal to the value of ‘word[]’ with base index len variable value.
5. If the condition is true then execute if condition statement. Another if condition statement is used to check the given string is palindrome using logical OR operator.
6. Check the value of ‘index’ variable increment by 1 is equal to the value of ‘len’ variable and the value of ‘index’ variable is equal to the value of ‘len’ variable.
7. If the condition is true then execute the statement and print the entered word is a palindrome. And again call the check() function to complete the process for whole string.
8. If the condition is false, then execute the else condition statement and print the statement as the entered word is not a palindrome.
Time Complexity: O(N)
In one function call, we are doing an O(1) operation of comparing the first
and last character. Recursive call is being done for at most N/2 times. N/2 because, in a string of
length N, we are removing 2 characters in each call. Thus, the overall complexity will be O(N).
Space Complexity: O(n2)
In the above program, space complexity is O(n2).
Testcase 1: In this case, we enter the string “sanfoundry” as input to check whether it is a palindrome string or not.
Enter a string: program program is not a palindrome
Testcase 2: In this case, we enter the string “malayalam” as input to check whether it is a palindrome string or not.
Enter a string: racecar racecar is a palindrome
In this approach, we make a copy of the user input character array and then comparing both. Here we define the main function and subsequently we define the isPalindromeStr(char []) function which accepts the string, reverses it and then finally checked for equality with the original string.
Here is source code of the C program to check a given string is palindrome using naive approach. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C program to read a string and check if it is a * palindrome. Display the result. */ #include <stdio.h> #include <string.h> #include <strings.h> void isPalindromeStr(char str[], int len) { char reverse_string[32] = { '\0' }; for (int i = len - 1; i >= 0; i--) { reverse_string[len - i - 1] = str[i]; } /* Compare the input string and its reverse. If both are equal * then the input string is palindrome. */ printf("%s reversed is %s therefore ", str, reverse_string); // strcasecmp is defined in strings.h if (!strcasecmp(str, reverse_string)) printf("%s is a palindrome. \n", str); else printf("%s is not a palindrome. \n", str); } int main(void) { char str[32]; puts("Enter a string : "); /* gets is depreciated in favor of fgets as fgets * provides memory safety in terms of assigning the * variable with the maximum allowed size and from * the specified source, here stdin. */ fgets(str, sizeof(str), stdin); strtok(str, "\n"); int length = (int)strlen(str); isPalindromeStr(str, length); return 0; }
1. Take the string as input and store it in a character array.
2. Pass the string into the isPalindromeStr function.
3. Make a copy of the original string and find its reverse.
4. If the reverse and the original string are the same ignoring case then it is a palindrome string otherwise it is not.
Time and Space Complexity:
The Time complexity of the above code is O(n) while the space complexity is O(2n) = O(n).
Testcase 1: In this case, we enter the string “aba” as input to check whether it is a palindrome string or not.
Enter a string: aba aba is a palindrome
Testcase 2: In this case, we enter the string “India” as input to check whether it is a palindrome string or not.
Enter a string: India India is not a palindrome
Here we do not create a copy of the character array but rather check for the array indices in order to decide whether the string is a palindrome.
The source of the program is as follows. Here we define the main function and subsequently we define the isPalindromeStr(char []) function which accepts the string, initializes two indices, compares at the two indices through the loop.
Here is source code of the C program to check a given string is palindrome using optimized approach. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C program to read a string and check if it's a * palindrome. Display the result. */ #include <stdio.h> #include <string.h> #include <ctype.h> void isPalindromeStr(char str[]) { int pt1 = 0; int pt2 = (int)strlen(str) - 1; while (pt2 > pt1) { if (tolower(str[pt1++]) != tolower(str[pt2--])) { printf("%s is not a palindrome.\n", str); return; } } printf("%s is a palindrome.\n", str); } int main(void) { char str[32]; puts("Enter a string : "); /* gets is depreciated in favor of fgets as fgets * provides memory safety in terms of assigning the * variable with the maximum allowed size and from * the specified source, here stdin. */ fgets(str, sizeof(str), stdin); strtok(str, "\n"); isPalindromeStr(str); return 0; }
1. Take the string as input and store it in a character array.
2. Pass the string into the isPalindromeStr function.
3. Define index pointers (not literal) pt1 and pt2.
4. Over the course of this program, pt1 will increase and vice versa until they become equal or in other words, reach the mid.
5. Check whether the characters at indices pt1 and pt2 are unequal for every iteration of the loop and if they are unequal, print not palindrome and return to the main function.
6. Even if this condition fails only once, the inner code gets executed and the control goes back to the main function.
Time and Space Complexity:
The Time complexity of the palindrome program is O(n) while the space complexity is also O(n).
Testcase 1: In this case, we enter the string “aba” as input to check whether it is a palindrome string or not.
Enter a string: malayalam malayalam is a palindrome
Testcase 2: In this case, we enter the string “India” as input to check whether it is a palindrome string or not.
Enter a string: Sanfoundry Sanfoundry is not a palindrome
In this approach, we identify whether the string is palindrome or not using stack.
1. Take a string as input.
2. Store the string in the stack array.
3. Check whether the string is palindrome or not.
Here is source code of the C Program to identify whether the string is palindrome or not using stack. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Identify whether the String is Palindrome or not using Stack
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50
int top = -1, front = 0;
int stack[MAX];
void push(char);
void pop();
void main()
{
int i, choice;
char s[MAX], b;
while (1)
{
printf("1-enter string\n2-exit\n");
printf("enter your choice\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter the String\n");
scanf("%s", s);
for (i = 0;s[i] != '\0';i++)
{
b = s[i];
push(b);
}
for (i = 0;i < (strlen(s) / 2);i++)
{
if (stack[top] == stack[front])
{
pop();
front++;
}
else
{
printf("%s is not a palindrome\n", s);
break;
}
}
if ((strlen(s) / 2) = = front)
printf("%s is palindrome\n", s);
front = 0;
top = -1;
break;
case 2:
exit(0);
default:
printf("enter correct choice\n");
}
}
}
/* to push a character into stack */
void push(char a)
{
top++;
stack[top] = a;
}
/* to delete an element in stack */
void pop()
{
top--;
}
1. Take a string as input and store it in the array s[].
2. Load each character of the array s[] into the array stack[].
3. Use variables front and top to represent the last and top element of the array stack[].
4. Using for loop compare the top and last element of the array stack[]. If they are equal, then delete the top element, increment the variable front by 1 and compare again.
5. If they are not equal, then print the output as “It is not a palindrome”.
6. Compare the elements in the steps 4-5 upto the middle element of the array stack[].
7. If every characters of the array is equal, then it is a paliandrome.
In this case, we check whether the entered string is palindrome or not. The input we entered as a string are madam, ugesh, abccba and abdbca.
1-enter string 2-exit enter your choice 1 Enter the String madam madam is palindrome 1-enter string 2-exit enter your choice 1 Enter the String ugesh ugesh is not a palindrome 1-enter string 2-exit enter your choice 1 Enter the String abccba abccba is palindrome 1-enter string 2-exit enter your choice 1 Enter the String abdbca abdbca is not a palindrome 1-enter string 2-exit enter your choice 2
To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.
- Apply for Computer Science Internship
- Check C Books
- Practice Computer Science MCQs
- Practice BCA MCQs
- Watch Advanced C Programming Videos