C++ program to find string is palindrome or not without using library
#include <iostream>
using namespace std;
int main() {
char str[100];
int len, i, j, flag=0;
cout << "Enter a string: ";
cin >> str;
// Find the length of the string
for (len = 0; str[len] != '\0'; len++);
// Check if the string is a palindrome
for (i = 0, j = len - 1; i < len / 2; i++, j--) {
if (str[i] != str[j]) {
flag = 1;
break;
}
}
if (flag) {
cout << str << " is not a palindrome" << endl;
} else {
cout << str << " is a palindrome" << endl;
}
return 0;
}
Let's go through this code step by step:
We start by including the necessary header files and defining the
mainfunction.We declare a character array
strof size 100 to store the input string, as well as integer variableslen,i,j, andflag.We prompt the user to enter a string using the
coutandcinstatements.We use a
forloop to find the length of the input string. This loop will iterate until the end of the string is reached, which is indicated by the null character\0.We use another
forloop to check if the input string is a palindrome. In this loop, we compare the first and last characters of the string, then move inward one character at a time until we reach the middle of the string. If we find any pair of characters that are not equal, we set theflagvariable to 1 and break out of the loop.Finally, we use an
ifstatement to check the value offlag. Ifflagis 1, we print a message indicating that the string is not a palindrome. Otherwise, we print a message indicating that the string is a palindrome.
The logic of this program is pretty straightforward. We first find the length of the input string using a for loop, then check whether the string is a palindrome using another for loop. The key insight is that for a string to be a palindrome, the first half of the characters must be equal to the second half in reverse order. So we simply compare the first and last characters of the string, then move inward until we reach the middle. If we find any pair of characters that are not equal, we know that the string is not a palindrome.
Note that we have used a character array str to store the input string. In C++, a string is essentially an array of characters terminated by a null character \0. So we can use an array to represent a string if we know the length of the string beforehand. In this program, we have assumed that the maximum length of the input string is 100 characters. If we want to handle longer strings, we would need to allocate a larger array dynamically using pointers.
Also note that we have used the using namespace std; statement to avoid typing std:: before all standard library functions and objects. This is not considered good practice in larger programs, but it's fine for small programs like this one.
No comments:
Post a Comment