From feab097a60983ca86f109e7cbc9091966d4cd80d Mon Sep 17 00:00:00 2001 From: Myles Busig Date: Thu, 31 Oct 2024 00:18:31 -0700 Subject: [PATCH] Add problem 7 solution --- include/p7.h | 7 +++++++ src/main.c | 10 ++++++++++ src/p7.c | 43 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 include/p7.h create mode 100644 src/p7.c diff --git a/include/p7.h b/include/p7.h new file mode 100644 index 0000000..502e340 --- /dev/null +++ b/include/p7.h @@ -0,0 +1,7 @@ +#ifndef P7_H +#define P7_H + +void reverse_string(char* str); + +#endif + diff --git a/src/main.c b/src/main.c index c8dc6c4..7720195 100644 --- a/src/main.c +++ b/src/main.c @@ -6,6 +6,7 @@ #include "p4.h" #include "p5.h" #include "p6.h" +#include "p7.h" void print_int_arr(int* arr, int size) { for (int i = 0; i < size; ++i) { @@ -67,6 +68,15 @@ int main(void) { str_to_upper(p6_str); printf("\"%s\"\n", p6_str); + // Problem 7 + printf("Problem 7:\n"); + + char p7_str[32] = "Hello Exam #2!"; + + printf("\"%s\"\n", p7_str); + reverse_string(p7_str); + printf("\"%s\"\n", p7_str); + return 0; } diff --git a/src/p7.c b/src/p7.c new file mode 100644 index 0000000..ce0833c --- /dev/null +++ b/src/p7.c @@ -0,0 +1,43 @@ +#include "p7.h" + +void reverse_string(char* str) { + // First and last character that still need to be swapped + char* first = str; + char* last = str; + + // Traverse the string until the null character is reached. + for (; *last != '\0'; ++last); + + // `last` points to the terminating null character currently, + // but we need a pointer to the last character of the string. + --last; + + // Traverse string from both ends until the indices meet or cross. + // + // ex "ABCD: + // A B C D + // ^ ^ + // first last + // + // D B C A + // ^ ^ + // first last + // + // D C B A + // ^ ^ + // last first + // + // At this point the indices have crossed, so we are finished + // reversing the string. + // + while (first < last) { + // Swap the first and last characters that need to be swapped. + char temp = *first; + *first = *last; + *last = temp; + + ++first; + --last; + } +} +