LearnFrenzy
Sign in Take a free test

C Const · const Programs · Question 3

Const-correct letter, digit and space counter in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links