Table of Contents
ToggleIn the last post, we explored a C program to multiply two numbers using the multiplication operator. Now let’s see how to divide numbers in C. Just as we used the ‘*’ symbol to multiply, we can use the ‘/’ operator to carry out division.
In this post, we will see a simple C program to divide two numbers entered by the user. We’ll use the same input and output functions as before, but focus on using the divide ‘/’ operator to see the quotient.
Algorithm to Divide two numbers in C
Below is the algorithm to divide two numbers in c, you can follow this algorithm.
Algorithm:
- Start: Begin the process.
- Input two numbers: Prompt the user to input the two numbers.
- Divide both the numbers
- Display answer: Show the calculated answer to the user.
- End: Conclude the process.
Program to divide two numbers in C
#include <stdio.h>
int main() {
double numerator, denominator, result;
printf("Enter numerator: ");
scanf("%lf", &numerator);
printf("Enter denominator: ");
scanf("%lf", &denominator);
// Check if the denominator is not zero to avoid division by zero error
if(denominator != 0.0) {
result = numerator / denominator;
printf("Result: %.2lf\n", result);
} else {
printf("Error: Division by zero!\n");
}
return 0;
}
The above C program begins by declaring variables for the numerator, denominator, and result, choosing the double
data type for precision with fractional numbers. The program prompts the user for the numerator and denominator through scanf
, ensuring an interactive experience. A critical part of the code is the conditional check to prevent division by zero, a common pitfall in division operations. If the denominator is not zero, it proceeds with the division and displays the result; otherwise, it alerts the user to the error.
Output
Time Complexity: The time complexity of this program is O(1).
Space Complexity: The space complexity of the program is also O(1).
If you liked this post you can checkout other C Programs.