can anyone explain difference between operators in this program int i=10;int n=i++%5;int k=++i%5;

3.8k Views Asked by At

Freebase query example in python:

I know that I'm dyslexic and I don't have a PhD but I always find Google APIs incomprehensible. I just need an example on the following: Get the '/music/genre' list and then get the subgenres ...

could anyone explain difference between operators in this program

int i=10;j=10;

int n=i++%5;

int k=++j%5;

when i try this program iam getting n=0 ,k=1 and i=11,j=11 and ++a and a++ operator with other operators. thank you in advance.

3

There are 3 best solutions below

0
On

++ is called the increment operator, they increase the variable value by 1.

  • When used in any expression, ++i will first increment the value of i by one and then use the incremented value in expression.

  • On other hand when i++ is used in any expression, exp is evaluated with the initial value of i, and after that value of i is incremented by one.

int n=i++%5;
is equivalent to

int n=i%5; // i=10, n = 10%5 = 0;
i = i +1;  //i = 10 + 1 = 11

And int k = ++j%5;
is equivalent to

j = j + 1;      // j = 10 + 1 = 11 
int k = j % 5;  // k = 11 % 5 = 1


Hope this will be helpful.

0
On

i++ means "use the value of i then increment it"
++i means "increment the value of i then use it"
i%5 means "the remainder after dividing i by 5"

0
On

i++ and ++i are called increments and both are equivalent to i = i + 1 but differ in when the variable is incremented.

int i = 0;
System.out.println(i++); //This prints 0 then increments i to 1
System.out.println(++i); //This prints 2 because i is 
                         //incremented by 1 and then printed

% is the modulus operator and provides the remainder of a division problem.

6 % 4 = 2 //This is the same as saying 6 divided by 4,
          //but prints the remainder which is 2

For you specific problem:

int i=10;
int n=i++%5; //Here you have 10 % 5 which is 0, so n = 0.
             //After that i is incremented to 11.