C Program to Get a Digit at Any Position of a Number

C Program to Get a Digit at Any Position of a Number

Retrieving a specific digit from a number is a common problem in programming. Whether you are working with numerical data, developing an application, or preparing for a coding interview, understanding how to extract a digit at a given position is a useful skill. In this article, we will explore an efficient C program to accomplish this task.

Understanding the Problem Statement

Given an integer number, our objective is to extract and display the digit at a specified position. The positions are counted from right to left, starting with 1 for the rightmost digit.

For example:

  • Input: Number = 56789, Position = 3
  • Output: Digit = 7

Approach to Solve the Problem

We can use a simple mathematical approach to extract the digit at any given position:

  1. Use a loop or division operation to remove the digits to the right of the desired position.
  2. Extract the last remaining digit using the modulus operator (%).

Implementation in C

Here is a well-structured C program to extract a digit from a given position in a number.

#include <stdio.h>

// Function to get the digit at a specified position
int getDigitAtPosition(int number, int position) {
    for (int i = 1; i < position; i++) {
        number /= 10; // Remove last digit
    }
    return number % 10; // Get last remaining digit
}

int main() {
    int number, position;
    
    // Input from user
    printf("Enter a number: ");
    scanf("%d", &number);
    printf("Enter the position: ");
    scanf("%d", &position);
    
    // Handling invalid positions
    if (position <= 0) {
        printf("Invalid position! Position should be greater than 0.\n");
        return 1;
    }
    
    // Calling the function
    int digit = getDigitAtPosition(number, position);
    
    // Displaying the result
    printf("The digit at position %d is: %d\n", position, digit);
    
    return 0;
}

Explanation of the Code

  1. Function getDigitAtPosition(int number, int position):
    • It removes digits from the number until it reaches the required position.
    • The modulus operator (% 10) extracts the last digit at that position.
  2. Handling User Input:
    • The program prompts the user to enter a number and the position of the digit to retrieve.
    • It ensures that the position is greater than 0 to prevent errors.
  3. Edge Case Handling:
    • If the position is greater than the number of digits, the function still works correctly and returns 0 (in case of leading zeroes when counting positions).
    • Negative numbers are handled correctly as integer division works the same way.

Example Runs

Example 1:

Input:

Enter a number: 987654
Enter the position: 4

Output:

The digit at position 4 is: 8

Example 2:

Input:

Enter a number: 34567
Enter the position: 2

Output:

The digit at position 2 is: 6

Alternative Approach Using Strings

Another method to solve this problem is by converting the number to a string and directly accessing the required character.

#include <stdio.h>
#include <string.h>

void getDigitFromString(int number, int position) {
    char numStr[20];
    sprintf(numStr, "%d", number); // Convert number to string
    int length = strlen(numStr);
    
    if (position > length || position <= 0) {
        printf("Invalid position!\n");
        return;
    }
    
    printf("The digit at position %d is: %c\n", position, numStr[length - position]);
}

int main() {
    int number, position;
    
    printf("Enter a number: ");
    scanf("%d", &number);
    printf("Enter the position: ");
    scanf("%d", &position);
    
    getDigitFromString(number, position);
    
    return 0;
}

Advantages of This Approach:

  • Simplifies extraction using string indexing.
  • Works for very large numbers as long as they fit in the string representation.
  • Makes handling of leading zeros easier.

Conclusion

Extracting a digit from a specific position in a number can be done using simple mathematical operations or string manipulation. The mathematical approach is efficient for numerical computations, while the string-based method provides flexibility for larger numbers.

By understanding these approaches, you can efficiently extract digits in C and apply similar techniques in other programming languages as well.

6 Comments

  1. tony

    Teste both functions and does not works:

    printf(“%d\n”, getdigit(1234, 1));
    printf(“%d\n”, getdigit(1234, 2));
    printf(“%d\n”, getdigit(1234, 3));
    printf(“%d\n”, getdigit(1234, 4));

    Prints:
    3
    2
    1
    0

    Espected
    1
    2
    3
    4

    • Srikanta

      It is a matter of interpretation.
      In the examples here, the numbering is assumed from right to left, starting from 0.
      That means, for the number 1234:
      0-th position digit is: 4.
      1-st position digit is: 3.
      2-nd position digit is: 2.
      3-rd position digit is: 1.

      But you can change the getdigit() function to get your output like this:

      int getdigit(int num, int n)
      {
          int r;
          n = ((num==0)?1:log10(num)+1) - n;
      
          r = num / pow(10, n);
      
          r = r % 10;
      
          return r;
      }
      
  2. Your logic is going wrong..
    Plz try it to find out the 2nd digit..

    • Srikanta

      Thanks for your comment.
      I re-tested the program – both the logics. It worked as expected for the 2nd position also. It will help if you can provide an example.

Leave a Reply

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