C Program to find first and last digit of a given number

In this blog post, we learn how to write a C Program to find the first and last digit of a number?. We will write the C Program to find the first digit and last digit of a number using the Arithmetic Operators. Here we will find first and the last digit of a number using the loop and without using the loop. Let see an example,

Input : 12345 

Output : 

First digit => 1

last digit => 5

 

Algorithm to find the first digit and the last digit using the loop:

 

  • Ask the user to enter an integer number. Suppose n = 12345, where n is an integer variable.
int n = 12345;
  • To find the last digit of a number, we use modulo operator %. When modulo divided by 10 returns last digit of the input number.
lastDigit = num % 10
  • To find the first digit of a number we divide the given number by 10 until the number is greater than 10. In the end, we get the first digit.

 

C Program to find first and last digit of a given number using loop:

 

#include <stdio.h>

int main()
{
    int n, sum=0, firstDigit, lastDigit;

    printf("Enter number = ");
    scanf("%d", &n);

    // Find last digit of a number
    lastDigit = n % 10;

    //Find the first digit by dividing n by 10 until n greater then 10
    while(n >= 10)
    {
        n = n / 10;
    }

    firstDigit = n;

    printf("first digit = %d and last digit = %d\n\n", firstDigit,lastDigit);

    return 0;
}

Output:

Enter number = 12345
first digit = 1 and last digit = 5

 

 

C Program to find first and last digit of a given number using without loop:

 

#include <stdio.h>

int main()
{
    int n,firstDigit, lastDigit,digit;

    printf("Enter number = ");
    scanf("%d", &n);

    //Find last digit of a number
    lastDigit = n % 10;

    //Find total number of digit - 1
    digit    = (int)log10(n);

    //Find first digit
    firstDigit = (int) (n / pow(10, digit));


    printf("first digit = %d and last digit = %d", firstDigit,lastDigit);

    return 0;
}

 

 

 

One comment

Leave a Reply

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