pranjal1805

calculator.c

Jun 1st, 2021
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.95 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int add(int x, int y)
  4. {
  5.   return x+y;
  6. }
  7.  
  8. int subtract(int x, int y)
  9. {
  10.   return x-y;
  11. }
  12.  
  13. int multiply(int x, int y)
  14. {
  15.   int result;
  16.   /* Code goes here */
  17.   result=0;
  18.   int i=1;
  19.   while(i<=y)
  20.   {
  21.         result=add(result,x);
  22.         i=add(i,1);
  23.   }
  24.   return result;
  25. }
  26.  
  27. int divide(int x, int y)
  28. {
  29.   int result;
  30.   /* Code goes here */
  31.   result=0;
  32.   while(x>y)
  33.   {
  34.       x=subtract(x,y);
  35.       result=add(result,1);
  36.    
  37.   }
  38.   return result;
  39. }
  40.  
  41. int squareroot(int x)
  42. {
  43.   int result;
  44.   /* Code goes here */
  45.   int temp;
  46.   result=divide(x,2);
  47.   temp=0;
  48.   while(result!=temp)
  49.   {    
  50.       int c=0,d=0;
  51.       temp=result;
  52.         c=divide(x,temp);
  53.         d=add(c,temp);
  54.       result=divide(d,2);
  55.  
  56.      
  57.   }
  58.   return result;
  59. }
  60.  
  61. int exponentiate(int x, int y)
  62. {
  63.   int result;
  64.   /* Code goes here */
  65.   result=1;
  66.   while(y!=0)
  67.   {
  68.       result=multiply(result,x);
  69.       y=subtract(y,1);
  70.   }
  71.   return result;
  72. }
  73.  
  74.  
  75. int main()
  76. {
  77.   int x,y,op;
  78.  
  79.   printf("Operations:\n");
  80.   printf("1. Add \n");
  81.   printf("2. Subtract \n");
  82.   printf("3. Multiply\n");
  83.   printf("4. Divide\n");
  84.   printf("5. Square Root\n");
  85.   printf("6. Exponentiate\n");
  86.  
  87.   printf("Enter the operation (1,2,..):\n");
  88.   scanf("%d",&op);
  89.  
  90.   switch (op)
  91.   {
  92.     case 5:   printf("Enter positive integer\n");
  93.               scanf("%d",&x);
  94.               break;
  95.     default:  printf("Enter first positive integer\n");
  96.               scanf("%d",&x);
  97.               printf("Enter second positive integer\n");
  98.               scanf("%d",&y);
  99.   }
  100.   switch (op)
  101.   {
  102.     case 1: printf("Result = %d\n",add(x,y)); break;
  103.     case 2: printf("Result = %d\n",subtract(x,y)); break;
  104.     case 3: printf("Result = %d\n",multiply(x,y)); break;
  105.     case 4: printf("Result = %d\n",divide(x,y)); break;
  106.     case 5: printf("Result = %d\n",squareroot(x)); break;
  107.     case 6: printf("Result = %d\n",exponentiate(x,y)); break;
  108.   }
  109.   return 0;
  110. }
Advertisement
Add Comment
Please, Sign In to add comment