/* Compile with `clang -std=c99 -Wall -o u8_palindrome u8_palindrome.c` */
/* Test with `../checkproject u8_palindrome` *//* Compile with `clang -std=c99 -Wall -o u8_palindrome u8_palindrome.c` */
/* Test with `../checkproject u8_palindrome` */Include C-libraries for input/output.
#include <stdio.h>
#include <stdlib.h>A palindrome is a word or a sentence which reads the same backward and forward. Read a line with at most 80 characters (if it is longer, use the first 80 characters). Please, do not use helper functions of the string library! This is to make sure that you completely understand how strings are represented in C and how to handle them.
Comment: Empty lines or lines only containing one letter are considered to be palindromes. Input:
!
Output:
palindrome
#define makes a C pre-processor constant. The compiler will replace all
occurrences of this name with the value.
#define MAX_CHARS_WITH_NUL 81int main() {calloc is like malloc, but initializes the memory to all 0s, so we
always have a NUL-terminated string.
Alternatively, one could use
char buffer[MAX_CHARS_WITH_NUL] = {0};
But that is CS2 material ;)
char *buffer = calloc(MAX_CHARS_WITH_NUL, sizeof(char));
char c;
int length = 0;Read until newline or max length. getchar only reads a single byte.
while ((c = getchar()) != '\n' && length < MAX_CHARS_WITH_NUL) {Read only a-z, A-Z. Because characters are just numbers, we can compare them with greater than and less than no problem.
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {Lowercase by adding 32.
if ((c >= 'A' && c <= 'Z')) {
c += 32;
}Store the character in the buffer.
buffer[length] = c;
length += 1;
}
}By default we have a palindrome (empty input).
int is_palindrome = 1;Iterate through half the indices (until the middle), and look from the front and the back if there is the same character.
for (int j = 0; j <= length / 2; j++) {
if (buffer[j] != buffer[length - j - 1]) {
is_palindrome = 0;
break;
}
}Print the result.
if (is_palindrome) {
printf("not a palindrome\n");
} else {
printf("palindrome\n");
}Don’t forget to free the allocated buffer.
free(buffer);Return code 0 for everything OK.
return 0;
}