Summary: This C program counts the frequency of digits (0–9) in a given string and prints their occurrences. It includes inline comments for beginner-level clarity and understanding of logic behind each step.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
char input[1000]; // A place to store the text the user types
int counter[10] = {0}; // This will count how many times each digit appears (0 to 9)
scanf("%s", input); // Read the text and store it in 'input'
// Go through each character in the input
for (int i = 0; input[i] != '\0'; i++) {
// If the character is a digit (from '0' to '9')
if (input[i] >= '0' && input[i] <= '9') {
int digit = input[i] - '0'; // Change the character to the real number (e.g., '3' - '0' = 3)
counter[digit]++; // Add 1 to that digit's counter
}
}
// Show how many times each digit appeared
for (int i = 0; i < 10; i++) {
printf("%d ", counter[i]);
}
return 0;
}
String Handling:
The input is stored in a character array. scanf("%s", input)
reads input until a space is encountered.
Digit Detection:
The code checks if a character is a digit using input[i] >= '0' && input[i] <= '9'
. This ensures that only numeric characters are processed.
Character to Integer Conversion:
input[i] - '0'
converts a character digit (e.g., '3') into its integer value (3).
Frequency Tracking:
An integer array counter[10]
is used to store the count of each digit from 0 to 9.
Output:
A simple loop prints the count of each digit in a single line, separated by spaces.