This blog is under construction

Monday, 8 July 2013

C program to calculate modulus

Write a C program to calculate modulus of a number / two numbers.


  #include <stdio.h>
  int main() {
        int num1, num2;

        /* get the first input from the user */
        printf("Enter the value for first number:");
        scanf("%d", &num1);

        /* find the modulus for num1 */
        printf("|%d| = ", num1);
        if (num1 < 0) {
                num1 = num1 * (-1);
        }
        printf("%d\n", num1);

        printf("Enter the value for second number:");
        scanf("%d", &num2);

        /* find the modulus for num2 */
        printf("|%d| = ", num2);
        if (num2 < 0) {
                num2 = num2 * (-1);
        }
        printf("%d\n", num2);
        /* find num1 modulo num2 */
        printf("%d modulo %d is %d\n", num1, num2, num1 % num2);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for first number:-100
  |-100| = 100
  Enter the value for second number:-93
  |-93| = 93
  100 modulo 93 is 7





See Also:

1 comment: