askvity

How to Print Remainder in C Programming?

Published in C++ Programming 2 mins read

To print the remainder in C programming, you use the modulo operator (%). This operator returns the remainder of a division operation between two integers.

Using the Modulo Operator

The basic syntax for calculating the remainder is:

remainder = dividend % divisor;

Where:

  • dividend is the number being divided.
  • divisor is the number dividing the dividend.
  • remainder is the result, the remainder of the division.

Example Code

Here's a simple C program demonstrating how to calculate and print the remainder:

#include <stdio.h>

int main() {
  int dividend, divisor, quotient, remainder;

  dividend = 15;
  divisor = 4;

  quotient = dividend / divisor;   // Integer division to find the quotient
  remainder = dividend % divisor;  // Modulo operator to find the remainder

  printf("Quotient = %d\n", quotient);
  printf("Remainder = %d\n", remainder);

  return 0;
}

Explanation:

  1. #include <stdio.h>: Includes the standard input/output library, which provides functions like printf for printing to the console.
  2. int main() { ... }: The main function where the program execution begins.
  3. int dividend, divisor, quotient, remainder;: Declares integer variables to store the dividend, divisor, quotient, and remainder.
  4. dividend = 15; and divisor = 4;: Assigns values to the dividend and divisor.
  5. quotient = dividend / divisor;: Performs integer division to calculate the quotient. In this case, 15 / 4 results in 3 (integer division truncates the decimal part).
  6. remainder = dividend % divisor;: Calculates the remainder using the modulo operator. 15 % 4 results in 3 because 15 divided by 4 is 3 with a remainder of 3.
  7. printf("Quotient = %d\n", quotient);: Prints the quotient to the console. \n adds a newline character for formatting.
  8. printf("Remainder = %d\n", remainder);: Prints the remainder to the console.
  9. return 0;: Indicates successful program execution.

When you run this code, the output will be:

Quotient = 3
Remainder = 3

Key Points

  • The modulo operator (%) only works with integer operands.
  • The remainder will always have the same sign as the dividend.
  • Understanding the modulo operator is fundamental for various programming tasks, such as checking for even or odd numbers, implementing circular buffers, and performing cryptographic operations.

Related Articles