Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what does this variable name do in the Do-While loop expression and what is the meaning of its existence in it?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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, and continues as long as n1 is not reduced to zero.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading