How to find the digit next to a given digit in a number with C++

1 Answer

0 votes
#include <iostream>

int find_next_digit(int number, int target) {
    int next = -1; // To store the next 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) {
            return next;   // Return the next digit if target is found
        }
        next = current;    // Update the next digit
    }

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

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

    int result = find_next_digit(number, target);

    if (result != -1) {
        std::cout << "The digit after " << target << " in " << number << " is " << result << ".\n";
    } else {
        std::cout << "The digit " << target << " is not found or has no next digit in " << number << ".\n";
    }
}



/*
run:

The digit after 2 in 8902741 is 7.

*/

 



answered Oct 18, 2025 by avibootz
...