TCS NQT coding questions for 2021 with answers(C/C++/Java)

Spread the love

TCS NQT coding questions for 2021 with answers

TCS NQT coding questions 2021:-

QUESTIONS 1:

A washing machine works on the principle of a Fuzzy System, the weight of clothes put inside it for washing is uncertain But based on weight measured by sensors, it decides time and water level which can be changed by menus given on the machine control area.  

For low-level water, the time estimate is 25 minutes, where approximately weight is between 2000 grams or any nonzero positive number below that.

In medium-level water, the time estimate is 35 minutes, where approximately weight is between 2001 grams and 4000 grams.

For high-level water, the time estimate is 45 minutes, where approximately weight is above 4000 grams.

Assume the capacity of the machine is a maximum of 7000 grams

Where approximately weight is zero, time estimate is 0 minutes.

Write a function that takes a numeric weight in the range [0,7000] as input and produces estimated time as output is: “OVERLOADED”, and for all other inputs, the output statement is

“INVALID INPUT”.

Input should be in the form of integer value –

Output must have the following format –

Time Estimated: Minutes

Example:

  • Input value:   2000
  • Output value:  Time Estimated :- 25 minutes

ANSWER:-

#include<stdio.h>
void calculateTime(int n)
{
    if(n==0)
        printf("Time Estimated : 0 Minutes");
    else if(n>0 && n<=2000) 
        printf("Time Estimated : 25 Minutes"); 
    else if(n>2000 && n<=4000) 
        printf("Time Estimated : 35 Minutes"); 
    else if(n>4000 && n<=7000)
        printf("Time Estimated : 45 Minutes");
    else
        printf("INVALID INPUT");
}
int main()
{
    int machineWeight;
    scanf("%d",&machineWeight);
    calculateTime(machineWeight);
    return 0;
}
n = int(input())
if n==0:
    print("Time Estimated :- 0 Minutes")
elif n in range(1,2001):
    print("Time Estimated :- 25 Minutes")
elif n in range(2001,4001):
    print("Time Estimated :- 35 Minutes")
elif n in range(4001,7001):
    print("Time Estimated :- 45 Minutes")
else:
    print("INVALID INPUT")

 

 

TCS NQT coding questions for 2021

QUESTIONS 2:

The Caesar cipher is a type of substitution cipher in which each alphabet in the plaintext or messages is shifted by a number of places down the alphabet.
For example, with a shift of 1, P would be replaced by Q, Q would become R, and so on.
To pass an encrypted message from one person to another, it is first necessary that both parties have the ‘Key’ for the cipher so that the sender may encrypt and the receiver may decrypt it.

Key is the number of offsets to shift the cipher alphabet. Key can have basic shifts from 1 to 25 positions as there are 26 total alphabets.

As we are designing custom Caesar Cipher, in addition to alphabets, we are considering numeric digits from 0 to 9. Digits can also be shifted by key places.
For Example, if a given plain text contains any digit with values 5 and key =2, then 5 will be replaced by 7, “-”(minus sign) will remain as it is. Key-value less than 0 should result in “INVALID INPUT”

Example 1:
Enter your Plain Text: All the best
Enter the Key: 1

ANSWER:-

#include <stdio.h>
int main()
{
    char str[100];
    int key, i=0, left;
    printf("Enter your plain text : ");
    scanf("%[^n]s",str);
    printf("Enter the key : ");
    scanf("%d",&key);
    if(key==0)
    {
        printf("INVALID INPUT");
    }
    else
    {
        while(str[i]!='')
        {
            //printf("%dn", str[i]);
            if(str[i]>=48 && str[i]<=57)
            {
                if(str[i]+key<=57)
                {
                    str[i] = str[i] + key;
                }
                else
                {
                    left = (str[i] + key) - 57;
                    str[i] = 47 + left;
                }   
            }
            else if(str[i]>=65 && str[i]<=90)
            {
                if(str[i]+key<=90)
                {
                    str[i] = str[i] + key;
                }
                else
                {
                    left = (str[i] + key) - 90;
                    str[i] = 64 + left;
                }  
            }
            else if(str[i]>=97 && str[i]<=122)
            {
                if(str[i]+key<=122)
                {
                    str[i] = str[i] + key;
                }
                else
                {
                    left = (str[i] + key) - 122;
                    str[i] = 96 + left;
                } 
            }
            i++;
        }
        printf("The encrypted text is : %s",str);
   }
   return 0;
}
def ceaser(text,key):
    result = ""
   # transverse the plain text
    for i in range(len(text)):
        char = text[i]
      # Encrypt uppercase characters in plain text
        if (char.isupper()):
            result += chr((ord(char) + key-65) % 26 + 65)
      # Encrypt lowercase characters in plain text
        elif (char.islower()):
            result += chr((ord(char) + key - 97) % 26 + 97)
        elif(char.isdigit()):
            result += str(int(char) + key)
        elif(char == '-'):
            result += '-'
        elif (char.isspace()):
            result += " "
    return result
