Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable To Solve This Program In C-Language

[This is the code that Im facing problems in the output is always going till infinity kinda confused on what is the issue here I have attached an image here of the question of the code 1

#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);
    }
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading