Sunday 17 February 2013

if else ladder-Calculator

// Simulate calculator using if else ladder
The If-Else  Ladder is used if we have a multiple conditions to check.The same problem can be solved using switch case also.




In this ladder first condition is checked using only if statement.If all conditions fail then last else will get executes

  1. int main()
  2. {
  3. int a,b,c;
  4. float r1;
  5. int flag=0;
  6. char ch;
  7. clrscr();
  8. printf("Enter x to stop");
  9. do
  10.     {
  11. printf("enter the two numbers");
  12. scanf("%d%d",&a,&b);
  13. printf("\n enter any +,-,*,/");
  14. scanf(" %c",&ch);
  15. if(ch=='+')
  16. c=a+b;
  17. else if (ch=='-')
  18. c=a-b;
  19. else if(ch=='*')
  20. c=a*b;
  21. else
  22.     {
  23. r1=(float)a/b;
  24. flag=1;

  25.     }
  26.     if(flag==1)
  27. printf("result is %f",r1);
  28.     else
  29. printf("result is %d",c);
  30.     }    while(ch!='x');
  31.     getch();
  32. }





1 comment: