Piyush Zalani
Piyush Zalani

Reputation: 31

while loop is not breaking even if the condition is satisfied

I have created a program to print armstrong number, but the inner while loop is not breaking, it should break when the value is 0, but it is going into continuous loop.

Can anyone tell me what's wrong in my program. Is this the correct behaviour of compiler.

#include<stdio.h>
int main()
{
        int i=1,n,a=0;
        while(i<=500)
        {
                printf("1st i = %d\n",i);
                while(i > 0)    //This loop is not breaking.
                {
                        printf("2nd i = %d\n",i);
                        n = i%10;
                        printf("n = %d\n",n);
                        a = n*n*n + a;
                        i = i/10;
                        printf ("3rd i = %d\n",i);
                        printf ("a = %d\n",a);
                        if (i==0)
                                break;
                }
                if (a==i)
                        printf("Number is Armstrong");
                i++;
        }
        return 0;
}

Please try running the program, it seems to be correct but it is not working.

Upvotes: 0

Views: 505

Answers (1)

angrykoala
angrykoala

Reputation: 4064

You are using same variable (i) for both loops, and in the inner loop the condition of exit is i being 0 or negative, but the only change in this variable in the inner loop is i=i/10 which usually gives unexpected results when using with int.

Also, the i will never reach 500 in the outer loop, as it is decreased in the inner loop. I'm not sure why are you doing this, but check if you have to use the same variable in both loops

Upvotes: 3

Related Questions