Performing Arithmetic

While the principles of arithmetic in C are exactly like those you learned in school, the actual results are more complex because of how C works with the different number types. For this reason, choosing the appropriate data type depends not only on the possible values it might store but also on how it will be used.

The standard operators for performing arithmetic are

  • +, for addition

  • -, for subtraction

  • *, for multiplication

  • /, for division

  • %, for modulus (finding the remainder of a division)

Using these operators, here are some sample calculations:

int a = 3;
int b = 2;
int c;
c = a + b; /* 5 */
c = a - b; /* 1 */
c = b - a; /* -1 */
c = a * b; /* 6 */
c = a / b; /* 1, not 1.5! */
c = a % b; /* 1 */

When you divide one integer by another integer, the result will always be an integer, meaning that any remainder (fraction) is dropped, as in the previous example. For this reason, you'll pretty much always want to use floats for division. If one of the two numbers involved in a division is a float, a float will automatically be the result:

float a = 3.0;
float b = 2.0;
float c;
c = a / b; /* 1.5 */

Conversely, the modulus operator (%) can only be used on integers. You cannot return the remainder of a division when one of the two numbers is a float.

To perform some arithmetic, you'll create an example that turns inches into feet. This will also allow you to see how the different types perform within the context of standard arithmetic.

To perform arithmetic

1.
Create a new, blank text document in your editor or integrated development environment (IDE).

2.
Being by documenting the file (Script 3.1):

/* feet_inches.c - Script 3.1 */

Script 3.1. This measurement converter performs arithmetic using different number types.


This simple comment matches the script number to its name. Feel free to add as many other notes as you need to your code.

3.
Type the required include line:

#include <stdio.h>

4.
Begin defining the main() function.

int main(void) {

If you are confused by either this or the previous step, review the two previous chapters.

5.
Define the variables to be used:

unsigned short int inches = 3435
unsigned short int feet_int;
unsigned short int inches_remainder;
float feet_float;

This application makes use of four variables: three short integers and a standard float. Each of the integers is short, limiting their range, and unsigned, as they can't be negative. One, inches, is assigned a value with which calculations will be made.

6.
Determine how many feet are in the specified inches:

feet_int = inches/12;

Dividing 3435 by 12 gives the number 286.25. But, since feet_int, inches and 12 are all integers, feet_int will have a value of just 12, with the remainder being dropped.

7.
Calculate how many inches are left over after determining the feet:

inches_remainder = inches % 12;

To find out how many inches are left (which corresponds to the .25 decimal when dividing 3435 by 12), use the modulus operator. This operator must be applied only to integers and will return an integer as well (inches_remainder).

8.
Recalculate the division using floats:

feet_float = inches/12.0;

Even though the feet_float variable was defined as a float, to successfully make that calculation, either inches or 12 must also be a float. Here, 12 has been turned into a float by adding a decimal point and a zero. Strange as it may seem, if this line were

feet_float = inches/12;

the result would be just 286.0 and the remainder would be lost.

9.
Print the results of the calculations:

printf ("%u inches is %u feet, %u
inches.
", inches, feet_int,
inches_remainder);
printf ("As a float, that's %f
feet.
", feet_float);

These two lines print all of the values being used, thanks to the printf() function and the appropriate signifiers. The %u signifier is used to match the unsigned integers, although %d (the standard integer marker) would have also worked. If you want, you can change %f in the second statement to %0.2f to format the result to two decimal places.

10.
Add the getchar() function to pause execution of the application:

getchar();

Once again, this function is being used merely to halt execution of the application, waiting for the user to press Return or Enter before closing.

11.
Finish the main() function:

   return 0;
}

12.
Save the file as feet_inches.c.

13.
Compile the application (Figure 3.1).

Figure 3.1. Your compiler (Dev-C++ here) should report on any errors in the code.


14.
Debug the application, if necessary.

If your compiler indicated any errors, fix them and recompile.

15.
Run the application (Figure 3.2).

Figure 3.2. Run the executable file to see the results (here the application is being run through Apple's Xcode).


✓ Tips

  • If you've forgotten the proper signifiers for the printf() function, see Table 2.2 in Chapter 2, “Introduction to Data Types,” or see Appendix B, “Resources.”

  • Do not confuse the addition and subtraction operators with those used to indicate the sign of a number. Spacing makes all the difference:

    int a = +3; /* Positive 3 */
    int b = -2; /* Negative 2 */
    int c = a + b; /* 1 */
    
  • When using the modulus operator, if the first number (a in the introductory examples) is negative, the resulting remainder will always be negative. Otherwise, the resulting remainder will be positive.

  • The float type stores an approximation of values (for example, 2.0 might actually be stored as 1.9999999). For this reason, arithmetic using floats can be tricky and you should never check to see if two floats have the same value.

  • Each of the arithmetic operators can be combined with the assignment operator (=) to perform calculations and assign a value in one step. For example:

    int a = 10;
    a += 2; /* 12 */
    a -= 3; /* 9 */
    a *= 2; /* 18 */
    a /= 6; /* 3 */
    a %= 2; /* 1 */
    

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset