0

write a program that input an integer and passes it to function.The function should return the number of digits in that number .

Example.. if the integer is 68 .Then function should return 2.

3rd Dec 2016, 5:21 AM
Abrar Hussain
Abrar Hussain - avatar
8 Answers
+ 4
#include <iostream> using namespace std; int func(int num){ int count=0; while(num) { num/=10; count++; } return count; } int main() { int num,c; cout<<"Enter a number\n"; cin>>num; c=func(num); cout<<c; return 0; }
3rd Dec 2016, 6:07 AM
Midhun Mathew
+ 3
@Hussain I will explain with an example assume it's a 3 digit number 456 initially count is 0 in 1st iteration 456 is divided by 10 and becomes a 2 digit number 45. count becomes 1 in 2nd iteration 45 is divided by 10 and becomes a 1 digit number 4. count becomes 2 in 3rd iteration 4 is divided by 10 and becomes a 0 . count becomes 3 and it exits the loop.
3rd Dec 2016, 2:28 PM
Midhun Mathew
0
#include <iostream> using namespace std; int num_dig(long long num) { int digits(1); while(!(num> >= 0 && num < 10) ) { num /= 10; ++digits; } return digits; } int main() { long long num = 54375; cout << num << " has " << num_dig(num) << " digits"; return 0; }
3rd Dec 2016, 6:56 AM
Elio
Elio - avatar
0
#Midhun_mathew its a fine code but i can't understand [ num/=10 and count++ ] when i'm enter 3 digit number then how it's work plz guide me its really helpfull for me thanks
3rd Dec 2016, 2:21 PM
Abrar Hussain
Abrar Hussain - avatar
0
@Mathew thanks JAZAKALLAH
3rd Dec 2016, 4:13 PM
Abrar Hussain
Abrar Hussain - avatar
0
@Mathew thanks JAZAKALLAH
3rd Dec 2016, 4:13 PM
Abrar Hussain
Abrar Hussain - avatar
0
@Elio your code not run in Dev C++! plz re check Thanks
3rd Dec 2016, 4:18 PM
Abrar Hussain
Abrar Hussain - avatar
0
what's the error you get? it could be this line int digits (1); change to int digits = 1;
3rd Dec 2016, 5:13 PM
Elio
Elio - avatar