You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.4 KiB

  1. // programmingMode
  2. #include <stdio.h>
  3. #include <math.h>
  4. #include "programmingMode.h"
  5. // Function to convert an integer to binary representation
  6. char* binaryRepresentation(int num);
  7. // get the NUmbers from the user
  8. int getIntegerInput(const char* prompt) {
  9. int num;
  10. printf("%s", prompt);
  11. scanf("%d", &num);
  12. return num;
  13. }
  14. // Display the diffrent operations and scan them
  15. char getOperatorInput() {
  16. char operator;
  17. printf("Enter operator (+, -, *, /): ");
  18. scanf(" %c", &operator);
  19. return operator;
  20. }
  21. // Calculation
  22. int performOperation(int num1, char operatorType, int num2) {
  23. switch (operatorType) {
  24. case '+':
  25. return num1 + num2;
  26. case '-':
  27. return num1 - num2;
  28. case '*':
  29. return num1 * num2;
  30. case '/':
  31. if (num2 != 0) {
  32. return num1 / num2;
  33. } else {
  34. printf("Error: Division by zero\n");
  35. return 0;
  36. }
  37. default:
  38. printf("Invalid operator\n");
  39. return 0;
  40. }
  41. }
  42. void programmingMode() {
  43. char choice;
  44. do {
  45. int num1 = getIntegerInput("Enter first integer: ");
  46. char operator = getOperatorInput();
  47. int num2 = getIntegerInput("Enter second integer: ");
  48. // Calculation
  49. int result = performOperation(num1, operator, num2);
  50. // Display the result in different bases based on user choice
  51. int base;
  52. printf("Choose base to print the result (2 for binary, 8 for octal, 16 for hexadecimal): ");
  53. scanf("%d", &base);
  54. switch (base) {
  55. case 2:
  56. printf("Result (Binary): %s\n", binaryRepresentation(result));
  57. break;
  58. case 8:
  59. printf("Result (Octal): %o\n", result);
  60. break;
  61. case 16:
  62. printf("Result (Hexadecimal): %x\n", result);
  63. break;
  64. default:
  65. printf("Invalid base choice\n");
  66. break;
  67. }
  68. // Ask user if they want to continue
  69. printf("Do you want to continue? (y/n): ");
  70. scanf(" %c", &choice);
  71. } while (choice == 'y' || choice == 'Y');
  72. }
  73. // Function to convert an integer to binary representation
  74. char* binaryRepresentation(int num) {
  75. static char binary[32];
  76. for (int i = 31; i >= 0; i--) {
  77. binary[i] = (num & 1) + '0';
  78. num >>= 1;
  79. }
  80. binary[32] = '\0';
  81. return binary;
  82. }