C program to Find First and Last Digit of a Number

C program to Find First and Last Digit of a Number

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

Recommended C Programs

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published.