![]() |
C Program for Palindrome [Number and Strings] |
Welcome back guys. Today I am gonna show how to check whether a number or string is palindrome or not. Palindrome is what we call when a reversed string is same as the original string. Like, MADAM, if we reverse the string still we get MADAM again. That's what called Palindrome. Other examples of Palindrome is RADAR,DAD etc. Our task to is code a C Programming to check whether it's Palindrome or not. Same rule applies for Numbers also. Some palindromic numbers are 141,242 etc.
Palindrome of String in C Program
There are different methods by which we can check palindrome but we will first do the easy method. First we will use string library functions, strcpy-strrev-strcmp, which will help us to check the Palindrome. Here we will make two char of arrays, one to get the string and another to hold the reversed string. If both are same,by comparing two with strcmp, we will output that the given string is Palindrome.So let's see our code.
#include <stdio.h> #include <string.h> int main() { char a[100], b[100]; printf("Enter the string to check if it is a palindrome\n"); gets(a); strcpy(b,a); strrev(b); if( strcmp(a,b) == 0 ) printf("Entered string is a palindrome.\n"); else printf("Entered string is not a palindrome.\n"); getch(); return 0; }
Palindrome of Number in C Program
if you remember, in my previous Reversing Number C Program tutorial, I showed your how to reverse a number. Here we will do the same but will add one extra thing. Have you guessed what that will be? No? Here will check at last whether the given number and the reversed number is same or not. If yes then we will output that given number is Palindrome and if not we will display the opposite. Simple enough. If you got my last tutorial well then you will have no problem understanding this code.
#include<stdio.h> #include<conio.h> int main() { int n, reverse = 0, temp; printf("Enter a number to check if it is a palindrome or not\n"); scanf("%d",&n); temp = n; while( temp != 0 ) { reverse = reverse * 10; reverse = reverse + temp%10; temp = temp/10; } if ( n == reverse ) printf("%d is a palindrome number.\n", n); else printf("%d is not a palindrome number.\n", n); getch(); return 0; }
Palindrome of String in C Program Without String Function
here we will check the same thing but without using String function. The logic behind it that we will set a counter from beginning as well as from end of the string and each counter will come to the middle. If in both case we have match then the given string is surely palindrome otherwise not.
#include <stdio.h> #include <string.h> int main() { char text[100]; int begin, middle, end, length = 0; gets(text); while ( text[length] != '\0' ) length++; end = length - 1; middle = length/2; for( begin = 0 ; begin < middle ; begin++ ) { if ( text[begin] != text[end] ) { printf("Not a palindrome.\n"); break; } end--; } if( begin == middle ) printf("Palindrome.\n"); getch(); return 0; }
0 comments