facebook like button

28 March, 2011

program 18: Counting the number of digits in a given number

The need:
     This program was given to me as a lab assignment.
The code:
-----------------------------------------
#include<stdio.h>
main()
{
    int s,d=0;
    printf("Enter the number to count its digits\n");
    scanf("%d",&s);     //scanning number into s
    while(s>0)     //while loop
    {
      s=s/10;
      d=d+1;     //you can also write d++ instead of d=d+1
    }
    printf("\nno of digits =\t%d",d);
}
-----------------------------------------

The approach: I hope you know how integer division works (recall example1 in program 5). I also assume that you are very much aware with 'while()' loop if you have gone through previous posts. Now in this while loop here I am dividing s by 10(which simply means each time I am removing left most digit of 's') in each run of loop. Here in this program I am using 'd' as the counter. You can clearly see that as a digit is removed from 's', 'd' is incremented. This while loop runs until value of 's' reaches 0. So its very obvious that when all the digits have been removed 'd' will be having the count of digits.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply