From ef3a27fa7852fb5ba844a5dad2a410ea32e41702 Mon Sep 17 00:00:00 2001 From: MarcUs7i Date: Fri, 10 Jan 2025 23:15:11 +0100 Subject: [PATCH] implement recursive and iterative functions to count character --- count_char.c | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/count_char.c b/count_char.c index 5dcd01b..947c3c2 100644 --- a/count_char.c +++ b/count_char.c @@ -22,12 +22,26 @@ until the end of the string ('\0'). */ -// TODO: the recursive implementation int count_char_recursive(const char* str, char c) { - return 0; + if (str[0] == '\0') { + return 0; + } + + // skips the first character by moving the pointer to the next character + char* truncated = str + 1; + + // true is 1, false is 0. no need to write a ternary operator + return (str[0] == c) + count_char_recursive(truncated, c); } -// TODO: the iterative implementation int count_char_iterative(const char* str, char c) { - return 0; + int sum = 0; + + for(int i = 0; str[i] != '\0'; i++) { + if (str[i] == c) { + sum++; + } + } + + return sum; }