C Program to Count Number of Digits in an Integer

by | Jan 28, 2023 | Uncategorized

Introduction

This program will count the total number of digits present in an integer entered by the user.

Go through the topics in the C language series below to better understand the concepts.

1. Operators in C

2. while and do while loop in C

Program

#include<stdio.h>
int main()
{
int num;
printf("Enter an integer\n");
scanf("%d",&num);


int count=0; // count will count the number of digits
while(num!=0) // gives true until num become equal to 0
{
num=num/10; //removes last digit from the num
count++; // count will increase on each iteration
}


printf("Number of digits are %d",count); //final value of count will be printed
return 0;
}

 

Output

Explanation

‘num’ variable will store the integer value entered by the user.

int count=0;

‘count’ will count the number of digits that’s why initialized with 0.

Let’s consider the value entered by the user to understand the working for ‘while’ loop.

For num=5096387

while(num!=0) ,this will give true since num is not 0

num=num/10;

num=5096387/10=509638; vanishes the last digit.

count++; thus count becomes 1.

count=1

The loop will iterate again for num=509638

num=509638/10=50963

count=2

The loop will iterate again for num=50963

num=50963/10=5096

count=3

………goes up to

The loop will iterate again for num=50

num=50/10=5

count=6

while(num!=0) this condition result true for num=5

The loop will iterate again for num=5

num=5/10=0

count=7

while(num!=0) this condition result false for num=0

Thus, the loop terminates and the final value of the count is 7.

 

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Advertisement

Advertisement

Advertisement

Advertisement