C

How to Get the First and Last Digit of a Number in C

In this tutorial, we are going to see how to get the first and last digit of a number in C. The following C program, ask the user to enter a number and then find the first and last digits of the number without using loops in C programming language.

You should know how to use POW() function in C.
 

How to Get the First and Last Digit of a Number in C
#include <stdio.h>
#include <math.h>

int main()
{
    int nbr, first, last, l;
 
    printf("\nEnter a number: ");
    scanf("%d", & nbr);
    
    // This will return the total number of digits - 1
    l = log10(nbr);   
    first = nbr / pow(10, l);
    
    last = nbr % 10;
      
    printf("\nThe first digit is %d", first);
    printf("\nThe last digit is %d", last);
 
    return 0;
}

Output:

Enter a number: 123

The first digit is 1
The last digit is 3

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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