Meaning of the expression n %= 100

Asked

Viewed 2,059 times

0

I have studied C and came across a very difficult problem that after a lot of trying, I gave up and went to look for an algorithm ready on the internet to study on it, but the expression n %= 100 I could not understand at all. I searched several programming and math sites but all I could find was that the percentage symbol in the middle of two whole numbers returned the rest of the division, and this I already knew, but when there’s an equality together?

If it helps the problem is the 1018 of the URI beginner module.

Here’s the code I’m studying:

#include <stdio.h>
int main()
{
    int n;
    scanf("%d", &n);
    printf("%d\n", n);
    printf("%d nota(s) de R$ 100,00\n", n/100);
    n %= 100;
    printf("%d nota(s) de R$ 50,00\n", n/50);
    n %= 50;
    printf("%d nota(s) de R$ 20,00\n", n/20);
    n %= 20;
    printf("%d nota(s) de R$ 10,00\n", n/10);
    n %= 10;
    printf("%d nota(s) de R$ 5,00\n", n/5);
    n %= 5;
    printf("%d nota(s) de R$ 2,00\n", n/2);
    n %= 2;
    printf("%d nota(s) de R$ 1,00\n", n);
    return 0;
}
  • Do you understand that n % 100 is the rest of the n for 100?

1 answer

0


The operator % (module) returns the rest of the division between two integers. When we find an expression like x = 5 % 2; that means that x will receive the rest of the 5 for 2, that is to say, x will store the value 1. Mathematically, 5xmod2.

It is important to note that % only operates on whole numbers, so any attempt to use it with other type operands, float for example, will result in error.

Already the expression n %= 100; is a form of syntactic sugar equivalent to n = n % 100; and, among other forms, can be rewritten as:

aux = n % 100;
n = aux;

Some other examples of syntatic sugar in C-based languages are:

a += 5;    // a = a + 5
b -= 4;    // b = b - 4
c *= 3;    // c = c * 3
d /= 2;    // d = d / 2
  • 1

    I think it’s interesting to talk about the module operator % to clarify to AP what is happening. I also have some observations when it comes to post-fixed increment/decrease operators, because that’s not exactly what happens when used in expressions

  • @Jeffersonquesado, I didn’t think it necessary to explain the operator % because there is already, in the question itself, a brief description of what it does. As for the post-fixed operators, you are absolutely right!

  • 1

    I find it relevant to at least mention a little bit about the rest of the division, as the answers are not only for the author of the question, but for all future visitors (and as you noticed, it is only briefly described in the question). The rest of the answer seems good, well formatted and well illustrated. It is on the right track.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.