Just to show you what I had in mind:
Code:
#include <stdio.h>
int main(void) {
int number = 0;
do {
fputs("Enter a four digit number: ", stdout);
scanf("%d", &number);
while (getchar() != '\n'); // discard all characters not convertible into an int
} while (number < 1000 || number > 9999);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
// I
int digits[4] = { 0 };
for (int divisor = 1000, idx = 0; idx < 4; divisor /= 10, ++idx) {
digits[idx] = ((number / divisor + 7) % 10);
number %= divisor;
}
const int newNumber = digits[0] * 10 +
digits[1] +
digits[2] * 1000 +
digits[3] * 100;
*/
/*
// II
int newNumber = 0;
for (int divisor = 1000, factor = 10; divisor; divisor /= 10) {
if (divisor == 100) {
factor = 1;
} else if (divisor == 10) {
factor = 1000;
} else if (divisor == 1) {
factor = 100;
} // else, both divisor and factor still have their initial values
newNumber += ((number / divisor + 7) % 10) * factor;
number %= divisor;
}
*/
// III
static const int factors[] = { 100, 1000, 1, 10 };
int newNumber = 0;
for (const int *iter = factors, *const end = iter + 4; iter < end; ++iter) {
newNumber += *iter * ((number + 7) % 10);
number /= 10;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
printf("New formed number: %04d\n", newNumber);
return 0;
}
I and II is using your math with the divisor variable. In I you'll find my original proposal to separate the digits first. In II branching is used to choose the right factor. This will add some unnecessary complexity though. III is what I would have come up after all. No additional branching, and no divisor variable with its additional division operations.