Print the Final Result
In this step, you'll expand on the previous example by creating a more complex arithmetic expression and printing detailed results to demonstrate the order of operations.
Open the file to modify the code:
cd ~/project
nano order_of_operations.c
Replace the previous code with the following:
#include <stdio.h>
int main() {
int a = 10;
int b = 5;
int c = 3;
int d = 2;
// Complex expression with multiple operations
int result_default = a + b * c - d;
int result_with_parentheses = a + (b * c - d);
printf("Original Expression Breakdown:\n");
printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);
printf("\nDefault Evaluation (a + b * c - d):\n");
printf("Step 1: b * c = %d\n", b * c);
printf("Step 2: a + (b * c) = %d\n", a + (b * c));
printf("Step 3: (a + b * c) - d = %d\n", result_default);
printf("\nParentheses Evaluation (a + (b * c - d)):\n");
printf("Step 1: b * c - d = %d\n", b * c - d);
printf("Step 2: a + (b * c - d) = %d\n", result_with_parentheses);
return 0;
}
Compile and run the program:
gcc order_of_operations.c -o order_of_operations
./order_of_operations
Example output:
Original Expression Breakdown:
a = 10, b = 5, c = 3, d = 2
Default Evaluation (a + b * c - d):
Step 1: b * c = 15
Step 2: a + (b * c) = 25
Step 3: (a + b * c) - d = 23
Parentheses Evaluation (a + (b * c - d)):
Step 1: b * c - d = 13
Step 2: a + (b * c - d) = 23
Key points:
- The code demonstrates how parentheses can change the order of operations
- We show step-by-step evaluation of the expressions
- Both expressions ultimately result in the same value (23)