First 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!

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.

6. Function

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?