Handle Division by Zero Gracefully
In this step, you will learn how to handle division by zero, which is a common error in arithmetic operations that can cause program crashes.
Open the existing arithmetic_operations.c
file:
cd ~/project
nano arithmetic_operations.c
Update the code to handle division by zero:
#include <stdio.h>
int main() {
// Declare variables to store input numbers and results
float num1, num2, multiply_result, divide_result;
// Prompt user to enter first number
printf("Enter the first number: ");
scanf("%f", &num1);
// Prompt user to enter second number
printf("Enter the second number: ");
scanf("%f", &num2);
// Perform multiplication
multiply_result = num1 * num2;
printf("Multiplication: %.2f * %.2f = %.2f\n", num1, num2, multiply_result);
// Check for division by zero before performing division
if (num2 != 0) {
divide_result = num1 / num2;
printf("Division: %.2f / %.2f = %.2f\n", num1, num2, divide_result);
} else {
printf("Error: Division by zero is not allowed!\n");
}
return 0;
}
Compile the updated program:
gcc arithmetic_operations.c -o arithmetic_operations
Run the program and test different scenarios:
Test with a non-zero divisor:
./arithmetic_operations
Example output (non-zero divisor):
Enter the first number: 10.5
Enter the second number: 3.2
Multiplication: 10.50 * 3.20 = 33.60
Division: 10.50 / 3.20 = 3.28
Test with zero as divisor:
./arithmetic_operations
Example output (zero divisor):
Enter the first number: 10.5
Enter the second number: 0
Multiplication: 10.50 * 0.00 = 0.00
Error: Division by zero is not allowed!
Key points:
- Use an
if
statement to check if the divisor is zero
- Provide a user-friendly error message
- Prevent program crash by handling the division by zero case