Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

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
...