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

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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