Write Sample Arithmetic Operations (Add, Sub, Mul, Div)
We'll dive deeper into arithmetic operations in C by creating a program that demonstrates various mathematical calculations. We'll write a comprehensive example that shows addition, subtraction, multiplication, and division with different types of numeric values.
Navigate to the project directory and create a new file:
cd ~/project
touch arithmetic_operations.c
Open the file in the WebIDE and add the following code:
#include <stdio.h>
int main() {
// Integer arithmetic operations
int a = 20, b = 5;
// Addition
int sum = a + b;
printf("Addition: %d + %d = %d\n", a, b, sum);
// Subtraction
int difference = a - b;
printf("Subtraction: %d - %d = %d\n", a, b, difference);
// Multiplication
int product = a * b;
printf("Multiplication: %d * %d = %d\n", a, b, product);
// Division
int quotient = a / b;
printf("Division: %d / %d = %d\n", a, b, quotient);
// Modulus (remainder)
int remainder = a % b;
printf("Modulus: %d %% %d = %d\n", a, b, remainder);
// Floating-point arithmetic
float x = 10.5, y = 3.2;
float float_sum = x + y;
float float_difference = x - y;
float float_product = x * y;
float float_quotient = x / y;
printf("\nFloating-point Arithmetic:\n");
printf("Addition: %.2f + %.2f = %.2f\n", x, y, float_sum);
printf("Subtraction: %.2f - %.2f = %.2f\n", x, y, float_difference);
printf("Multiplication: %.2f * %.2f = %.2f\n", x, y, float_product);
printf("Division: %.2f / %.2f = %.2f\n", x, y, float_quotient);
return 0;
}
When learning programming, it's essential to understand how different data types impact mathematical operations. This example demonstrates the nuanced behavior of arithmetic operations in C, showcasing the differences between integer and floating-point calculations.
Compile and run the program:
gcc arithmetic_operations.c -o arithmetic_operations
./arithmetic_operations
Example output:
Addition: 20 + 5 = 25
Subtraction: 20 - 5 = 15
Multiplication: 20 * 5 = 100
Division: 20 / 5 = 4
Modulus: 20 % 5 = 0
Floating-point Arithmetic:
Addition: 10.50 + 3.20 = 13.70
Subtraction: 10.50 - 3.20 = 7.30
Multiplication: 10.50 * 3.20 = 33.60
Division: 10.50 / 3.20 = 3.28
As you progress in your programming journey, understanding these fundamental arithmetic operations will help you build more complex algorithms and solve real-world computational problems. Each operator has its unique characteristics and use cases, which you'll discover through practice and exploration.
Key points to note:
- Integer division truncates the decimal part
- The modulus operator (
%
) works only with integers
- Floating-point arithmetic allows for decimal calculations
- Use
%.2f
format specifier to display floating-point numbers with two decimal places
By mastering these basic arithmetic operations, you're laying a strong foundation for your programming skills and preparing yourself for more advanced computational techniques.