1,485 views
2 2 votes
Why printf("%d",5%-2); is 1, not -1.

1 Answer

2 2 votes

good one  

Does '%' mean either "mod" or "rem" in C?

In C  %mean   it will give remainder not mod 

First of all  modulo  and %    are different so stop calculating it on  google calculator  ( google calculator is calculating                       a modulo b  )

 7 %  3 -->  1  
 7 % -3 -->  1  
-7 %  3 --> -1  
-7 % -3 --> -1 

Modulo as Euclidean division   The wiki Euclidean division asserts 0 ≤ r < |b| which means the remainder aka "modulo operation." is always at least 0

 7 modulo  3 -->  1  
 7 modulo -3 -->  1  
-7 modulo  3 -->  2  
-7 modulo -3 -->  2   

Google uses a different definition of modulo 

 7 modulo  3 -->  1  
 7 modulo -3 --> -2 
-7 modulo  3 -->  2  
-7 modulo -3 --> -1 

coming to actual question how you calculate a% b      ,  remember  in result of a%b will take sign of numerator  ,  so you have to  just calculate a%b  as  you do it for  positive numbers , then see numerator i.e. a      sign if   sign of a  is  negative then   put  (-)  with your answer  , else if a is positive no need to do anythinh

Thank you !!

• edited by
Position:
Show:

Related questions

1 1 vote
0 0 answers
844
844 views
Akshay Nair asked Jan 29, 2018
844 views
What is the output of the following program?void main(){printf("%d",5%2);printf("%d",-5%2);printf("%d",5%-2);printf("%d",-5%-2);printf("%d",2%5);}A) 1,-1 -1 1 0B)1 -1 1 -...
7 7 votes
3 answers 3 answers
1.7k
1.7k views
Parshu gate asked Nov 20, 2017
1,692 views
What is the output of the following program?#include<stdio.h int main() { int array[]={10, 20, 30, 40}; printf(“%d”, -2[array]); return 0; }$-60$$-30$$60$Garbage value
1 1 vote
1 answers 1 answer
1.7k
1.7k views
kaveeshnyk asked May 7, 2019
1,697 views
#include<stdio.h int main(){ int (*a)[5]; int arr[5][5]={ {10,65,300,400,500}, {100,20,3000,40,5000} }; a = arr; ++a ; char *ptr = (char*)*a...
0 0 votes
2 2 answers
959
959 views
kallu singh asked Aug 12, 2017
959 views
Consider the following C programint f1(int n) { if(n == 0 || n == 1) return n; else return (2*f1(n-1) + 3*f1(n-2)); }Consider the program given in above question, f1(8) a...