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

Fri, 16 Apr, 2021

WORD IS THE KEY

(TCS Ninja – Aug 2019 Slot 1)

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 cases

Case 1

  • Input – defer
  • Expected Output – defer is a keyword

Case 2

  • Input – While
  • Expected Output – while is not a keyword

Answer in C programming

#include<stdio.h>
#include<string.h>

int main(){
    
    char str[16][10] = {"break", "case", "continue", "default", "defer", "else","for", 
    "func", "goto", "if", "map", "range", "return", "struct", "type", "var"};
    
    char input[20];
    
    int flag = 0;
    scanf("%s",input);
    
    for(int i = 0; i<16;i++){
        if(strcmp(input,str[i]) == 0){
            flag = 1;
            break;
        }
    }
    
    if(flag==1){
        printf("%s is a keyword",input);
    }
    else{
        printf("%s is not a keyword",input);
    }
    return 0;
}

Answer in C++

#include<iostream>
#include<string.h>

using namespace std;

int main(){
    
    char str[16][10] = {"break", "case", "continue", "default", "defer", "else","for", 
    "func", "goto", "if", "map", "range", "return", "struct", "type", "var"};
    
    char input[20];
    
    int flag = 0;
    cin >> input;
    
    for(int i = 0; i<16;i++){
        if(strcmp(input,str[i]) == 0){
            flag = 1;
            break;
        }
    }
    
    if(flag==1){
        cout << input << " is a keyword";
    }
    else{
        cout << input << " is not a keyword";
    }
    return 0;
}

Answer in Java

import java.util.*;
public class Main
{
	public static void main(String[] args) {
	    String[] s=new String[]{"break","case","continue","default","defer","else","for","func","goto","if","map","range","return","struct","type","var"};
		List<String> l=Arrays.asList(s);
		Scanner sin=new Scanner(System.in);
		String s1=sin.nextLine();
		if(l.contains(s1))
		  System.out.println(s1+" is a keyword");
		  else
		  System.out.println(s1+" is not a keyword");
	}
}

Answer in Python

keyword = {"break", "case", "continue", "default", "defer", "else", "for", 
"func", "goto", "if", "map", "range", "return", "struct", "type", "var"}

input_var = input()
if input_var in keyword:
    print(input_var+ " is a keyword")
else:
    print(input_var+ " is a not keyword")

 

0 comments
Leave a comment