AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumcincrement

~75s

Pre-increment against post-increment

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;
}
Show the answer and the worked solution

Correct answer: C.

7 5 7

Worked solution

  1. j = i++ gives j the current value 5, then i becomes 6.
  2. k = ++i raises i to 7 first, so k also receives 7.
  3. 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.

Pre-increment against post-increment — Aptitude Question

Pre-increment against post-increment: What does this C program print? Answer and worked solution on CodeKairo.

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

  1. 5 5 7
  2. 6 5 6
  3. 7 5 7
  4. 7 6 7
Show the answer and the worked solution

Correct answer: C. 7 5 7

Worked solution

  1. j = i++ gives j the current value 5, then i becomes 6.
  2. k = ++i raises i to 7 first, so k also receives 7.
  3. 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