If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To find the first digit of a number in C, you can use a combination of mathematical operations and control flow statements. Here is one way you can accomplish this:
Copy code
int firstDigit(int n) {
while (n >= 10) {
n /= 10;
}
return n;
}
This function takes an integer as an argument and uses a while loop to repeatedly divide the number by 10 until it is less than 10. The first digit of the number will be the last value of n before the while loop exits.
You could also use the modulus operator %
to get the last digit and then divide the number by 10 until the number is less than 10
Copy code
int firstDigit(int n) {
if(n<0) n = -n;
while (n >= 10) {
n /= 10;
}
return n;
}
This function first checks for negative numbers and make them positive, so the result is always positive, and it uses a while loop to repeatedly divide the number by 10 until it is less than 10. The first digit of the number will be the last value of n before the while loop exits.
This function assumes that the input number is always a positive number. If the input number can be negative, it's important to handle this case before the while loop.
Comments: 0