C program to find and print first and last digit of a number; Through this tutorial, we will learn how to find and print first and last digit of a number in c program using log() & pow() , while loop.
C Program to Find First and Last Digit Of a Number
- C Program to Print First and Last Digit Of a Number using Log10() and pow()
- C Program to Print First and Last Digit Of a Number using While Loop
C Program to Find First and Last Digit Of a Number using Log10() and pow()
/**
* C program to find first and last digit of a number
*/
#include <stdio.h>
#include <math.h>
int main()
{
int n, firstDigit, lastDigit, digits;
/* Input a number from user */
printf("Enter any number: ");
scanf("%d", &n);
/* Find last digit */
lastDigit = n % 10;
/* Total number of digits - 1 */
digits = (int)log10(n);
/* Find first digit */
firstDigit = (int)(n / pow(10, digits));
printf("First digit = %d\n", firstDigit);
printf("Last digit = %d\n", lastDigit);
return 0;
}
The output of the above c program; as follows:
Enter any number: 1235 First digit = 1 Last digit = 5
C Program to Find First and Last Digit Of a Number using While 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;
}
The output of the above c program; as follows:
Enter number = 2 first digit = 2 and last digit = 2