Add problem 7 solution
This commit is contained in:
parent
9549e635ac
commit
9f770dc80a
7
include/p7.h
Normal file
7
include/p7.h
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
#ifndef P7_H
|
||||||
|
#define P7_H
|
||||||
|
|
||||||
|
void reverse_string(char* str);
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
10
src/main.c
10
src/main.c
@ -6,6 +6,7 @@
|
|||||||
#include "p4.h"
|
#include "p4.h"
|
||||||
#include "p5.h"
|
#include "p5.h"
|
||||||
#include "p6.h"
|
#include "p6.h"
|
||||||
|
#include "p7.h"
|
||||||
|
|
||||||
void print_int_arr(int* arr, int size) {
|
void print_int_arr(int* arr, int size) {
|
||||||
for (int i = 0; i < size; ++i) {
|
for (int i = 0; i < size; ++i) {
|
||||||
@ -67,6 +68,15 @@ int main(void) {
|
|||||||
str_to_upper(p6_str);
|
str_to_upper(p6_str);
|
||||||
printf("\"%s\"\n", 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;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
43
src/p7.c
Normal file
43
src/p7.c
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Loading…
x
Reference in New Issue
Block a user