Problem Statement
Valid Keyword
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.
Test Case:
Case 1
Input – defer
Expected Output – defer is a keyword
Case 2
Input – while
Expected Output – while is not a keyword
Programming Language - C
#include <stdio.h>
#include <string.h>
int main() {
char keywords[16][10]={"break", "case", "continue", "default", "defer", "else","for",
"func", "goto", "if", "map", "range", "return", "struct", "type", "var"} ;
char input[]="";
scanf("%s",input);
int flag=0,i;
for(i = 0; i < 32; i++) {
if(strcmp(str,keywords[i])==0) {
flag=1;
}
}
if(flag==1)
printf("%s is a keyword",str);
else
printf("%s is not a keyword",str);
}
Programming Language - Java
package codingExample;
import java.util.Scanner;
public class IsKeyword {
public static void main(String[] args) {
String str[] = { "break", "case", "continue", "default", "defer", "else",
"for", "func", "goto", "if", "map", "range", "return", "struct", "type", "var" };
boolean isKeyword = false;
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
for (int i = 0; i < 16; i++) {
if (str[i].equals(input)) {
isKeyword = true;
break;
}
}
if (isKeyword) {
System.out.println(input + " is a keyword");
} else {
System.out.println(input + " is not a keyword");
}
}
}
0 Comments