📖 Scenario: Imagine you are calculating the total cost of items in a shopping cart. You want to make sure the calculations happen in the right order so you get the correct total.
🎯 Goal: You will write a small C program that uses operator precedence to calculate a total price correctly.
📋 What You'll Learn
Create variables with exact names and values as instructed
Use operator precedence correctly in an expression
Print the final calculated total
💡 Why This Matters
🌍 Real World
Calculating prices, discounts, and totals correctly is important in shopping apps and billing systems.
💼 Career
Understanding operator precedence helps avoid bugs in financial calculations and data processing in software development.
Progress0 / 4 steps
1
Create initial variables
Create three int variables called price, quantity, and discount with values 50, 3, and 20 respectively.
C
Hint
Use the syntax int variable_name = value; to create each variable.
2
Add a variable for total cost calculation
Create an int variable called total and set it to zero.
C
Hint
Remember to use int total = 0; to create the variable.
3
Calculate total using operator precedence
Calculate the total price after discount using the expression price * quantity - discount and assign it to the variable total.
C
Hint
Use the expression price * quantity - discount exactly to assign to total.
4
Print the total
Use printf to print the text Total: followed by the value of total and a newline.
C
Hint
Use printf("Total: %d\n", total); inside main to print the result.
Practice
(1/5)
1. Which operator has the highest precedence in the expression 3 + 4 * 5?
easy
A. Division (/)
B. Addition (+)
C. Subtraction (-)
D. Multiplication (*)
Solution
Step 1: Recall operator precedence rules
Multiplication and division have higher precedence than addition and subtraction in C.
Step 2: Identify operators in the expression
The expression has addition (+) and multiplication (*). Multiplication runs first.
Final Answer:
Multiplication (*) -> Option D
Quick Check:
Multiplication > Addition [OK]
Hint: Multiplication and division run before addition and subtraction [OK]
Common Mistakes:
Thinking addition runs before multiplication
Ignoring operator precedence
Assuming left to right always applies
2. Which of the following expressions is correctly written to add 2 and 3, then multiply the result by 4?
easy
A. (2 + 3) * 4
B. 2 + (3 * 4)
C. 2 + 3 * 4
D. 2 * 3 + 4
Solution
Step 1: Understand the desired calculation
Add 2 and 3 first, then multiply by 4.
Step 2: Check parentheses usage
Only (2 + 3) * 4 uses parentheses to add 2 and 3 first, then multiply by 4.
Final Answer:
(2 + 3) * 4 -> Option A
Quick Check:
Parentheses change order to add first [OK]
Hint: Use parentheses to force addition before multiplication [OK]
Common Mistakes:
Ignoring parentheses and trusting default precedence