-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathPalindrome.c
55 lines (44 loc) · 1.3 KB
/
Palindrome.c
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* Below code checks if the given input string is
a palindrome or not. The string is traversed till
its middle index and beginning and end of the string
is compared.*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define maximum length of input string
#define MAXLENGTH 100
// This function checks if string is a palindrome
int check_palindrome(char* string) {
// Iterate till the middle of the string
for(int i = 0; i < (strlen(string) - 1) / 2; i++) {
/* Check if character at beginning index of the
string matches the end of the string at same index*/
if(string[i] != string[strlen(string) - 2 - i]) {
// If it does not then return -1
return -1;
}
}
// If everything matches then return 1
return 1;
}
int main() {
// Take string as input from the user
char string[MAXLENGTH];
printf("Enter a string to check if it is a palindrome: ");
fgets(string, MAXLENGTH, stdin);
// Calling the function to check
int result = check_palindrome(string);
// If the string is a palindrome
if(result == 1) {
printf("The given string is a palindrom.\n");
}
// If the string is not a palindrome
else {
printf("The given string is not a palindrom.\n");
}
return 0;
}
/* Sample I/O:
Enter a string to check if it is a palindrome: This is a si sihT
The given string is a palindrom.
*/