Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add palindrome implementation in C - Nov 1 #25

Merged
merged 1 commit into from
Nov 4, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions November/Day 1/C/palindrome.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* @file
* @brief A program to determine if a string is a palindrome or not
*/

#include <assert.h> // for assert function (for tests)
#include <stdbool.h> // for bool data type
#include <string.h> // 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;
}