Sunday, February 15, 2015

C program to perform a user defined mathematical operation

The c program given below is able to perform a mathematical operation according to users interest. After running the program you will be asked to provide a number, that will be stored into a float type variable number1.

Soon, you will be asked to provide another number, that will be stored into a float type variable number2.

Later a message will be displayed to choose an operation you want to perform. For example: if you want to add those two numbers, then you have to provide the sign +. Similarly - for subtraction, * for multiplication and / for division.

Actually the sign you will provide, that will be stored as a character into the variable choice. Later, the if-else condition will one of those four operations depending on the value stored into the variable choice. But if there is anything else except +, -, * or / then a message will be displayed saying Invalid Operation!!!

//user defined mathematical operation
#include<stdio.h>
void main(){
    //declaring float type variables
    float number1, number2, sum, sub, mul, div;
    
    //declaring charater type variable
    char choice;
    
    //displaying message to input the 
    printf("Enter the first number: ");
    //storing data into variable number1
    scanf("%f",&number1);

    //displaying message to input the 
    printf("Enter the second number: ");
    //storing data into variable number2
    scanf("%f",&number2);

    //displaying message to choose an option
    printf("\nWhich operation do you want to perform: ");
    printf("\nEnter + to add the numbers: ");
    printf("\nEnter - to subtract the numbers: ");
    printf("\nEnter * to multiply the numbers: ");
    printf("\nEnter / to divide the numbers: ");
    
    //storing data into variable choice
    scanf(" %c",&choice);
    
    //if-else condition to choose an operation
    if(choice=='+'){
        sum=number1+number2;
        // .2 is used to show two digits after the point
        printf("\nThe sumation: %.2f",sum);
    } else if(choice=='-') {
        sub=number1-number2;
        printf("\nThe subtraction: %.2f",sub);
    } else if(choice=='*') {
        mul=number1*number2;
        printf("\nThe product: %.2f",mul);
    } else if(choice=='/') {
        div=number1/number2;
        printf("\nThe quetation: %.2f",div);
    } else {
        printf("\nInvalid operation!!!");
    }
}


No comments:

Post a Comment