This code is running properly when I use 1 digit numbers. But It's keep lagging on more digit numbers
Something is wrong. I'm trying to make a cade which can count number count of any natural number. Like number count of 2 is 1, 30 is 2, 456 is 3. My code is running for 1 digit numbers but not for two digit numbers.
#include<stdio.h>
void main(void)
{
int num,count,check;
float div;
printf("Enter a natural number\n");
scanf("%d", &num);
while (num<=0)
{
printf("Error\n");
printf("Enter a number\n");
scanf("%d", &num);
}
while(num>1)
{
count=1;
check=10;
div=num/check;
if(div<=1)
{
printf("Number count is\n%d", count);
break;
}
check = check*10;
count = count+1;
}
}
The problem with your solution is that after check
and count
are modified at the end of the loop, they are re-declared to 1
and 10
respectively at the beginning of the loop at every passage.
You need to move the declaration just before the while loop.
Also div
doesn't need to be a float
given that the decimal part of this number is irrelevant.
You could also use less variables by replacing check
by 10
and
using num
directly instead of temporarily storing results in div
.
I think this might be a simpler solution
#include <stdio.h>
int main(){
int num = 0, digits = 0;
while (num <= 0)
{
printf("Enter a natural number\n");
scanf("%d", &num);
num == 0 ? printf("Error\n") : 0;
}
for( ; num > 0; digits++)
num /= 10;
printf("number of digits: %d\n", digits);
}
As num
is continuously divided by 10, the decimal of the result gets truncated since num
is an int
while digits
steadily increases.