Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

i got into this simple program in c programing, the program is simply reversing any input number by user, using a while loop, i dont know if its okay to post such a question but i didnt realy understood how the while loop works

int n, reverse = 0;

   printf("Enter a number to reverse
");
   scanf("%d",&n);

   while (n != 0)
   {
      reverse = reverse * 10;
      reverse = reverse + n%10;
      n = n/10;
   }

   printf("Reverse of entered number is = %d
", reverse);

i would be so thankfull if anyone could explain it to me

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

while(condition is true)
{
    // Do stuff.
    // Normally, but not always, the "stuff" we're doing is something that modifies
    // the condition we're checking.
}

So in your case as long as the content of n is not equal to 0, you will continue to execute the loop. If 0 is entered in the scanf() the loop will be skipped altogether.

At each iteration of your loop you're using the property of integer division to make the value of n smaller by a factor of 10. ie:

n = 541
n = n / 10 = 541/10 = 54
n = n / 10 = 54/10  = 5
n = n / 10 = 5/10   = 0 

So n will eventually be 0 and the loop will exit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...