# Print all n-digit numbers with absolute difference between sum of even and odd digits is 1 in C++

In this problem, we are given an integer n, and we have to print all n-digit numbers such that the absolute difference between the sum of digit of the number at even and odd places is 1. While creating the numbers leading 0’s are not considered.

The absolute difference is the difference between both numbers whose value is an absolute value (positive value).

Let’s take an example to understand the problem −

Input: n = 2
Output: 10 12 21 23 32 34 43 45 54 56 65 67 76 78 87 89 98
Explaination : taking an of the numbers from the output,
54, even digit - odd digit = 5 - 4 = 1
89, even digit - odd digit = 8 - 9 = -1 , |-1| = 1.

To solve this problem, we will have to find all the n-digit numbers with difference 1 or -1. For this, we will fix a digit place with all values and based on its position to be even or odd, call for values at other places in the number such that the condition remains satisfied.

## Example

The below program will illustrate our solution −

Live Demo

#include <iostream>
using namespace std;
void printNumber(int n, char* out, int index, int evenSum, int oddSum){
if (index > n)
return;
if (index == n){
if (abs(evenSum - oddSum) == 1) {
out[index] = ' ';
cout << out << " ";
}
return;
}
if (index & 1) {
for (int i = 0; i <= 9; i++) {
out[index] = i + '0';
printNumber(n, out, index + 1, evenSum, oddSum + i);
}
} else {
for (int i = 0; i <= 9; i++) {
out[index] = i + '0';
printNumber(n, out, index + 1, evenSum + i, oddSum);
}
}
}
int findNumberWithDifferenceOne(int n) {
char out[n + 1];
int index = 0;
int evenSum = 0, oddSum = 0;
for (int i = 1; i <= 9; i++) {
out[index] = i + '0';
printNumber(n, out, index + 1, evenSum + i, oddSum);
}
}
int main() {
int n = 3;
cout<<n<<" digit numbers with absolute difference 1 : \n";
findNumberWithDifferenceOne(n);
return 0;
}

## Output

3 digit number with absolute difference 1 −
100 111 120 122 131 133 142 144 153 155 164 166 175 177 186 188
197 199 210 221 230 232 241 243 252 254 263 265 274 276 285 287
296 298 320 331 340 342 351 353 362 364 373 375 384 386 395 397
430 441 450 452 461 463 472 474 483 485 494 496 540 551 560 562
571 573 582 584 593 595 650 661 670 672 681 683 692 694 760 771
780 782 791 793 870 881 890 892 980 991