I have a loop that doesn't exit and I need help converting a problem statement into a loop statement. Problem statement attached here:
#include <stdio.h>
int main(){
int num,last,newnum;
printf("ENTER YOUR NUMBER: ");
scanf("%d",&num);
while (num != 7 || num != -7 || num != 0){
last = num % 10;
last = last * 2;
num = num / 10;
num = num - last;
printf("%d",num);
}
}
You used the ||
operator when the &&
operator is the intended one. Let's look at why:
Say num == 0
, then the loop should not execute but instead becomes an infinite loop.
If we solve the boolean condition like so:
true || true || false
evaluates to true
. The only case where it would evaluate to false
would be if num
equalled 7, -7, and 0 simultaneously, which is impossible. Plugging a sample value into the boolean condition is a good tool for figuring out why your loop ends too early or goes on too long.
while (num != 7 && num != -7 && num != 0)
This ^ is what your loop should be. However, as I was testing it, it seemed to get stuck in infinite loops regardless. That is because the loop body won't always result in 7, -7, or 0, as not every number is divisible by 7. The number 499443, divisible by 7, didn't produce an infinite loop, but the number 2, which is not, did.
Also, indent your code in the future, as it can make debugging easier.
If you need a more practical way to check if a number is divisible by 7, then you can use:
if (num % 7 == 0) {
// Divisible by 7
}