Pre-increment against post-increment — Aptitude Question
Pre-increment against post-increment: What does this C program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 75 seconds
Question
What does this C program print?
#include <stdio.h>
int main(void) {
int i = 5;
int j = i++;
int k = ++i;
printf("%d %d %d", i, j, k);
return 0;
}Options
- 5 5 7
- 6 5 6
- 7 5 7
- 7 6 7
Show the answer and the worked solution
Correct answer: C. 7 5 7
Worked solution
- j = i++ gives j the current value 5, then i becomes 6.
- k = ++i raises i to 7 first, so k also receives 7.
- At the print statement i = 7, j = 5 and k = 7, so the program prints 7 5 7.
Answer: 7 5 7.
The idea
Both forms change the variable by one; they differ only in the value the expression yields. Splitting the statement into 'use, then bump' or 'bump, then use' settles every case.
Shortcut. i is bumped twice, so it ends at 7, which rules out "5 5 7" and "6 5 6"; j copied i before any bump (5) and k after both (7).
Common trap. "7 6 7" treats j = i++ like ++i, as if the increment happened before j was assigned; the postfix form hands over the old value 5.
All Programming Fundamentals questions · placement mock tests