If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C, to find the last digit of a number, you can use the modulo operator (%). The modulo operator returns the remainder of dividing the left operand by the right operand.
You can use the modulo operator to find the last digit of a number by dividing the number by 10 and taking the remainder. Since 10 is a power of 10, the remainder will be the last digit of the number.
Here is an example of how this can be done in C:
Copy code
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Last digit of %d is: %d", num, num % 10);
return 0;
}
This program prompts the user to enter an integer value, and then uses the modulo operator to find the remainder of dividing the number by 10. The remainder is the last digit of the number. Finally, it prints the result.
An alternative way to find the last digit of a number without using the modulo operator is to use the bitwise AND operator (&) and the bitwise NOT operator(~) to mask out the other digits.
Copy code
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Last digit of %d is: %d", num, num & ~(~0 << 4));
return 0;
}
The bitwise AND operator (&) masks out all but the last four bits of the number, while the bitwise NOT operator (~) inverts all the bits of the number, resulting in the last digit of the number.
It's worth mentioning that the negative numbers representation in C is using two's complement representation, so the last digit for negative number will be the last digit of the absolute value of the number.
Comments: 0