How to Do Simple Arithmetic with C Programming

Math in your C source code is brought to you by the +, –, *, and / operators. These are the basic math symbols, with the exception of * and /, mostly because the × and ÷ characters aren’t found on the typical computer keyboard.

Operator Function
+ Addition
* Multiplication
/ Division
More C math operators exist, as well as a tumult of mathematical functions.

Calculations in C are made by placing values on either side of a math operator, just as you did all throughout school, but with the benefit of the computer making the calculations. Here is a sample:


#include <stdio.h>
int main()
  puts("Values 8 and 2:");
  printf("Addition is %d\n",8+2);
  printf("Subtraction is %d\n",8-2);
  printf("Multiplication is %d\n",8*2);
  printf("Division is %d\n",8/2);

Exercise 1: Create a project named ex0504 using the source code shown in Listing 5-2. Save. Build. Run.

The output looks something like this:

Values 8 and 2:
Addition is 10
Subtraction is 6
Multiplication is 16
Division is 4

What you see in this code are immediate calculations. That is, the value that’s calculated, the result, isn’t stored. Instead, the program does the math and deals with the result, which is stuffed into the %d conversion character in the printf() function’s formatting text.

Exercise 2: Write a program that displays the result of adding 456.98 and 213.4.

Exercise 3: Write a program that displays the result of multiplying the values 8, 14, and 25.

Exercise 4: Write a program that solves one of those stupid riddles on Facebook: What’s the result of 0+50*1–60–60*0+10? Solve the equation yourself before you run the program to see the computer’s result.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus

Inside Sweepstakes

Win $500. Easy.