Performing Arithmetic Operations in C
In the C programming language, you can perform various arithmetic operations on numerical data types, such as integers (e.g., int
, long
, short
) and floating-point numbers (e.g., float
, double
). These operations include addition, subtraction, multiplication, division, and modulus (remainder).
Basic Arithmetic Operators
The basic arithmetic operators in C are:
- Addition:
+
- Subtraction:
-
- Multiplication:
*
- Division:
/
- Modulus (remainder):
%
Here's an example of how to use these operators in C:
#include <stdio.h>
int main() {
int a = 10;
int b = 4;
printf("Addition: %d\n", a + b); // Output: 14
printf("Subtraction: %d\n", a - b); // Output: 6
printf("Multiplication: %d\n", a * b); // Output: 40
printf("Division: %d\n", a / b); // Output: 2
printf("Modulus: %d\n", a % b); // Output: 2
return 0;
}
In the example above, we perform various arithmetic operations on the variables a
and b
, and then print the results using the printf()
function.
Order of Operations
When you have multiple arithmetic operations in an expression, the order of operations is determined by the precedence of the operators. The order of precedence in C is as follows:
- Parentheses
()
- Unary operators (e.g.,
++
,--
,+
,-
) - Multiplication
*
, Division/
, Modulus%
- Addition
+
, Subtraction-
You can use parentheses to change the order of operations and control the flow of the expression. Here's an example:
#include <stdio.h>
int main() {
int a = 10;
int b = 4;
int c = 2;
printf("Expression 1: %d\n", a + b * c); // Output: 18
printf("Expression 2: %d\n", (a + b) * c); // Output: 28
return 0;
}
In the first expression, the multiplication b * c
is performed first, and then the addition a + (b * c)
is executed. In the second expression, the parentheses (a + b)
are evaluated first, and then the multiplication (a + b) * c
is performed.
Floating-Point Arithmetic
When working with floating-point numbers (e.g., float
, double
), the arithmetic operations behave slightly differently. Here's an example:
#include <stdio.h>
int main() {
float a = 10.5;
float b = 3.7;
printf("Addition: %.2f\n", a + b); // Output: 14.20
printf("Subtraction: %.2f\n", a - b); // Output: 6.80
printf("Multiplication: %.2f\n", a * b); // Output: 38.85
printf("Division: %.2f\n", a / b); // Output: 2.84
return 0;
}
In this example, we perform arithmetic operations on floating-point numbers and use the %.2f
format specifier to print the results with two decimal places.
Mermaid Diagram
Here's a Mermaid diagram that summarizes the key concepts of performing arithmetic operations in C:
This diagram shows the main topics covered in this answer, including the basic arithmetic operators, the order of operations, and the considerations when working with floating-point arithmetic.