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

~60s

A character used in arithmetic

Assume the ASCII character set, in which 'A' has the value 65. What does this C program print?

#include <stdio.h>

int main(void) {
    char c = 'A';
    printf("%c %d", c + 2, c + 2);
    return 0;
}
Show the answer and the worked solution

Correct answer: C.

C 67

Worked solution

  1. c holds 65, so c + 2 is the integer 67.
  2. Under %c the value 67 is printed as the character it codes for, which is C.
  3. Under %d the same value is printed as the number 67, so the output is C 67.

Answer: C 67.

The idea

In C a character is just its code, and the conversion specifier decides how that code is displayed. Nothing about the value changes between the two printings.

Shortcut. One value, two views: 'A' + 2 = 67, which %c shows as the letter two after A, C, and %d as the number 67.

Common trap. "67 67" assumes that adding an int turns the char into a number %c cannot show as a letter; %c prints whatever code it is given as a character.

A character used in arithmetic — Aptitude Question

A character used in arithmetic: Assume the ASCII character set, in which 'A' has the value 65. Answer and worked solution on CodeKairo.

Question

Assume the ASCII character set, in which 'A' has the value 65. What does this C program print?

#include <stdio.h>

int main(void) {
    char c = 'A';
    printf("%c %d", c + 2, c + 2);
    return 0;
}

Options

  1. A 65
  2. C 2
  3. C 67
  4. 67 67
Show the answer and the worked solution

Correct answer: C. C 67

Worked solution

  1. c holds 65, so c + 2 is the integer 67.
  2. Under %c the value 67 is printed as the character it codes for, which is C.
  3. Under %d the same value is printed as the number 67, so the output is C 67.

Answer: C 67.

The idea

In C a character is just its code, and the conversion specifier decides how that code is displayed. Nothing about the value changes between the two printings.

Shortcut. One value, two views: 'A' + 2 = 67, which %c shows as the letter two after A, C, and %d as the number 67.

Common trap. "67 67" assumes that adding an int turns the char into a number %c cannot show as a letter; %c prints whatever code it is given as a character.

All Programming Fundamentals questions · placement mock tests