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.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
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
- A 65
- C 2
- C 67
- 67 67
Show the answer and the worked solution
Correct answer: C. C 67
Worked solution
- c holds 65, so c + 2 is the integer 67.
- Under %c the value 67 is printed as the character it codes for, which is C.
- 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