Write a C Program to Make a Simple Calculator.

Prince Patel
By -
0

Write a C Program to Make a Simple Calculator.


Programming is all about solving problems and creating useful applications. One of the fundamental applications that budding programmers often tackle is building a calculator. Calculators are simple yet essential tools that can be created using C, a versatile and widely-used programming language. In this article, we'll walk through the process of creating a simple calculator in C.

Understanding the Problem

Before we start coding, it's essential to understand the problem we're trying to solve. Our goal is to create a basic calculator that can perform four primary arithmetic operations: addition, subtraction, multiplication, and division. Users should be able to enter two numbers and choose the operation they want to perform. The program should then display the result.

Here's a  C Program to Make a Simple Calculator:

#include<stdio.h> #include<conio.h> void main() { // Declare variables to store user input and the result double num1, num2, result; char operator; // Prompt the user to enter the first number printf("Enter the first number: "); scanf("%lf", &num1); // Prompt the user to enter the operator (+, -, *, /) printf("Enter an operator (+, -, *, /): "); scanf(" %c", &operator); // Note the space before %c to consume the newline character // Prompt the user to enter the second number printf("Enter the second number: "); scanf("%lf", &num2); // Perform the selected operation and store the result switch (operator) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': if (num2 != 0) { result = num1 / num2; } else { printf("Error: Division by zero is not allowed.\n"); return 1; // Exit with an error code } break; default: printf("Error: Invalid operator.\n"); return 1; // Exit with an error code } // Display the result printf("Result: %lf\n", result); }

Output:









Tags:

Post a Comment

0Comments

Post a Comment (0)