C Program to Find First and Last Digit of a Number


Write a C program to find first and last digit of the user input number, without using looping.

Related Read:
Basic Arithmetic Operations In C

Source Code: C Program to Find First and Last Digit of a Number

 
#include < stdio.h >
#include < math.h >

int main()
{
    int num, first, last, count;

    printf("Enter an integer number\n");
    scanf("%d", &num);

    count = log10(num);

    first = num / pow(10, count);
    last  = num % 10;

    printf("First Digit = %d\nLast Digit = %d\n", first, last);

    return 0;
}

Output 1:
Enter an integer number
123
First Digit = 1
Last Digit = 3

Output 2:
Enter an integer number
123456
First Digit = 1
Last Digit = 6

Output 3:
Enter an integer number
15937
First Digit = 1
Last Digit = 7

Output 4:
Enter an integer number
5986
First Digit = 5
Last Digit = 6

Output 5:
Enter an integer number
964801
First Digit = 9
Last Digit = 1

C Program to Find First and Last Digit of a Number


[youtube https://www.youtube.com/watch?v=4D6kDTQNk6E]

YouTube Link: https://www.youtube.com/watch?v=4D6kDTQNk6E [Watch the Video In Full Screen.]


Logic To Find First and Last Digits of a Number

If user enters a number 123. i.e., num = 123; Then num % 10 would give the last digit of the number i.e., 3. To get first digit, we need to know the number of digits present in the number. To get that we make use of a built-in method called log10(). log10() returns the number of digits present in the number minus 1. That is because, it starts the count from 0. So if num = 123, log10(num) will return 2 and not 3. We store the number of digits inside variable count.

Now we use pow() method and calculate 10 to the power of count(value present in variable count) i.e., pow(10, count); We divide the user entered number by pow(10, count); to get the first digit of the number.
i.e., First_Digit = num / pow(10, count);

Note: Both pow() and log10() are built-in methods present in header file math.h So we include that library file at the beginning of our C program source code.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

Your email address will not be published. Required fields are marked *