Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i wrote a program that displays number of digits of an integer

#include<stdio.h>  
int main()
{
    int num , count=0;
    scanf("%d",&num);
    while(num)
    {
        num=num/10;
        count++;
    }
    printf("The number has %d digits",count);
    return 0;


The program works fine , but i want also for num " 0 " to print me that it has 1 digit , cause it prints it has 0.

What I have tried:

i thinked something like starting to count with 1 , but then is now working obvious for the rest.
Posted
Updated 27-Nov-22 10:12am
v2

And how is this from the identical question you posted a week ago: C program that counts how many digits a number have[^]
The answer hasn't changed since then, but I'll repeat it in case you didn't understand:
Quote:
Simplest solution? change your initial value, and your test.

If you start with a count of one, and test for "greater than or equal to ten" as your loop check, it'll give you the right answer for all positive values.
You can read it louder in your mind if that helps.
 
Share this answer
 
Comments
CPallini 26-Nov-22 8:43am    
:-D
The solution is simple. Why don't you use a do-while loop instead of a while loop?
 
Share this answer
 
Quote:
print me the reverse of a number

It would be good to solve the task exactly like this. Instead of trying to compose a new number, it would be better to just output the individual digits. Numbers like 100 would then also be displayed correctly.
 
Share this answer
 
Quote:
The program works fine , but i want also for num " 0 " to print me that it has 1 digit , cause it prints it has 0.

You code works for any cases but 1 specific case.
Solution , add specific code to handle this specific case.
C++
#include<stdio.h>  
int main()
{
    int num , count=0;
    scanf("%d",&num);
    // if num is special case
      // handle the special case
    // else
      // handle general case
      while(num)
      {
          num=num/10;
          count++;
      }
    // end of if
    printf("The number has %d digits",count);
    return 0;
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900