There are some issues:
- You are looping on
number
and it eventually becomes zero.
- When you try to add to the
sum
, you want the original value of number
but you're using the partially modified value.
- You want to preserve the original value and use a temp copy in the loop.
- The
while (number >= 0)
in the outer loop won't stop immediately if a negative number is executed (i.e. an extra loop iteration is performed). We want to use an if
after the scanf_s
.
- Because
number
gets trashed by the inner loop, the outer loop will only execute once.
Here's the refactored code. It is annotated:
#include <stdio.h>
int
main(void)
{
int number = 1,
temp_var = 0,
sum = 0;
// NOTE/BUG: this will loop once too often
#if 0
while (number >= 0) {
#else
while (1) {
#endif
printf("Put in a number: ");
scanf("%d", &number);
// NOTE/FIX: correct way to stop on negative number
#if 1
if (number < 0)
break;
#endif
// NOTE/FIX: to prevent "number" from being trashed, we should use a temp
// value in the loop
int temp_number = number;
while (temp_number >= 1) {
temp_var = temp_number % 10;
if (temp_var == 7) {
sum = sum + number;
break;
}
temp_number = temp_number / 10;
}
}
printf("%d\n", sum);
return 0;
}
In the code above, I used cpp
conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
Here's a slightly cleaned up version that puts the digit match code in a function:
#include <stdio.h>
// hasdigit -- decide if a given number contains a given decimal digit
int
hasdigit(int number,int dig)
{
int temp_var;
int match = 0;
while (number != 0) {
temp_var = number % 10;
match = (temp_var == dig);
if (match)
break;
number = number / 10;
}
return match;
}
int
main(void)
{
int number;
int sum = 0;
while (1) {
printf("Put in a number: ");
scanf("%d", &number);
if (number < 0)
break;
if (hasdigit(number,7))
sum += number;
}
printf("%d\n", sum);
return 0;
}