easy
0 views
Word is Key – TCS NQT Question 3
Determine if a given word is a reserved keyword in a specific programming language
Understand the Problem
Problem Statement
One programming language has the following keywords that cannot be used as identifiers:
- break, case, continue, default, defer, else, for, func, goto, if, map, range, return, struct, type, var
Write a program to find if the given word is a keyword or not.
Constraints
- Input word length: 1 to 20 characters
- Input word can contain letters (a-z, A-Z) only
- Keywords are case-sensitive (must match exactly)
- Word will not contain spaces or special characters
- Keywords list is fixed and predefined
Examples
Example 1
Input
deferOutput
defer is a keywordExplanation
The input word 'defer' matches exactly with one of the predefined keywords in the list, so the output correctly identifies it as a keyword.
Example 2
Input
WhileOutput
while is not a keywordExplanation
Although 'while' is a common programming keyword, it is not in the predefined list of 16 keywords. Note that the comparison is case-sensitive, so 'While' (with capital W) is different from 'while'.
Solution
#include <stdio.h>
#include <string.h>
int main() {
// Array of predefined keywords
const char* keywords[] = {
"break", "case", "continue", "default", "defer",
"else", "for", "func", "goto", "if",
"map", "range", "return", "struct", "type", "var"
};
// Number of keywords
const int numKeywords = 16;
// Input word
char inputWord[21]; // Max 20 chars + null terminator
// Read input
scanf("%20s", inputWord);
// Flag to track if keyword found
int isKeyword = 0;
// Check against each keyword
for (int i = 0; i < numKeywords; i++) {
if (strcmp(inputWord, keywords[i]) == 0) {
isKeyword = 1;
break;
}
}
// Output result
if (isKeyword) {
printf("%s is a keyword\n", inputWord);
} else {
printf("%s is not a keyword\n", inputWord);
}
return 0;
}Time:O(k) where k is the number of keywords (16). Since the keyword list is fixed, this is effectively O(1).
Space:O(k) for storing the keyword array, which is O(1) since k is fixed at 16.
Approach:
The C solution:
- Defines an array of 16 keyword strings using const char* for efficiency
- Uses a fixed-size character array (21 bytes) to store input with bounds checking
- Reads input using scanf with width specifier to prevent buffer overflow
- Iterates through the keyword array using strcmp() for exact string comparison
- Uses a flag variable to track if a match is found
- Outputs the result in the required format using printf
Key features: memory-safe input handling, efficient string comparison, clear output formatting.
Visual Explanation
Loading diagram...