implement recursive and iterative functions to count character

This commit is contained in:
MarcUs7i 2025-01-10 23:15:11 +01:00
parent 410e8d1ac5
commit ef3a27fa78

View file

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