Add problem 7 solution

This commit is contained in:
Myles Busig 2024-10-31 00:18:31 -07:00
parent 733052f838
commit feab097a60
3 changed files with 60 additions and 0 deletions

7
include/p7.h Normal file
View File

@ -0,0 +1,7 @@
#ifndef P7_H
#define P7_H
void reverse_string(char* str);
#endif

View File

@ -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;
}

43
src/p7.c Normal file
View File

@ -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;
}
}