Write a function that counts letters, digits and spaces in a string it only reads, returning the counts through pointers.
Solution
main.c
#include <ctype.h>
#include <stdio.h>
void count_chars(const char *s, int *letters, int *digits, int *spaces) {
*letters = *digits = *spaces = 0;
for (; *s; s++) {
unsigned char c = (unsigned char) *s;
if (isalpha(c)) (*letters)++;
else if (isdigit(c)) (*digits)++;
else if (c == ' ') (*spaces)++;
}
}
int main(void) {
int l, d, sp;
count_chars("Batch 2026 has 120 students", &l, &d, &sp);
printf("letters %d, digits %d, spaces %d\n", l, d, sp);
return 0;
}
Output Verified by compiling and running
letters 16, digits 7, spaces 4
The input is const char * (read-only), while the results come back through non-const pointers. The signature alone tells a reader which arguments the function changes.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!