Last Digit of a Number In C Language

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

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.

4. Operators

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?