In the world of programming, performing fundamental arithmetic operations is a common task. In this article, we’ll walk through a simple C program that takes two floating-point numbers as input and computes their sum, difference, product, and quotient. Let’s dive into the code and explore each step.
Code Structure
The program starts by including the standard input-output header file, <stdio.h>
, and features the main function where the core logic resides. Variables are declared to store user input (num1
and num2
) and the results of arithmetic operations (sum
, diff
, prod
, and quot
).
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <stdio.h> main() { // Variable declaration float num1, num2; float sum = 0, diff = 0, prod = 0, quot = 0; // Code goes here return 0; } |
Variable Declaration
We declare floating-point variables to store the user input and the results of arithmetic operations.
1 2 3 4 |
float num1, num2; float sum = 0, diff = 0, prod = 0, quot = 0; |
User Input
The program prompts the user to enter two floating-point numbers using printf
and captures the input using scanf
.
1 2 3 4 5 6 7 |
printf("Enter the first number: "); scanf("%f", &num1); printf("Enter the second number: "); scanf("%f", &num2); |
Arithmetic Operations
Arithmetic operations are then performed on the entered numbers – addition, subtraction, multiplication, and division.
1 2 3 4 5 |
sum = num1 + num2; diff = num1 - num2; prod = num1 * num2; |
Division Check
To prevent division by zero, a conditional statement checks if the second number is zero before performing division.
1 2 3 4 5 6 7 |
if (num2 != 0) { quot = num1 / num2; } else { printf("Cannot divide by zero.\n"); } |
Output
Finally, the program prints the results of the arithmetic operations with a precision of two decimal places.
1 2 3 4 5 6 |
printf("The sum is %.2f\n", sum); printf("The difference is %.2f\n", diff); printf("The product is %.2f\n", prod); printf("The quotient is %.2f\n", quot); |
Conclusion
In conclusion, this C program provides a foundation for performing basic arithmetic operations. Understanding the code structure, variable declaration, user input, and the logic behind arithmetic operations is crucial for anyone starting their programming journey. Feel free to run the program with different inputs to observe the results firsthand. Happy coding!
YouTube