From cdf0b78f28d44537cda7d64348fd5a9d5347331a Mon Sep 17 00:00:00 2001 From: Randy Kwalar Date: Thu, 4 Nov 2021 07:00:56 +0100 Subject: [PATCH] Add palindrome implementation in C --- November/Day 1/C/palindrome.c | 51 +++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 November/Day 1/C/palindrome.c diff --git a/November/Day 1/C/palindrome.c b/November/Day 1/C/palindrome.c new file mode 100644 index 0000000..150d7b5 --- /dev/null +++ b/November/Day 1/C/palindrome.c @@ -0,0 +1,51 @@ +/** + * @file + * @brief A program to determine if a string is a palindrome or not + */ + +#include // for assert function (for tests) +#include // for bool data type +#include // for strlen function + +/** + * @brief Determines if the input `string` is a palindrome or not + * @param string the string (array of characters) to be checked + * @returns true if `string` is a palindrome + * @returns false if `string` is not a palindrome + */ +bool isPalindrome(const char string[]) { + int lengthOfString = strlen(string); // the length of `string` + + // iterates over the `string` + for(int i = 0; i < lengthOfString / 2; i++) { + // checks if elements at adjacent ends of `string` are different + if(string[i] != string[lengthOfString - i - 1]) { + // if they are different, + return false; + } + } + + // otherwise, + return true; +} + +/** + * @brief Self-test Implementations + * @returns void + */ +void test(void) { + char *str = "abbbba"; + assert(isPalindrome(str) == true); + + str = "randy"; + assert(isPalindrome(str) == false); +} + +/** + * @brief Main function + * @returns 0 on exit + */ +int main(void) { + test(); // runs self-test implementation of the program + return 0; +} \ No newline at end of file