-3

I have solve a basic problem in c that is count the digits in integer and I have written -

#include<stdio.h>

int main()   
{
    int n;

    scanf("%d",&n);
    
    int i;
    while(n!=0)
    {
        n %= 10;
        ++i;
    }
    
    printf("%d",i);
}

I already know that above code is wrong, I should write n/=10; instead of n%=10; but I wants to know why it is not printing even value of i i.e 0.

If I have written any wrong so please ignore it ,I am new here..

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 6
    Because if `n` is not a multiple of `10`, then it will iterate forever. – Eugene Sh. Oct 26 '21 at 13:15
  • 2
    Why don't you print `n` inside the loop and observe what's happening? Also, `i` (uninitialized) is incremented forever - signed integer overflow causes UB. – babon Oct 26 '21 at 13:19
  • Because you are not exiting the loop – Sandeep_Rao Oct 26 '21 at 13:21
  • Debug fail, as described by @babon. If you cannot debug, you cannot program computers. If nothing else, just put in some printf's so you can inspect important vars during thexrun, (or, of course, use an actual debugger:). – Martin James Oct 26 '21 at 16:35

1 Answers1

2

If the number n is not divisible by 10 then the value of this expression (the remainder of the division)

n %= 10;

will never be equal to 0.

Also the variable i is not initialized.

int i;

You should write

int i = 0;

do
{
    ++i;
} while ( n /= 10 );

printf( "%d\n", i );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335