Thursday, 6 August 2015

Find Number Of Digits In A Number

/*
 * C Program to find number of digits in a number.
 * Pre-Condition : Program needs to be written without using any library function.
 * Example       : If number is 1234 - output will be 4.
 */

// Include
#include <stdio.h>

// Declarations
/* getNumberOfDigits
 * Description : A function that gives number of digits in a given number.
 * Parameters  : i_number is the number of which number of digits needs to be found.
 * Return      : unsigned int data which is number of digits.
 */
unsigned int getNumberOfDigits(int i_number);

// Definitions
int main()
{
    int i_number;
    printf("Enter number of which number of digits needs to find : ");
    scanf("%d",&i_number);
    printf("Number of digits in %d : %u\n",i_number,getNumberOfDigits(i_number));
}

unsigned int getNumberOfDigits(int i_number)
{
    unsigned int count = 0;
    // As long as i_number does not become 0 - repeat
    while (i_number)
    {
        count++;
        i_number/=10;   // reduce the number by 1 digit
    }
    
    return count;
}

No comments:

Post a Comment