Q:

C program to count total number of digits of an Integer number

0

C program to count total number of digits of an Integer number

This program will read an integer number and count total number of digits of input number. for example there is a number 1234 and total number of digits are 4.

Logic behind to implement this program - Divide number by 10 and count until number is not zero, before using counter variable, initialize the count variable by 0.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Count Digits of a Number using C program

/* C program to count digits in a number.*/

#include <stdio.h>

int main()
{
    int num, tNum, cnt;

    printf("Enter a number: ");
    scanf("%d", &num);

    cnt = 0;
    tNum = num;

    while (tNum > 0) {
        cnt++;
        tNum /= 10;
    }

    printf("Total numbers of digits are: %d in number: %d.", cnt, num);

    return 0;
}

Using User Define Function

/* C program to count digits in a number.*/

#include <stdio.h>

/*function to count digits*/
int countDigits(int num)
{
    int count = 0;
    while (num > 0) {
        count++;
        num /= 10;
    }
    return count;
}

int main()
{
    int num, tNum, cnt;

    printf("Enter a number: ");
    scanf("%d", &num);

    cnt = countDigits(num);

    printf("Total numbers of digits are: %d in number: %d.", cnt, num);

    return 0;
}

Output:

    Enter a number: 28765
    Total numbers of digits are: 5 in number: 28765.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now