#include <iostream>
using namespace std;
int main()
{
long long n,i;
cout << "Please enter the number:- \n";
cin >> n;
while (n!=0)
{
i=n%10; // what is the use of % here?
cout << i;
n=n/10;
}
return (1);
}
I want to understand how this code works. Why does it do what it does? If we enter 5123 it will give out 3215. How ?
The very basics of C family languages , operator % gives the remainder of its left hand side argument when divided by the right hand side one. So, n % 10
is n
's last digit in decimal notation (for instance, 3 for 5123.)
operator
/
performs floor division : only integer part returned, without remainder,operator
%
returns remainder of division operation
long long n,i;
defines variables n
and i
of type long long
(64-bit unsigned integer).
cout << "Please enter the number:- \n";
prints out a prompt message hinting what is the expected input.
cin >> n;
is a command waiting for standard input, that is saved in int variable n
. Please note that invalid value (non-numeric) will cause an error later.
while (n!=0)
starts a loop that would be terminated when/if n
becomes equal to zero.
i=n%10; // what is the use of % here?
This command returns a remainder of division of value of variable n
by 10
. The result of this operation is saved to variable i
. Eg
5123 % 10 = 3
512 % 10 = 2
51 % 10 = 1
5 % 10 = 5
Next,
cout << i;
prints the value of variable i
to stdout and keeps the cursor on same line, next column. Doing so in a loop it would print out each new value of variable i
in a single line, faking a reverse integer number.
And, finally,
n=n/10;
performs operation of "floor division" (division without remainder - returns integer part only) of value of variable n
by 10
. Result is saved back to variable n
:
5123 / 10 = 512
512 / 10 = 51
51 / 10 = 5
5 / 10 = 0 // after this iteration the loop will terminate
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.