-1

Im a CSE fresher. I found this code on w3school and dont know whats going on.

#include <stdio.h>

int main() {
  // A variable with some specific numbers
  int numbers = 12345;
  
  // A variable to store the reversed number
  int revNumbers = 0;

  // Reverse and reorder the numbers
  while (numbers) {
    // Get the last number of 'numbers' and add it to 'revNumber'
    revNumbers = revNumbers * 10 + numbers % 10;
    // Remove the last number of 'numbers'
    numbers /= 10;
  }

  // Output the reversed numbers
  printf("%d", revNumbers);

  return 0;
}

Can anyone explain the loops condition?

2
  • 1
    The loop condition of the loop while (numbers) { is equivalent to while (numbers != 0 ) { Commented Jul 5 at 10:34
  • Looking at the answers, I noticed that everybody is assuming you know what numbers % 10 do. If you do, fine. If you didn't, that is the remainder operator. n % 10 gives you the remainder of the division n / 10. For example, if n =12345, n / 10 = 1234 (n is an int, so there is no decimal part) and the remainder of that division is 5 (n % 10 = 5). If you already knew that, sorry for the post.
    – rpsml
    Commented Jul 9 at 20:25

4 Answers 4

1

Can anyone explain the loops condition?

It keeps dividing until zero. Expressions in C evaluate to true if non-zero, otherwise false if zero.

Since it is integer division, there is never a remainder. So you get 12345, 1234, 123, 12, 1, then the loop stops.

1

Given the syntax:

while ( expression ) statement

a while loop executes a statement repeatedly, until the value of expression becomes equal to zero (1), so here the loop will end only when numbers equals 0.

The codeline:

numbers /= 10;

is equivalent to a decimal right shift, so at the end of the first iteration numbers evaluates 1234; after the second one (but before starting the third one) 123, and so on until no more digits will be left to be shifted since 0 have been reached.


(1) https://en.cppreference.com/w/c/language/while

0

So the Loop Condition is :

The while (numbers) loop continues until numbers becomes 0. In C, non-zero values are true, and zero is false.

Inside the Loop:

  1. revNumbers = revNumbers * 10 + numbers % 10;

    • This line takes the last digit of numbers and appends it to revNumbers.
  2. numbers /= 10;

    • This line removes the last digit from numbers.
0

It will loop until the variable 'numbers' reaches 0.

Initially it will evaluate numbers 12345. As the integer variable is non-zero it will return true. So it will enter the loop and divide it by 10 and so on, until it reaches 0 then it will be evaluated as false.

In C when you use integers like this non-zero == true and 0 or null == false

Not the answer you're looking for? Browse other questions tagged or ask your own question.