Showing posts with label calculator. Show all posts
Showing posts with label calculator. Show all posts

Thursday, 26 May 2011

The Switch Statement

The switch statement is similar to the else-if construct but has more flexibility and a clearer format. Let's create a four function calculator using switch statement:


included files
void main()
{
 float num1=1.0,num2=1.0;
 char operator;
 while(!(num1==0.0 && num2==0.0))
 {
  printf("Type number, operator, number\n");
  scanf("%f %c %f",&num1,&operator,&num2);
  switch(operator)
   {
    case'+':
    printf(" = %f",num1 + num2);
    break;
    case'-':
    printf(" = %f",num1 - num2);
    break;
    case'*':
    printf(" = %f",num1 * num2);
    break;
    case'/':
    printf(" = %f"num1 / num2);
    break;
    default:
     printf("Unknown Operator!");
   } 
 printf("\n\n")
 }
getch();
}


In the above code, the statement 'case' is working as 'if', while 'default' is working as 'else' statement...


If you have any question, you can ask me freely!

Wednesday, 18 May 2011

Create a Calculator by using if-else statement

Just copy the code...


#include<stdio.h>
#include<conio.h>
void main (void)
{
 char ch;
 float num1,num2;
 clrscr();
 printf("What do you want to do?\n");
 printf("Addition, Subtraction, Multiplication or Division:");
 ch=getche();
 printf("\nEnter first number:");
 scanf("%f",&num1);
 printf("\nEnter second number:");
 scanf("%f",&num2);
 printf("\n\n");


if(ch=='A')   
 printf("%f %c %f = %.2f",num1,+,num2,num1+num2);

if(ch=='S')   
 printf("%f %c %f = %.2f",num1,-,num2,num1-num2);
if(ch=='M')   
 printf("%f %c %f = %.2f",num1,*,num2,num1*num2);
if(ch=='D')   
 printf("%f %c %f = %.2f",num1,/,num2,num1/num2);
getch();  



}


What is this?