Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with this c program? Debugging it suggests that the program is struck at while (sqroot != 0); [duplicate]

Here's a screenshot of debugging process
I am learning to program in C. I am trying to find if a number is a mirror image or not, But the program compiles error-free yet didn't give the desired result. Debugging the program shows that it struck at while (sqroot != 0);

    // Mirror number
    #include <stdio.h>
    #include <math.h>
    int main() {
            int num, rev1, rev2, rem1, rem2, sqr, sqroot;
            printf("Enter a number\n");
            scanf("%d", & num);
            sqr = pow(num, 2);
            while (sqr != 0) {
                    rem1 = sqr % 10;
                    rev1 = rev1 * 10 + rem1;
                    sqr = sqr / 10;

            }
            sqroot = sqrt(rev1);

            while (sqroot != 0); {
                    rem2 = sqroot % 10;
                    rev2 = rev2 * 10 + rem2;
                    sqroot = sqroot / 10;
            }

            if (rev2 == num)
                    printf("number is mirror");
            else
                    printf("Not a mirror number");

            return 0;
    }
like image 324
Gourav Thakur Avatar asked Jan 29 '26 13:01

Gourav Thakur


2 Answers

while (sqroot != 0); { ... } is an infinite loop. because the ; is considered as an empty instruction. An instruction (empty or not) just after an if (condition) or a while (condition) is considered to be the only instruction of the if, while, for scope.

It is the same than writting

while (sqroot != 0)
{
    ; /* Do nothing */
}
/* The scope below doesn't belong to the while */
{
    rem2 = sqroot % 10;
    rev2 = rev2 * 10 + rem2;
    sqroot = sqroot / 10;
}

Remove the ; and this problem should be solved.

while (sqroot != 0) {
    rem2 = sqroot % 10;
    rev2 = rev2 * 10 + rem2;
    sqroot = sqroot / 10;
}
like image 131
Cid Avatar answered Jan 31 '26 02:01

Cid


Initialize to rev1=0 and rev2=0.Because without a initial value,rev1 and rev2 will contain garbage values so that run time error will occur.

like image 31
BhaskarReddyKrish Avatar answered Jan 31 '26 03:01

BhaskarReddyKrish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!