|
To make a successful C program (or any program for that matter) you need to learn some basic math operations. Computers "think" mathematically, so it is a good idea to be able to speak in mathematics. C lets you do just this.The Basics
You can incorperate these into your C statements (sentences). The following program will display the results of the calculations above using printf().
- Add = +
- 1000 + 2000 = 3000
- Subtract = -
- 700 - 500 = 200
- Multiply = *
- 25 * 4 = 100
- Divide = /
- 100 / 4 = 25
- Grouping = ( )
- (700 - 500) * 2 = 400
DOWNLOAD PROGRAM
#include <stdio.h> int main(void) { printf("1000 + 2000 = %d \n", 1000 + 2000); printf("700 - 200 = %d \n", 700 - 200); printf("25 * 4 = %d \n", 25 * 4); printf("100 / 4 = %d \n", 100 / 4); printf("(700 - 500) * 2 = %d \n", (700 - 500) * 2); return 0; }
I had to sneak in a few new things to the code besides the basic math features so that it would run. It's a piece of cake though. We only need to look at one line to understand the others.printf("1000 + 2000 = %d \n", 1000 + 2000);
The data placed between the " and " are tossed to the screen. So as expected, you will see
1000 + 2000 =But what about the %d? This says to print out an integer. The integer it will print is the result of the equation AFTER the comma. Specifically, this is a format specifier. There will be much more to say about these.
What about the \n? This is an escape sequence for a carrage return. It makes a new line.
Here is a quick glance of the precedence of the arithmetic operators. This will come in useful to know.
Operators Operations Order of evaluation ( ) Parentheses Always evaluate the expression between these first. If there are nested parentheses, do the inner most ones first, and move outwards one by one. If some parentheses are besides another, evaluate left to right. *, /, % Multiplication
Division
ModulusEvaluate these operations 2nd. If more than one exist next to eachother, evaluate them left to right. + , - Addition
SubtractionThese evaluate last. If more than one exist next to eachother, evaluate them left to right.