Home > database >  Modulo % in C
Modulo % in C

Time:07-08

How actually Modulus work in this code i am writing below,

int n;
cin>>n;

while(n != 0){
   int ans = n % 10;
   cout<<ans;
   n = n / 10;
}

for example input value is "456" , first ans will be 6 and n = 45 next next itr - ans will be 5 and n = 4;

Main Question n = 4 this time now 4 % 10 , in calculator i try this it come 0.4 in int value it should be 0, but in c it showing me ans = 4 this time , hows it possible or how it works in background?

CodePudding user response:

Thr modulus operator is not for computing percentages.

a % b

returns the remainder after dividing a by b, so the answer of 4 is correct for your example.

CodePudding user response:

From the C 14 Standard (5.6 Multiplicative operators)

2 The operands of * and / shall have arithmetic or unscoped enumeration type; the operands of % shall have integral or unscoped enumeration type. The usual arithmetic conversions are performed on the operands and determine the type of the result.

and

4 The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second.

So 4 can be represented like 4 / 10 4 % 10. 4 / 10 yields 0 and 4 % 10 yields 4.

By the way the code snippet has a logical error

int n;
cin>>n;

while(n != 0){
   int ans = n % 10;
   cout<<ans;
   n = n / 10;
}

If the user will enter 0 then nothing will be outputted though the expected output should be 0.

You need to rewrite the code snippet using do-while loop instead of the while loop. For example

int n;
cin>>n;

do{
   int ans = n % 10;
   cout<<ans;
   n = n / 10;
} while ( n != 0 );

As for your calculator then it seems the key % denotes the floating point division. So 4 % 10 yields 0.4. It looks similar if to write in C

std::cout << 4 / 10.0 << '\n';
  • Related