English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

Count digits in an integer with C program

Comprehensive Collection of C Programming Examples

In this example, you will learn to calculate the number of digits in the integer entered by the user.

To understand this example, you should understand the followingC programmingTopic:

This program takes an integer from the user and calculates the number of digits. For example: if the user enters2319Then the output of the program will be4.

Program calculates the number of digits

#include <stdio.h>
int main() {
    long long n;
    int count = 0;
    printf("Enter an integer: ");
    scanf("%lld", &n);
 
    //Iterate until n becomes 0
    //The last digit is removed from n in each iteration
    //The count is incremented each iteration1
    while (n != 0) {
        n /= 10;     // n = n/10
        ++count;
    
    printf("Number of digits: %d", count);

Output result

Enter an integer: 3452
Number of digits: 4

The integer entered by the user is stored in the variable n. Then iterate while LoopUntil the test expression n!= 0 is evaluated to 0 (false).

  • After the first iteration, the value of n is345, and count increases to1.

  • After the second iteration, the value of n is34, and count is increased to2.

  • After the third iteration, the value of n is3, and count is increased to3.

  • After the fourth iteration, the value of n is 0, and count is incremented to4.

  • Then the test expression of the loop is evaluated to false, and the loop terminates.

Comprehensive Collection of C Programming Examples