Write a C language program of a calculator.

May 13, 2020

Question: Write a C language program of a calculator.

Algorithm:

Program:

#include<stdio.h>
#include<stdlib.h>

//function declarations
void display(float n1, float n2, char choice, float result);
void add(float n1, float n2);
void sub(float n1, float n2);
void mul(float n1, float n2);
void div(float n1, float n2);

//function for displaying the result
void display(float n1, float n2, char ch, float result)
{
  printf("%.2f %c %.2f = %.2f\n", n1, choice, n2, result);
}

//function for addition of two numbers
void add(float n1, float n2)
{
  float result = n1 + n2;
  display(n1, n2, '+', result);
}

//function for subtraction of two numbers
void sub(float n1, float n2)
{
  float result = n1 - n2;
  display(n1, n2, '-', result);
}

//function for multiplication of two numbers
void mul(float n1, float n2)
{
  float result = n1 * n2;
  display(n1, n2, '*', result);
}

//function for division of two numbers
void div(float n1, float n2)
{
  float result = n1 / n2;
  display(n1, n2, '/', result);
}

//main function
int main()
{
  float n1, n2;
  int choice=1;

  while(choice!=0)
  {
    printf("Enter First numbers: ");
    scanf("%f", &n1);
    
    printf("Enter Second numbers: ");
    scanf("%f", &n2);

    printf("\n*****************");
    printf("\n1.Addition");
    printf("\n2.Subtraction");
    printf("\n3.Multiplication");
    printf("\n4.Division");
    printf("\nEnter 0 to exit");
    printf("\nEnter your choice: ");
    scanf("%d", &choice);

    switch (choice) {
      case 0:
        display();
      case 1:
        add(n1,n2);
        break;
      case 2:
        subtract(n1,n2);
        break;
      case 3:
        multiply(n1,n2);
        break;
      case 4:
        divide(n1,n2);
        break;
      case 7:
        printf("Thank You.");
        exit(0);
      default:
        printf("Invalid input.");
        printf("Please enter correct input.");
    }

    printf("\n**********************************\n");
  }
  return 0;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

tech.techiya