![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Modulus of Negative Numbers in C
Here we will see what will be the result if we use negative numbers to get the modulus. Let us see the following programs and their outputs to get the idea.
Example
#include<stdio.h> int main() { int a = 7, b = -10, c = 2; printf("Result: %d", a % b / c); }
Output
Result: 3
Here the precedence of % and / are same. So % is working at first, so a % b is generating 7, now after dividing it by c, it is generating 3. Here for a % b, the sign of left operand is appended to the result. Let us see it more clearly.
Example
#include<stdio.h> int main() { int a = 7, b = -10; printf("Result: %d", a % b); }
Output
Result: 7
If we interchange the sign of a and b, then it will be like below.
Example
#include<stdio.h> int main() { int a = -7, b = 10; printf("Result: %d", a % b); }
Output
Result: -7
Similarly if both are negative, then also the result will be negative.
Example
#include<stdio.h> int main() { int a = -7, b = -10; printf("Result: %d", a % b); }
Output
Result: -7
Advertisements