/*---------------------------------------------------------- * HTBLA-Leonding * --------------------------------------------------------- * Title: Count Character Occurrence * Author: Marc Tismonar * ---------------------------------------------------------- * Description: * Recursive and iterative implementation of an algorithm that * counts the occurrences of a specific character within a string. * ---------------------------------------------------------- */ #include "count_char.h" /* Instructions: Define a function count_char(s, c) that takes a string `s` and the character 'c' to count as input. Increase the counter by one, if the character matches the character at the current position within the string and add the count of that character in the remaining string until the end of the string ('\0'). */ int count_char_recursive(const char* str, char c) { if (str[0] == '\0') { return 0; } // skips the first character by moving the pointer to the next character const 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); } int count_char_iterative(const char* str, char c) { int sum = 0; for(int i = 0; str[i] != '\0'; i++) { if (str[i] == c) { sum++; } } return sum; }