Problem 2: Given an integer, output the number of digits of that number.
Solution: This problem also can be soloved by above method, i.e converting into a string, then output the length of that string. But we will solve it with another approch.
Now have a close look at the code:
#include<stdio.h>
int main() {
int n, totaldigits = 0;
scanf("%d",&n);
while(n > 0) {
totaldigits ++;
n/= 10; // or n = n / 10;
}
printf("%d\n",totaldigits);
return 0;
}
|
for input 12334:
n = 12334 and initially totaldigits = 0;
Now consider the while loop:
n = 12334, n > 0 , so totaldigit will increase by 1, and n will be 1233, because n = n/10;
n = 1233, n > 0 , totaldigit = 2, n = 123
n = 123, n > 0 , totaldigit = 3, n = 12
n = 12, n > 0, totaldigit = 4, n = 1
n = 1, n > 0, totaldigit = 5, n = 0, because 1/10 = 0
n = 0 ,condition fails ( n > 0) and will exit from the loop
so our result is 5, i.e totaldigits = 5
Hope you get it.
Try yourself: Output the summation of the digits of n ( tips: think about % operator, i will cover later)
Back to Problem list