Explanation
The program counts and prints the number of digits in a number entered by the user.
Header
The code begins with including the standard input-output header file using #include <stdio.h>
.
Variable Declaration
The main()
function is defined, and two integer variables d
and m
are declared. Variable m
is initialized to 0 to count the number of digits.
Program Description
The program prints a description message for the user to understand its functionality.
User Input
The user is prompted to enter a number for which they want to count the digits. The input is read using scanf("%d", &d);
. The value of d
is stored in another variable j
for later use.
Digit Counting Logic
The program counts the number of digits in the entered number using a while
loop:
while (d != 0)
: Continuously checks ifd
is not equal to 0.d /= 10;
: Dividesd
by 10, effectively removing the last digit.m++;
: Increments the digit countm
by 1.
Program End
The program prints the number of digits stored in m
and the original number stored in j
. It ends with printf("\n");
to print a new line and return 0;
to indicate successful execution.
Code
/*
* -----------------------------------------------------------
* Logic Building with Computer Programming (CSU1128)
* Instructor: Dr. Pankaj Vaidya | Author: Divya Mohan
*
* This code is a part of the educational initiative by dmj.one
* with aim of empowering and inspiring learners in the field of
* Computer Science and Engineering through the respective courses.
*
* (c) 2022, Divya Mohan for dmj.one. All rights reserved.
* -----------------------------------------------------------
*/
#include <stdio.h>
int main()
{
int d, m = 0;
printf("\n\n Program to count and print the number of digits in the entered number that the user enters. Example 3310. \n\n");
printf("Enter a number for which you want to count the number of digits (Example: 2100) - and press enter: ");
scanf("%d", &d);
int j = d;
while (d != 0)
{
d /= 10;
m++;
}
printf("\nNumber of digits in the entered number %d is %d.", j, m);
printf("\n");
return 0;
}
Output
Program to count and print the number of digits in the entered number that the user enters. Example 3310.
Enter a number for which you want to count the number of digits (Example: 2100) - and press enter:
6632
Number of digits in the entered number 6632 is 4.