#check the above function
text = input("Enter your plain text:")
key = int(input("Enter the key:"))
print(ceaser(text,key))

 

QUESTIONS 3:

We want to estimate the cost of painting a property. Interior wall painting cost is Rs.18 per sq. ft. and exterior wall painting cost is Rs.12 per sq. ft.

Take input as
1. Number of Interior walls
2. Number of Exterior walls
3. Surface Area of each Interior 4. Wall in units of square feet
Surface Area of each Exterior Wall in units of square feet

If a user enters zero as the number of walls then skip Surface area values as the User may don’t want to paint that wall.

Calculate and display the total cost of painting the property
Example 1:

6
3
12.3
15.2
12.3
15.2
12.3
15.2
10.10
10.10
10.00
Total estimated cost: 1847.4 INR

ANSWER:-

#include<stdio.h>
int main()
{
    int ni,ne,i=0;
    float int_p=18,ext_p=12,cost=0,temp;
    scanf("%d %d",&ni,&ne);
    if(ni<0 || ne<0 )
    {
        printf("INVALID INPUT");
    }
    else if(ni==0 && ne==0)
    {
        printf("Total estimated Cost : 0.0");
    }
    else
    {
        for(i=0;i<ni;i++)
        {
            scanf("%f",&temp);
            cost+= int_p*temp;
        }
        for(i=0;i<ne;i++)
        {
            scanf("%f",&temp);
            cost+= ext_p*temp;
        }
        printf("Total estimated Cost : %.1f",cost);
    }
    return 0;
}
#include<iostream>
using namespace std;
int main()
{
    int ni,ne,i=0;
    float int_p=18,ext_p=12,cost=0,temp;
    scanf("%d %d",&ni,&ne);
    if(ni<0 || ne<0 )
    {
        cout<<"INVALID INPUT";
    }
    else if(ni==0 && ne==0)
    {
        cout<<"Total estimated Cost : 0.0";
    }
    else
    {
        for(i=0;i<ni;i++)
        {
            cin>>temp;
            cost+= int_p*temp;
        }
        for(i=0;i<ne;i++)
        {
            cin>>temp;
            cost+= ext_p*temp;
        }
        cout<<"Total estimated Cost : "<<cost;      
    }
    return 0;
}

import java.util.Scanner;
class Main {
public static void main(String[] args) {
int ni, ne, i = 0;
float intP = 18, extP = 12, cost = 0, temp;
Scanner sc = new Scanner(System.in);
ni = sc.nextInt();
ne = sc.nextInt();
if(ni < 0 || ne < 0) {
System.out.print(“INVALID INPUT”);
} else if(ni == 0 && ne == 0) {
System.out.print(“Total estimated Cost : 0.0”);
} else {
for(i = 0; i < ni; i++) {
temp = sc.nextFloat();
cost += intP * temp;
}
for(i = 0; i < ne; i++) {
temp = sc.nextFloat();
cost += extP * temp;
}
System.out.printf(“Total estimated Cost : %.1f”, cost);
}
}
}

interior_walls = int(input())
exterior_walls = int(input())
if interior_walls:
int_walls = []
for i in range(interior_walls):
int_walls.append(float(input()))

if exterior_walls:
ext_walls = []
for i in range(exterior_walls):
ext_walls.append(float(input()))
if exterior_walls < 0 or interior_walls < 0:
print(“Invalid Input”)
exit()
if exterior_walls and interior_walls:
print(“Total estimated Cost : “,(sum(int_walls)*18+sum(ext_walls)*12),”INR”)
else:
if exterior_walls:
print(“Total estimated Cost : “,sum(ext_walls)*12,”INR”)
elif interior_walls:
print(“Total estimated Cost : “,sum(int_walls)*18,”INR”)
else:
print(“Total estimated Cost : 0.0 INR”)

 

TCS NQT coding questions for 2021

QUESTIONS 4:

