Darkphoton Darkphoton - 1 month ago 5
C Question

Finding all Well-Ordered Numbers within a range, how to print last value before while loop stops in C and print only 10 values per line?

The objective of the C-program is to print out all the well-ordered numbers between 100 and 999. Well-ordered numbers are numbers that have digits that are at least smaller by 1 when compared to the digit on it's right (e.g. 123, 456, and 159 are all well-ordered numbers).

I start off setting three

integer
values
x
,
y
, and
z
values at
1
,
2
, and
3
respectively as that is the lowest well-ordered number possible in this range. My idea is to increment
z
first so that we get:
123, 124, 125, .. 129
, then whenever it reaches 9 it increments
y
by 1 and
z
is set back down to
y+1
and it follows from there: 134, 135, 136..139 etc. The
while loop
checks if the number has reached the last one in the range between
100
and
999
which is
789
. My so far "working" code is pasted below.

So far the logic works to print out every well-ordered number between
100-999
, but it can't print the last one which is
789
and stops printing at
689
before
x
is incremented one last time. I spent so long trying to figure it out but can't seem to find where to place this print or where the logic can be changed in order to access this final print where
x
is incremented once more so that
789
shows in the answer.

Also the problem I'm working on mentions to print only 10 numbers before returning, and I also couldn't find a way to do this. I'm quite new to the C language so I was wondering if anyone can figure this out and give me some hints or guidance? Have I completely gone about this the wrong way and there is a simpler way to do this?

Thank you all for helping in advance.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
int x, y, z;
x = 1;
y = 2;
z = 3;

while(x != 7 || y != 8 || z != 9) {
printf("%d%d%d \n", x, y, z); // print well-ordered number

if(y==8) {
x++; // only increment x when y is reached the last position
y = x+1; // put y in the next correct position
z = y; // put z in the next correct position
}
if(z==9) {
y++; // only increment y when z's reached the last position
z = y; // reset z's position
}

z++; // increment z as it's always the first priority to maintain a well-ordered number

}


return 0;


}

Answer

Instead of checking for != , go for <= .

Rest everything is fine.