C Program to Divide Two Numbers
This program demonstrates how to divide two numbers in C, a fundamental operation for beginners learning arithmetic and input-output functions.
In this tutorial, you’ll learn how to write a C program to take two numbers as input, divide the first by the second, and display the result.
Concept Overview
C programming allows arithmetic operations using basic operators. The '/' operator is used to divide one number by another. Care must be taken to avoid division by zero.
Program
#include <stdio.h>
int main() {
int numerator, denominator;
float quotient;
// Ask the user to enter two numbers
printf("Enter numerator: ");
scanf("%d", &numerator);
printf("Enter denominator: ");
scanf("%d", &denominator);
// Check for division by zero
if (denominator == 0) {
printf("Error: Division by zero is not allowed.\n");
} else {
// Perform division
quotient = (float)numerator / denominator;
// Display the result
printf("Quotient = %.2f\n", quotient);
}
return 0;
}
Output
Enter numerator: 20 Enter denominator: 5 Quotient = 4
Explanation
- `#include
` – Includes the standard input-output library for using `printf()` and `scanf()` functions. - `int numerator, denominator; float quotient;` – Declares two integers and a float to store the quotient.
- `scanf()` – Takes user input for numerator and denominator.
- Checks if denominator is not zero to avoid division by zero error.
- `quotient = (float)numerator / denominator;` – Performs the division operation and stores it as a float.
- `printf()` – Displays the result on the screen.