A City Bus is a Ring Route Bus that runs in a circular fashion. That is, Bus once starts at the Source Bus Stop, halts at each Bus Stop in its Route and at the end, it reaches the Source Bus Stop again.

If there are n  number of Stops and if the bus starts at Bus Stop 1, then after nth Bus Stop, the next stop in the Route will be Bus Stop number 1 always.

If there are n stops, there will be n paths.One path connects two stops. Distances (in meters) for all paths in Ring Route is given in array Path[] as given below:
Path = [800, 600, 750, 900, 1400, 1200, 1100, 1500]
Fare is determined based on the distance covered from source to destination stop as  Distance between Input Source and Destination Stops can be measured by looking at values in array Path[] and fare can be calculated as per the following criteria:

  • If d =1000 meters, then fare=5 INR

  • (When calculating fare for others, the calculated fare containing any fraction value should be ceiled. For example, for distance 900n when fare initially calculated is 4.5 which must be ceiled to 5)

The path is circular in function. Value at each index indicates distance till the current stops from the previous one. And each index position can be mapped with values at the same index in BusStops [] array, which is a string array holding abbreviation of names for all stops as-
“THANERAILWAYSTN” = ”TH”, “GAONDEVI” = “GA”, “ICEFACTROY” = “IC”, “HARINIWASCIRCLE” = “HA”, “TEENHATHNAKA” = “TE”, “LUISWADI” = “LU”, “NITINCOMPANYJUNCTION” = “NI”, “CADBURRYJUNCTION” = “CA”

Given, n=8, where n is a number of total BusStops.
BusStops = [ “TH”, ”GA”, ”IC”, ”HA”, ”TE”, ”LU”, ”NI”,”CA” ]

Write a code with function get are(String Source, String Destination) which takes Input as the source and destination stops(in the format containing first two characters of the Name of the Bus Stop) and calculate and return travel fare.

Example 1:
Input Values
ca
Ca

Output Values
INVALID OUTPUT

Example 2:
Input Values
NI
HA
Output Values
23.0 INR

Note: Input and Output should be in the format given in the example.

ANSWER:-

#include <bits/stdc++.h>
using namespace std;
int main() {
string s , d;
 cin>>s>>d;
 transform(s.begin(),s.end() , s.begin(),::toupper);
 transform(d.begin(),d.end() , d.begin(),::toupper);
 string arrs[8] = {"TH" , "GA", "IC" , "HA" , "TE", "LU" ,"NI","CA"};
 float arr[8]={800,600,750,900,1400,1200,1100,1500};
 float res=0;
 int st ,ed;
 for(int i=0;i<8;i++)
 {
     if(s==arrs[i])
     st=i;
     
     if(d==arrs[i])
     ed=i;
  }
  if(st==ed)
  {
      cout<<" INVALID INPUT";
      return 0;
  }
  else
  {
      int i=st+1;
      cout<<i;
        while(i!=ed+1)
        {
            res+=(arr[i]);
            i=(i+1)%8;
        }
        cout<<(ceil)(res*0.005);
        return 0;
 }
}
import math
def getFare(source,destination):
    route=[ [ "TH", "GA", "IC", "HA", "TE", "LU", "NI", "CA"],
    [800,600,750,900,1400,1200,1100,1500]
        ]
    fare = 0.0
    if not (source in route[0] and destination in route[0]):
        print("Invalid Input")
        exit()
    if route[0].index(source) < route[0].index(destination):
        for i in range(route[0].index(source),route[0].index(destination)+1):
            fare+=route[1][i]
    elif route[0].index(destination) < route[0].index(source):
        for i in range(route[0].index(source)+1,len(route[0])):
            fare+=route[1][i]
        for i in range(0,route[0].index(destination)+1):
            fare+=route[1][i]
    return float(math.ceil(fare*0.005))
   
source = input()
destination = input()
fare = getFare(source,destination)
if fare == 0:
    print("Invalid Input")
else:
    print(fare)

4 thoughts on “TCS NQT coding questions for 2021 with answers(C/C++/Java)”

  1. Right now it seems like Movable Type is the preferred blogging platform available right now.
    (from what I’ve read) Is that what you’re using on your
    blog?

    Reply
  2. To make your preparation easy, we are discussing previously asked TCS Ninja coding questions. After going through the below mentioned questions, you will be in a position to answer any kind of coding questions. It will be easier for you to answer these questions if your concepts are clear in C programming.

    Reply

Leave a Comment