C program to find first and last digit of a number

Category: C Program

Learn how to efficiently extract the first and last digits of a number in C programming. Explore a concise method to find these digits and enhance your coding skills with this tutorial.

In this article, we'll explore how to create a simple C program to find the first and last digits of a number.

Understanding First and Last Digits

  • First Digit: The leftmost digit in a number.
  • Last Digit: The rightmost digit in a number.

C program to find first and last digit of a number

Let's delve into the C programming language to create a program that finds the first and last digits of a number.

#include <stdio.h>

int main() {
    int number, first_digit, last_digit;

    // Input from the user
    printf("Enter a number: ");
    scanf("%d", &number);

    // Finding the last digit
    last_digit = number % 10;

    // Finding the first digit
    while (number >= 10) {
        number /= 10;
    }
    first_digit = number;

    // Displaying the first and last digits
    printf("First digit: %d\n", first_digit);
    printf("Last digit: %d", last_digit);

    return 0;
}

Output

Enter a number: 12345
First digit: 1
Last digit: 5

Finding the Last Digit: The program finds the last digit by taking the remainder when the number is divided by 10 (number % 10).

Finding the First Digit: To find the first digit, the program continuously divides the number by 10 until the number becomes less than 10, leaving the first digit as the value of number.

In this article, we've created a simple C program that efficiently finds the first and last digits of a number. Understanding how to extract these digits from a number is fundamental in various programming scenarios.


Recommended Posts