Home > OS >  what does this variable name do in the Do-While loop expression and what is the meaning of its exist
what does this variable name do in the Do-While loop expression and what is the meaning of its exist

Time:11-09

im trying to learn how to reverse a number but came across a problem about this Do-While loop. Specifically while (n1). Usually i just see people put in a condition with about comparison.

#include <iostream>
#include <conio.h>
using std::cout;
using std::cin;
using std::endl;
int main()
{

    long int n1, n2, Rinteger = 0;
    cout << "Enter an integer: " << endl;
    cin >> n1;
    n2 = n1;
    do
    {
        Rinteger *= 10; 
        int digit = n1 % 10; 
        Rinteger  = digit;
        n1 /= 10; 
    } while (n1);
    
    cout << "Initial integer: " << n2 << "." << endl;
    cout << "Reversed integer: " << Rinteger << "." << endl;
    return 0;
}

There are other ways to reverse an integer but i am curious about how does this Do-While loop works

CodePudding user response:

while(n1) without a comparison just means while (n1 != 0) (C treats zero/NULL values as false, all other values as true). So the loop body is always entered once (thanks to being a do/while, rather than a plain while), and continues as long as n1 is not reduced to zero.

CodePudding user response:

This means to repeat while n1 is true. In C , an int is considered true when it's nonzero.

CodePudding user response:

while loop only enter´s if the condition is true. do-while loop enter´s at least once, then check if the condition is true to continues.

  • Related