# Number of n digit stepping numbers in C++

C++Server Side ProgrammingProgramming

In this this tutorial, we are going to write a program that counts the number of n digit stepping numbers.

The stepping number is a number where the difference between the consecutive digits is 1.

You are given a number n representing the number of digits. You need to count the total number of stepping numbers with n digits.

Let's see the steps to solve the problem.

• Initialise the number n.

• Initialise the count to 0.

• Write a loop that iterates from the lowest n digit number to highest n digit number.

• Check whether the current number is stepping number or not.

• Increment the count if the current number is a stepping number.

• Return the count.

## Example

Let's see the code.

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool isSteppingNumber(int n) {
int previousDigit = -1;
while (n) {
int currentDigit = n % 10;
if (previousDigit != -1 && abs(previousDigit - currentDigit) != 1) {
return false;
}
previousDigit = currentDigit;
n /= 10;
}
return true;
}
int getSteppingNumbersCount(int n) {
int lowestNumber = pow(10, n - 1), highestNumber = pow(10, n) - 1;
int count = 0;
for (int i = lowestNumber; i <= highestNumber; i++) {
if (isSteppingNumber(i)) {
count += 1;
}
}
return count;
}
int main() {
int n = 3;
cout << getSteppingNumbersCount(n) << endl;
return 0;
}

## Output

If you run the above code, then you will get the following result.

32

## Conclusion

If you have any queries in the tutorial, mention them in the comment section.