implement recursive and iterative functions to count character
This commit is contained in:
parent
410e8d1ac5
commit
ef3a27fa78
1 changed files with 18 additions and 4 deletions
22
count_char.c
22
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) {
|
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) {
|
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;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue