48.6k views
4 votes
Write a function that accepts a pointer to a C-string as its argument. The function should count the number of times the character 'w' occurs in the argument and return that number.

User Synthaze
by
8.9k points

1 Answer

2 votes

Final answer:

The function 'countW' is written in C and counts the number of times the character 'w' appears in a C-string. It iterates through the string, increments the count for each 'w', and returns the total count.

Step-by-step explanation:

The student wants to write a function in C that counts the occurrences of the character 'w' in a given C-string. We will define such a function that takes a pointer to a const char (C-string) and returns the count of 'w' characters found.

Example Function Definition

int countW(const char* str) {
int count = 0;
while (*str) {
if (*str == 'w') {
count++;
}
str++;
}
return count;
}

This function iterates over each character in the string until it reaches the null terminator (which is the end of the C-string). If the current character is 'w', the function increments a count. Once the loop is finished, the function returns the total count of 'w' characters.

User Javiss
by
8.4k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.