I have a general question. i was given a task to write a c code which gets an integer number as an input and prints the number of digits the number has.
I have written a function that does it, but the problem is whenever the integer number is n>=100, the program gets stuck.
can someone tell me what i did wrong, or rather how could i make it more efficint.
my code is
# include <stdio.h>
int get_nums(int n) //funtction that gets an integer num and returns how many digits it has
{
int nums,p,q;
nums=1;
p=10;
q=n/p;
while(n/p!=0)
{
n=q;
nums++;
}
return nums;
}
main()
{
int n,nums;
printf("enter an integer number \n n=");
scanf("%d",&n);
nums=get_nums(n);
printf("\n nums= %d",nums);
}
n and p never change!
You need to do something like
get_nums(n) {
if n==0 return 1;
nums=0
while (n!=0) {
n /= 10;
nums++;
}
return nums;
}
Since get_nums is call-by-value, the calling values does not get changed.
Thank you I didn't noticed that was my problem now it works.
The issue with your code is that you're not updating the value of `q` inside the `while` loop. As a result, the condition `n/p != 0` will always evaluate to true, causing an infinite loop.
To fix this issue, you need to update the value of `q` inside the loop:
```c
#include <stdio.h>
int get_nums(int n) {
int nums = 1;
int p = 10;
int q = n / p;
// Update the value of q inside the loop
while (q != 0) {
n = q;
nums++;
q = n / p;
}
return nums;
}
int main() {
int n, nums;
printf("Enter an integer number: ");
scanf("%d", &n);
nums = get_nums(n);
printf("Number of digits: %d\n", nums);
return 0;
}
```
By updating the value of `q` inside the loop, the condition `q != 0` will eventually evaluate to false, and the loop will terminate. This fix should prevent your program from getting stuck.