How to find the digit previous to a given digit in a number with C

1 Answer

0 votes
#include <stdio.h>

// Finds the digit that comes before the target digit when scanning from right to left.

int find_previous_digit(int number, int target) {
    int previous = -1; // To store the previous digit (default: -1 if not found)
    int current;

    while (number > 0) {
        current = number % 10; // Extract the last digit
        number /= 10;          // Remove the last digit

        if (current == target) {
            if (number != 0) {
                return number % 10;   // Return the previous digit if target is found
            }
        }
        previous = current;    // Update the previous digit
    }

    return -1; // Return -1 if the target digit is not found
}

int main() {
    int number = 8902741;
    int target = 7;

    int result = find_previous_digit(number, target);

    if (result != -1) {
        printf("The digit before %d in %d is %d.\n", target, number, result);
    } else {
        printf("The digit %d is not found or has no previous digit in %d.\n", target, number);
    }

    return 0;
}



/*
run:

The digit before 7 in 8902741 is 2.

*/

 



answered Oct 18, 2025 by avibootz
edited Oct 21, 2025 by avibootz
...