Operators & Expressions
Operators perform mathematical and logical changes on data variables. In C, understanding division limits and prefix vs postfix increments is essential.
1 Arithmetic, Relational, and Logical Operators
C operators include:
- Arithmetic: `+`, `-`, `*`, `/`, `%` (modulus).
- Relational: `==`, `!=`, `>`, `<`, `>=`, `<=`.
- Logical: `&&` (AND), `||` (OR), `!` (NOT) with short-circuit rules.
⚠️ Integer Division Trap: Just like Java, dividing two integers in C yields a truncated integer quotient. For instance, `7 / 2` evaluates to `3`. To retrieve the decimal value, use type-casting: `(double)7 / 2` yields `3.5`.
2 Increment Placement Tracing
The increment operator (`++`) increases a variable's value by 1. Placement dictates execution order:
- Postfix (`x++`): Yields the original value of `x` in the expression, then increments `x`.
- Prefix (`++x`): Increments `x` first, then evaluates the expression.
C — Arithmetic and Increments
▶ Run Code
#include <stdio.h>
int main() {
int val = 5;
// Division types
printf("Integer division (5 / 2): %d\n", 5 / 2);
printf("Cast division ((double)5 / 2): %.1lf\n", (double)5 / 2);
// Prefix vs Postfix execution
int postfix = val++; // postfix gets 5, val becomes 6
printf("Postfix assignment: postfix=%d, val=%d\n", postfix, val);
val = 5; // Reset
int prefix = ++val; // val becomes 6, prefix gets 6
printf("Prefix assignment: prefix=%d, val=%d\n", prefix, val);
return 0;
}
3 Code Challenge
Challenge: Write a program that defines three test scores as integers (e.g. 85, 90, 78). Compute their average. Use double casting to ensure the final average retains decimal accuracy, and print it to the screen.