-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
77 lines (67 loc) · 2.68 KB
/
main.c
File metadata and controls
77 lines (67 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <stdio.h>
#include <stdbool.h>
/*
* Requirements:
* - The calculator should be console-based.
* - It should perform basic arithmetic operations: addition, subtraction, multiplication, and division.
* - The user should be able to input two numbers and select the operation.
* - Implement error handling for invalid inputs and division by zero.
* - The program should continue to run until the user chooses to exit.
*/
int main (){
printf("---------------------\n");
printf("| Simple Calculator |\n");
printf("---------------------\n\n");
char execution;
int first_operand;
int second_operand;
char operator;
while(true){
printf("ENTER \"x\" to exit or ENTER \"y\" to continue\n");
scanf(" %c", &execution);
getchar(); // Consume the newline character left in the buffer
if(execution == 'x')
return 0;
else if (execution != 'y'){
printf("Invalid Input! Try again.\n");
continue;
}
else {
printf("Enter first operand:\n");
if (scanf("%d", &first_operand) != 1) { // Check if input is a valid number
printf("Invalid Input! Please enter a valid number.\n");
while (getchar() != '\n'); // Clear the input buffer
continue; // Start the loop again
}
printf("Enter second operand:\n");
if (scanf("%d", &second_operand) != 1) { // Check if input is a valid number
printf("Invalid Input! Please enter a valid number.\n");
while (getchar() != '\n'); // Clear the input buffer
continue; // Start the loop again
}
printf("Enter operator:\n");
scanf(" %c", &operator); // Note the space before %c to skip any whitespace
getchar(); // Consume the newline character left in the buffer
switch (operator) {
case '+':
printf("Result: %d\n", first_operand + second_operand);
break;
case '-':
printf("Result: %d\n", first_operand - second_operand);
break;
case '*':
printf("Result: %d\n", first_operand * second_operand);
break;
case '/':
if (second_operand == 0)
printf("Error: Division by zero!\n");
else
printf("Result: %d\n", first_operand / second_operand);
break;
default:
printf("Invalid operator!\n");
break;
}
}
}
}