C Program for Basic Calculator Using switch स्विच का उपयोग करके Basic Calculator बनाना

A basic calculator performs arithmetic operations such as addition, subtraction, multiplication, and division. In C language, we can use the switch statement to perform these operations based on the user's choice.

एक Basic Calculator Addition, Subtraction, Multiplication और Division जैसी arithmetic operations करता है। C भाषा में switch statement का उपयोग करके user की choice के आधार पर इन operations को perform किया जा सकता है।

C Program

#include <stdio.h>
int main(void)
{
float a, b, ans;
int choice;
while (1)
{
printf("\nBasic Calculator\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
if (choice == 5)
break;
if (choice < 1 || choice > 5)
{
printf("Wrong input\n");
continue;
}
printf("Enter two numbers: ");
scanf("%f %f", &a, &b);
switch (choice)
{
case 1:
ans = a + b;
printf("Answer = %f\n", ans);
break;
case 2:
ans = a - b;
printf("Answer = %f\n", ans);
break;
case 3:
ans = a * b;
printf("Answer = %f\n", ans);
break;
case 4:
if (b != 0)
{
ans = a / b;
printf("Answer = %f\n", ans);
}
else
{
printf("Division by zero is not allowed\n");
}
break;
}
}
return 0;
}

Output

Basic Calculator
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 1
Enter two numbers: 10 5
Answer = 15.000000

Explanation

  • while(1) repeats the calculator menu until the user chooses Exit.

  • switch(choice) selects the arithmetic operation.

  • case 1 performs Addition.

  • case 2 performs Subtraction.

  • case 3 performs Multiplication.

  • case 4 performs Division, after checking that the second number is not zero.

  • case 5 exits the program using break.

  • default-like validation checks invalid choices.

switch(choice) user की choice के अनुसार operation select करता है। Division करने से पहले यह जाँच की जाती है कि दूसरा number zero न हो। User द्वारा 5 चुनने पर calculator बंद हो जाता है।

Modern C Compatibility Note

This program uses standard C and works with modern compilers such as GCC, Clang, and Visual Studio C. It does not require conio.h, clrscr(), getch(), or exit().

This program demonstrates how to create a basic calculator using the switch statement and a loop in C.

यह program C भाषा में switch statement और loop का उपयोग करके Basic Calculator बनाना सिखाता है।

Comments

Popular posts from this blog

C Language Topics in Hindi and English

Complete C Programming Syllabus | Advanced C Roadmap for Students

Top High-Paying Tech Skills to Learn in 2025