C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
intAnswer = x % y; // This calculates the remainder (4)
printf("%d modulus (i.e. remainder of) %d equals %d", x, y,
intAnswer);
return 0;
}

The last math statement in this program might be new to you. If you need the remainder after integer
division, use C’s modulus operator (%). Given the values just listed, the following statement puts a 4
in intAnswer:


Click here to view code image


ansMod = x % y; /* 4 is the remainder of 19 / 5 */

You now know the three ways C divides values: regular division if a float is on either or both sides
of the /, integer division if an integer is on both sides of the /, and modulus if the % operator is used
between two integers.


Tip

You can’t use % between anything but integer data types.

The following short program computes the net sale price of tires:


Click here to view code image


// Example program #2 from Chapter 9 of Absolute Beginner's Guide to
// C, 3rd Edition
// File Chapter9ex2.c
/* This program asks the user for a number of tires and price per
tire. It then calculates a total price, adding sales tax. */
// If you find you use a sales tax rate that may change, use #define
// to set it in one place
#include <stdio.h>
#define SALESTAX .07
main()
{
// Variables for the number of tires purchased, price,
// a before-tax total, and a total cost
// with tax
int numTires;
float tirePrice, beforeTax, netSales;
/* Get the number of tires purchased and price per tire. */
printf("How many tires did you purchase? ");
scanf(" %d", &numTires);
printf("What was the cost per tire (enter in $XX.XX format)? ");
scanf(" $%f", &tirePrice);
Free download pdf