TCS Coding Questions
TCS Coding Questions
There is a JAR full of candies for sale at a mall counter. JAR has the capacity N, that is JAR can
contain maximum N candies when JAR is full. At any point of time. JAR can have M number of
Candies where M<=N. Candies are served to the customers. JAR is never remain empty as
when last k candies are left. JAR if refilled with new candies in such a way that JAR get full.
Write a code to implement above scenario. Display JAR at counter with available number of
candies. Input should be the number of candies one customer can order at point of time. Update
the JAR after each purchase and display JAR at Counter.
Output should give number of Candies sold and updated number of Candies in JAR.
Given,
K =< 5, where k is number of minimum candies that must be inside JAR ever.
● Input Value
○ 3
● Output Value
○ NUMBER OF CANDIES SOLD : 3
○ NUMBER OF CANDIES AVAILABLE : 7
● Input Value
○ 0
● Output Value
○ INVALID INPUT
○ NUMBER OF CANDIES LEFT : 10
Solution in C
#include<stdio.h>
int main()
{
int n=10, k=5;
int num;
scanf("%d",&num);
if(num>=1 && num<=5)
{
printf("NUMBER OF CANDIES SOLD : %d\n",num);
printf("NUMBER OF CANDIES LEFT : %d",n-num);
}
else
{
printf("INVALID INPUT\n");
printf("NUMBER OF CANDIES LEFT : %d",n);
}
return 0;
}
Solution in C++
#include <iostream.h>
using namespace std;
int main()
{
int n=10, k=5;
int num;
cin>>num;
if(num>=1 && num<=5)
{
cout<< "NUMBER OF CANDIES SOLD : "<<num<<"\n";
cout<<"NUMBER OF CANDIES LEFT : "<<n-num;
}
else
{
cout<<"INVALID INPUT\n";
cout<<"NUMBER OF CANDIES LEFT : "<<n;
}
return 0;
}
Solution in Java
import java.util.Scanner;
class Main{
public static void main(String[] args) {
int n = 10, k = 5;
int num;
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
if(num >= 1 && num <= 5) {
System.out.println("NUMBER OF CANDIES SOLD : " + num);
System.out.print("NUMBER OF CANDIES LEFT : " + (n - num));
} else {
System.out.println("INVALID INPUT");
System.out.print("NUMBER OF CANDIES LEFT : " + n);
}
}
}
Solution in Python
total_candies = 10
no_of_candies = int(input())
if no_of_candies in range(1, 6):
print('No. of Candies Sold:',no_of_candies)
print('No. of Candies Left:',total_candies-no_of_candies)
else:
print("Invalid Input")
print('No. of Candies Left:',total_candies)
Question 2
Selection of MPCS exams include a fitness test which is conducted on ground. There will be a
batch of 3 trainees, appearing for running test in track for 3 rounds. You need to record their
oxygen level after every round. After trainee are finished with all rounds, calculate for each
trainee his average oxygen level over the 3 rounds and select one with highest oxygen level as
the most fit trainee. If more than one trainee attains the same highest average level, they all
need to be selected.
Display the most fit trainee (or trainees) and the highest average oxygen level.
Note:
● The oxygen value entered should not be accepted if it is not in the range between
1 and 100.
● If the calculated maximum average oxygen value of trainees is below 70 then declare
the trainees as unfit with meaningful message as “All trainees are unfit.
● Average Oxygen Values should be rounded.
Example 1:
● INPUT VALUES
95
92
95
92
90
92
90
92
90
● OUTPUT VALUES
○ Trainee Number : 1
○ Trainee Number : 3
Note:
Round 1
Round 2
Round 3
Output must be in given format as in above example. For any wrong input final output
should display “INVALID INPUT”
Solution in C
#include <stdio.h>
int main()
{
int trainee[3][3];
int average[3] = {0};
int i, j, max=0;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf("%d",&trainee[i][j]);
if(trainee[i][j]<1 || trainee[i][j]>100)
{
trainee[i][j] = 0;
}
}
}
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
average[i] = average[i] + trainee[j][i];
}
average[i] = average[i] / 3;
}
for(i=0; i<3; i++) { if(average[i]>max)
{
max = average[i];
}
}
for(i=0; i<3; i++)
{
if(average[i]==max)
{
printf("Trainee Number : %d\n",i+1);
}
if(average[i]<70)
{
printf("Trainee is Unfit");
}
}
return 0;
}
Solution in C++
#include<iostream.h>
using namespace std;
int main()
{
int trainee[3][3];
int average[3] = {0};
int i, j, max=0;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++) { cin>>trainee[i][j];
if(trainee[i][j]<1 || trainee[i][j]>100)
{
trainee[i][j] = 0;
}
}
}
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
average[i] = average[i] + trainee[j][i];
}
average[i] = average[i] / 3;
}
for(i=0; i<3; i++) { if(average[i]>max)
{
max = average[i];
}
}
for(i=0; i<3; i++)
{
if(average[i]==max)
{
cout<<"Trainee Number : "<<i+1<<"\n";
}
if(average[i]<70)
{
cout<<"Trainee is Unfit";
}
}
return 0;
}
Solution in Java
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int[][] trainee = new int[3][3];
int[] average = new int[3];
int max = 0;
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
trainee[i][j] = sc.nextInt();
if(trainee[i][j] < 1 || trainee[i][j] > 100) {
trainee[i][j] = 0;
}
}
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
average[i] = average[i] + trainee[j][i];
}
average[i] = average[i] / 3;
}
for(int i = 0; i < 3; i++) {
if(average[i] > max) {
max = average[i];
}
}
for(int i = 0; i < 3; i++) {
if(average[i] == max) {
System.out.println("Trainee Number : " + (i + 1));
}
if(average[i] <70) {
System.out.print("Trainee is Unfit");
}
}
}
Solution in Python
trainee = [[],[],[],[]]
for i in range(3):
for j in range(3):
trainee[i].append(int(input()))
if (trainee[i][-1]) not in range(1,101):
print("invalid input")
for i in range(3):
trainee[3].append((trainee[2][i]+trainee[1][i]+trainee[0][i])//3)
maximum = max(trainee[3])
for i in range(3):
if trainee[3][i] < 70 :
print("Trainee {0} is unfit".format(i+1))
elif trainee[3][i] == maximum:
print("Trainee Number: ",i+1)
Question 3
A washing machine works on the principle of 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.
For 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.
Write a function which 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”.
Example:
● Input value
2000
● Output value
Solution in Python
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")
Question 4
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.
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 OFFSET to shift the cipher alphabet. Key can have basic shifts from 1 to
25 positions as there are 26 total alphabets.
For Example, if a given plain text contains any digit with values 5 and keyy =2, then 5 will be
replaced by 7, “-”(minus sign) will remain as it is. Key value less than 0 should result into
“INVALID INPUT”
Example 1:
Write a function CustomCaesarCipher(int key, String message) which will accept plaintext and
key as input parameters and returns its cipher text as output.
Solution in C
#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]!='\0')
{
//printf("%d\n", 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;
}
Solution in Python
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))
Question 5
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
If a user enters zero as the number of walls then skip Surface area values as User may
don’t want to paint that wall.
Example 1:
3
12.3
15.2
12.3
15.2
12.3
15.2
10.10
10.10
10.00
Solution in C
#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;
}
Solution in C++
#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;
}
Solution in Java
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);
}
}
}
Solution in Python
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")
Question 6
A City Bus is a Ring Route Bus which runs in 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:
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 following criteria:
Path is circular in function. Value at each index indicates distance till current stop from the
previous one. And each index position can be mapped with values at same index in BusStops []
array, which is a string array holding abbreviation of names for all stops as-
Write a code with function getFare(String Source, String Destination) which take Input as 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
Input should not be case sensitive and output should be in the format INR
Solution in C++
#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;
}
}
Solution in Python
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)
Question 7
There are total n number of Monkeys sitting on the branches of a huge Tree. As travelers offer
Bananas and Peanuts, the Monkeys jump down the Tree. If every Monkey can eat k Bananas
and j Peanuts. If total m number of Bananas and p number of Peanuts are offered by travelers,
calculate how many Monkeys remain on the Tree after some of them jumped down to eat.
At a time one Monkeys gets down and finishes eating and go to the other side of the road. The
Monkey who climbed down does not climb up again after eating until the other Monkeys finish
eating.
Monkey can either eat k Bananas or j Peanuts. If for last Monkey there are less than k Bananas
left on the ground or less than j Peanuts left on the ground, only that Monkey can eat
Bananas(<k) along with the Peanuts(<j).
Write code to take inputs as n, m, p, k, j and return the number of Monkeys left on the Tree.
k= Number of eatable Bananas by Single Monkey (Monkey that jumped down last may
get less than k Bananas)
j = Number of eatable Peanuts by single Monkey(Monkey that jumped down last may get
less than j Peanuts)
Remember that the Monkeys always eat Bananas and Peanuts, so there is no possibility of k
and j having a value zero
Example 1:
Input Values
20
12
12
Output Values
Note:Kindly follow the order of inputs as n,k,j,m,p as given in the above example. And output
must include the same format as in above example(Number of Monkeys left on the Tree:)
Solution in C
#include <stdio.h>
int main()
{
int n,k,j,m,p;
float atebanana=0.0,atepeanut=0.0;
scanf("%d %d %d %d %d",&n,&k,&j,&m,&p);
if(n<0 || k<0 || j<0 || m<0 || p<0)
{
printf("INVALID INPUT");
}
else
{
if(k>0)
atebanana =(float)m/k;
if(j>0)
atepeanut =(float) p/j;
n=n-atebanana-atepeanut;
printf("Number of Monkeys left on the Tree:%d",n);
}
return 0;
}
Solution in Java
import java.util.*;
class Monkeys
{
public static void main(String []args)
{
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int j = sc.nextInt();
int m = sc.nextInt();
int p = sc.nextInt();
int atebanana=0 ,atepeanut=0;
if( n<0 && k<0 || j<0 || m<0 || p<0)
{
System.out.println("Invalid Input");
}
else
{
if(k>0)
atebanana =m/k;
if(j>0)
atepeanut = p/j;
n=n-atebanana-atepeanut;
System.out.println("Number of Monkeys left on the Tree: "+n);
}
}
}
Question 8
Chain Marketing Organization has has a scheme for income generation, through which its
members generate income for themselves. The scheme is such that suppose A joins the
scheme and makes R and V to join this scheme then A is Parent Member of R and V who are
child Members. When any member joins the scheme then the parent gets total commission of
10% from each of its child members.
Child members receive commission of 5% respectively. If a Parent member does not have any
member joined under him, then he gets commission of 5%.
Display how many members joined the scheme including parent member.Calculate the Total
commission gained by each members in the scheme. The fixed amount for joining the scheme
is Rs.5000 on which commission will be generated
SchemeAmount = 5000
TOTAL MEMBERS:3
COMISSION DETAILS
Input :
Amit
Rajesh
Output:
Total Members: 2
Comission Details
Solution in C++
using namespace std;
int main()
{
string par;
cin >> par;
string x;
cin >> x;
if (x == "N") {
cout << "TOTAL MEMBERS:1\n";
cout << "COMISSION DETAILS\n";
cout << par << ":250 INR\n";
} else {
string child;
cin >> child;
vector<string>v;
string temp = "";
for (int i = 0; i < child.length(); i++) {
if (child[i] == ',') {
v.push_back(temp);
temp = "";
}
else if (child[i] != ' ')
temp += child[i];
}
v.push_back(temp);
cout << "TOTAL MEMBERS:" << v.size() + 1 << "\n";
cout << "COMISSION DETAILS\n";
cout << par << ":" << v.size() * 500 << " INR\n";
for (auto a : v) {
cout << a << ":" << "250 INR\n";
}
}
}
Solution in Python
parent = input()
Yes_No = input()
if Yes_No == "N":
print("TOTAL MEMBERS:1\nCOMMISSION DETAILS\n{0}: 250 INR".format(parent))
elif Yes_No == "Y":
child=list(map(str,input().split(",")))
print("TOTAL MEMBERS:{}".format(len(child)+1))
print("COMMISSION DETAILS \n{0}:{1} INR".format(parent,len(child)*500))
for i in child:
print("{0}:250 INR".format(i))
Question 9
FULLY AUTOMATIC VENDING MACHINE – dispenses your cuppa on just press of button. A
vending machine can serve range of products as follows:
Coffee
1. Espresso Coffee
2. Cappuccino Coffee
3. Latte Coffee
Tea
1. Plain Tea
2. Assam Tea
3. Ginger Tea
4. Cardamom Tea
5. Masala Tea
6. Lemon Tea
7. Green Tea
8. Organic Darjeeling Tea
Soups
Beverages
Write a program to take input for main menu & sub menu and display the name of sub
menu selected in the following format (enter the first letter to select main menu):
Welcome to CCD
Enjoy your
Example 1:
● Input:
○ c
○ 1
● Output
○ Welcome to CCD!
○ Enjoy your Espresso Coffee!
Example 2:
● Input
○ t
○ 9
● Output
○ INVALID OUTPUT!
Solution in C
#include <stdio.h>
int main ()
{
char t[8][30] =
{ "Plain Tea", "Assam Tea", "Ginger Tea", "Cardamom Tea", "Masala Tea",
"Lemon Tea", "Green Tea", "Organic Darjeeling Tea" };
char s[4][20] =
{ "Hot and Sour Soup", "Veg Corn Soup", "Tomato Soup",
"Spicy Tomato Soup" };
char b[3][20] =
{ "Hot Chocolate Drink", "Badam Drink", "Badam-Pista Drink" };
int item, i;
if (ch == 'c')
if (item == i + 1)
break;
if (i == 3)
if (item == i + 1)
break;
if (i == 8)
if (item == i + 1)
{
printf ("Welcome to CCD!\nEnjoy your %s!", s[i]);
break;
if (i == 4)
if (item == i + 1)
break;
if (i == 3)
{
else
return 0;
Solution in Python
m = input()
if m=='c' or m=='t' or m=='s' or m=='b':
if m=='c':
submenu = int(input())
if submenu in range(3):
print('Welcome to CCD!\nEnjoy your {}!'.format(menu[0][submenu-1]))
else:
print("INVALID INPUT")
if m=='t':
submenu = int(input())
if submenu in range(8):
print('Welcome to CCD!\nEnjoy your {}!'.format(menu[1][submenu-1]))
else:
print("INVALID INPUT")
if m=='s':
submenu = int(input())
if submenu in range(4):
print('Welcome to CCD!\nEnjoy your {}!'.format(menu[2][submenu-1]))
else:
print("INVALID INPUT")
if m=='b':
submenu = int(input())
if submenu in range(3):
print('Welcome to CCD!\nEnjoy your {}!'.format(menu[3][submenu-1]))
else:
print("INVALID INPUT")
else:
print("INVALID INPUT!")
Question 10
A doctor has a clinic where he serves his patients. The doctor’s consultation fees are different
for different groups of patients depending on their age. If the patient’s age is below 17, fees is
200 INR. If the patient’s age is between 17 and 40, fees is 400 INR. If patient’s age is above 40,
fees is 300 INR. Write a code to calculate earnings in a day for which one array/List of values
representing age of patients visited on that day is passed as input.
Note:
Example 1:
● Input
20
30
40
50
2
3
14
● Output
Total Income 2000 INR
Note: Input and Output Format should be same as given in the above example.
Output Format
Solution in Python
age = []
for i in range(20):
m = input()
if m == "":
break
elif int(m) in range(0,120):
age.append(int(m))
else:
print("INVALID INPUT")
exit()
fees = 0
for i in age:
if i < 17:
fees+=200
elif i <40:
fees+=400
else:
fees+=300
print("Total Income {} INR".format(fees))
Question 11
To check whether a year is leap or not
Step 1:
Step 2:
Step 3:
Solution in C++
#include<stdio.h>
using namespace std;
//main program
int main()
{
//initialising variables
int year;
cout<<"Enter year to check: ";
//user input
cin>>year;
//checking for leap year
if( ((year % 4 == 0)&&(year % 100 != 0)) || (year % 400==0) )
{
//input is a leap year
cout<<year<<" is a leap year";
}
else
{
//input is not a leap year
cout<<year<< " is not a leap year";
}
return 0;
}
Solution in Java
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc=new Scanner(System.in);
//input year from user
System.out.println("Enter a Year");
int year = sc.nextInt();
//condition for checking year entered by user is a leap year or not
if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}
Solution in Python
num = int(input("Enter the year you want to check if is leap year or not: "))
if(num%4 == 0):
if(num%100 == 0):
if(num%400 == 0):
print("The year {} is a leap year".format(num))
else:
print("The year {} is Not a leap year".format(num))
else:
print("The year {} is a leap year".format(num))
else:
print("The year {} is Not a leap year".format(num))
Question 12
Problem Statement (Word is Key)
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
Test cases
Case 1
● Input – defer
● Expected Output – defer is a keyword
Case 2
● Input – While
● Expected Output – while is not a keyword
Solution in C
#include<stdio.h>
#include<string.h>
int main(){
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;
}
Solution in C++
#include<iostream>
#include<string.h>
int main(){
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;
}
Solution in Java
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
String str[]= {"break", "case", "continue", "default", "defer", "else","for", "func", "goto",
"if", "map", "range", "return", "struct", "type", "var"};
int flag = 0;
Scanner sc = new Scanner(System.in);
String input=sc.nextLine();
for(int i = 0; i<16;i++){
if(str[i].equals(input)){
flag = 1;
break;
}
}
if(flag==1){
System.out.println(input+" is a keyword");
}
else{
System.out.println(input+" is not a keyword");
}
}
}
Solution 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")
Question 13
Sweet Seventeen
Test Cases
Case 1
● Input – 1A
● Expected Output – 27
Case 2
● Input – 23GF
● Expected Output – 10980
Solution in C
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(){
char hex[17];
long long decimal, place;
int i = 0, val, len;
decimal = 0;
place = 1;
scanf("%s",hex);
len = strlen(hex);
len--;
for(i = 0;hex[i]!='\0';i++)
{
if(hex[i]>='0'&& hex[i]<='9'){
printf("%lld",decimal);
return 0;
}
Solution in C++
#include <iostream>
#include <math.h>
#include <string.h>
char hex[17];
long long decimal, place;
cin>> hex;
len = strlen(hex);
len--;
for(i = 0;hex[i]!='\0';i++)
{
if(hex[i]>='0'&& hex[i]<='9'){
cout<< decimal;
return 0;
}
Solution in Python
'''The int() function converts the specified value into an integer number.
We are using the same int() method to convert the given input.
int() accepts two arguments, number and base.
Base is optional and the default value is 10.
In the following program we are converting to base 17'''
num = str(input())
print(int(num,17))
Solution in Java
import java.util.*;
public class Main
{
public static void main(String[] args) {
HashMap<Character,Integer> hmap = new HashMap<Character,Integer>();
hmap.put('A',10);
hmap.put('B',11);
hmap.put('C',12);
hmap.put('D',13);
hmap.put('E',14);
hmap.put('F',15);
hmap.put('G',16);
hmap.put('a',10);
hmap.put('b',11);
hmap.put('c',12);
hmap.put('d',13);
hmap.put('e',14);
hmap.put('f',15);
hmap.put('g',16);
Scanner sin = new Scanner(System.in);
String s = sin.nextLine();
long num=0;
int k=0;
for(int i=s.length()-1;i>=0;i--)
{
if((s.charAt(i)>='A'&&s.charAt(i)<='Z')||(s.charAt(i)>='a' &&s.charAt(i)<='z'))
{
num = num + hmap.get(s.charAt(i))*(int)Math.pow(17,k++);
}
else
{
num = num+((s.charAt(i)-'0')*(int)Math.pow(17,k++));
}
}
System.out.println(num);
}
}
Question 14
Oddly Even Problem Statement
Given a maximum of 100 digit numbers as input, find the difference between the sum of odd
and even position digits
Test Cases
Case 1
● Input: 4567
● Expected Output: 2
Explanation :Odd positions are 4 and 6 as they are pos: 1 and pos: 3, both have sum 10.
Similarly, 5 and 7 are at even positions pos: 2 and pos: 4 with sum 12. Thus, difference is 12 –
10 = 2
Case 2
● Input: 5476
● Expected Output: 2
Case 3
● Input: 9834698765123
● Expected Output: 1
Solution in C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int a = 0,b = 0,i = 0, n;
char num[100];
return 0;
}
Solution in C++
#include <iostream>
#include <string.h>
#include <stdlib.h>
int main()
{
int a = 0,b = 0,i = 0, n;
char num[100];
return 0;
}
Solution in Java
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
String s=sin.nextLine();
Solution in Python
num = [int(d) for d in str(input("Enter the number:"))]
even,odd = 0,0
for i in range(0,len(num)):
if i % 2 ==0:
even = even + num[i]
else:
odd = odd + num[i]
print(abs(odd-even))
Question 15
Our hoary culture had several great persons since time immemorial and king vikramaditya’s
nava ratnas (nine gems) belongs to this ilk.They are named in the following shloka:
Among these, Varahamihira was an astrologer of eminence and his book Brihat Jataak is
recokened as the ultimate authority in astrology.
He was once talking with Amarasimha,another gem among the nava ratnas and the author of
Sanskrit thesaurus, Amarakosha.
Amarasimha wanted to know the final position of a person, who starts from the origin 0 0 and
travels per following scheme.
Scheme
… And thus he travels, every time increasing the travel distance by 10 units.
Test Cases
Case 1
● Input : 3
● Expected Output :-20 20
Case 2
● Input: 4
● Expected Output: -20 -20
Case 3
● Input : 5
● Expected Output : 30 -20
Case 4
● Input : 7
● Expected Output : 90 -20
Solution in C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d", &n);
char c = 'R';
int x = 0, y = 0;
int distance = 10;
while(n)
{
switch(c)
{
case 'R':
x = x + distance;
c = 'U';
distance = distance + 10;
break;
case 'U':
y = y + distance;
c = 'L';
distance = distance + 10;
break;
case 'L':
x = x - distance;
c = 'D';
distance = distance + 10;
break;
case 'D':
y = y - distance;
c = 'A';
distance = distance + 10;
break;
case 'A':
x = x + distance;
c = 'R';
distance = distance + 10;
break;
}
n--;
}
printf("%d %d",x,y);
return 0;
}
Solution in C++
#include <iostream>
char c = 'R';
int x = 0, y = 0;
int distance = 10;
while(n)
{
switch(c)
{
case 'R':
x = x + distance;
c = 'U';
distance = distance + 10;
break;
case 'U':
y = y + distance;
c = 'L';
distance = distance + 10;
break;
case 'L':
x = x - distance;
c = 'D';
distance = distance + 10;
break;
case 'D':
y = y - distance;
c = 'A';
distance = distance + 10;
break;
case 'A':
x = x + distance;
c = 'R';
distance = distance + 10;
break;
}
n--;
}
Solution in Java
import java.util.Scanner;
case 'U':
y = y + distance;
ch = 'L';
distance = distance + 10;
break;
case 'L':
x = x - distance;
ch = 'D';
distance = distance + 10;
break;
case 'D':
y = y - distance;
ch = 'A';
distance = distance + 10;
break;
case 'A':
x = x + distance;
ch = 'R';
distance = distance + 10;
break;
}
a--;
}
System.out.println(x+ " , "+y);
}
}
Solution in Python
n = int(input())
c = 'R'
dis = 10
x,y=0,0
for i in range(n):
if c=='R':
x=x+dis
c='U'
dis=dis+10
elif c=='U':
y=y+dis
c='L'
dis=dis+10
elif c=='L':
x=x-dis
c='D'
dis=dis+10
elif c=='D':
y=y-dis
c='A'
dis=dis+10
elif c=='A':
x=x+dis
c='R'
dis=dis+10
print(x,y)
Question 16
Write a code to check whether no is prime or not. Condition use function check() to find whether
entered no is positive or negative ,if negative then enter the no, And if yes pas no as a
parameter to prime() and check whether no is prime or not?
Solution in C
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cout<<"Enter the number: ";
cin>>n;
if(n>0){
prime(n);
}
else{
cout<<"negative number.Please enter a postive number"<<endl;
}
return 0;
}
Solution in C++
#include <iostream>
using namespace std;
void enter();
void check(int);
void prime(int);
int main()
{
enter();
return 0;
Solution in Java
import java.util.Scanner;
class Main
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
//First we will ask the user to enter a number
System.out.println ("Enter value to be evaluated : ");
int n = sc.nextInt ();
//create object of class CheckPrime
Main prime = new Main ();
//calling function with value n, as parameter
prime.verify (n);
}
//function for checking number is positive or negative
void verify (int n)
{
if (n < 0)
System.out.println ("Negative number detected enter positive number");
else
calc (n);
}
//creating function for checking prime or not
void calc (int n)
{
int x = 0;
for (int i = 2; i < n; i++)
{
if (n % i == 0)
++x;
}
if (x >= 1)
System.out.println ("The number that you have entered is not prime");
else
System.out.println ("The number that you have entered is prime");
}
}
Question 17
Find the 15th term of the series?
0,0,7,6,14,12,21,18, 28
void main()
{
int n;
scanf("%d",&n);
if(n%2==0)
a1(n/2);
else
a2(n/2+1);
}
int a1(int x)
{
int s=0;
for(int i=0;i<x-1;i++)
{
s=s+6;
}
printf("%d",s);
}
int a2(int x)
{
int s=0;
for(int i=0;i<x-1;i++)
{
s=s+7;
}
printf("%d",s);
}
Solution in C++
#include <iostream>
using namespace std;
int main()
{
//we would be init. the variables here
int val, extra;
cout<<"Enter the term you want to print: ";
//user input
cin>>val;
//logic for merging to different patterns
if(val==0||val==1)
{
cout<<0;
return 0;
}
else if(val%2==0)
{
val=val/2;
extra=6;
}
else
{
val=val/2+1;
extra=7;
}
//the code brain ends here
//now, we will print o/p
cout<<(val-1)*extra;
return 0;
}
Solution in Java
import java.util.Scanner;
if (i % 2 != 0)
{
a = a + 7;
arr[k] = a;
k++;
}
else
{
b = b + 6;
arr[k] = b;
k++;
}
}
System.out.print (arr[n - 1]);
}
}
Solution in Python
val = int (input ('enter the number: ')) x = 0 y = 0 for i
in range (1, val + 1):
if (i % 2 != 0)
:
x=x+7
else
:
y = y + 6 if (val % 2 != 0)
:
print (' {} term in accordance to the program is {}'.
format (val, x - 7))
else:
print ('{} term in accordance to the program is {}'.format (val, y - 6))
Question 18
Find the nth term of the series.
Test Case 1
● Input- 16
● Expected Output – 2187
Test Case 2
● Input- 13
● Expected Output – 64
Explanation
1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243,64, 729, 128, 2187 can represented as :
There are two consecutive sub GP’s at even and odd positions
Solution in C
#include<stdio.h>
#include<math.h>
int three(int n)
{
int x;
//n-1 because powers start from 0 not 1
x = pow(3,n-1);
printf("%d",x);
}
int two(int n)
{
int x;
//n-1 because powers start from 0 not 1
x = pow(2,n-1);
printf("%d",x);
}
int main()
{
int n;
scanf("%d",&n);
Solution in C++
#include<iostream>
#include<math.h>
int two(int n)
{
int x;
//n-1 because powers start from 0 not 1
x = pow(2,n-1);
cout<< x;
}
int main()
{
int n;
cin >> n;
Solution in Python
num = int(input())
if(num%2==0):
num = num // 2
print(3**(num-1))
else:
num = num // 2 + 1
print(2**(num-1))
Question 19
The program will receive 3 English words inputs from STDIN
1. These three words will be read one at a time, in three separate line
2. The first word should be changed like all vowels should be replaced by *
3. The second word should be changed like all consonants should be replaced by @
4. The third word should be changed like all char should be converted to upper case
5. Then concatenate the three words and print them
Other than these concatenated word, no other characters/string should or message should be
written to STDOUT
For example if you print how are you then output should be h*wa@eYOU.
You can assume that input of each word will not exceed more than 5 chars
Test Cases
Case 1
Input
● how
● are
● you
Case 2
Input
● how
● 999
● you
Solution in C
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
int i;
char a[100],b[100],c[100];
scanf("%s",a);
scanf("%s",b);
scanf("%s",c);
for(i=0;a[i]!='\0';i++)
{
if(a[i]=='a'||a[i]=='e'||a[i]=='i'||a[i]=='o'||a[i]=='u'||a[i]=='A'||a[i]=='E'||a[i]=='I'||a[i]=='O'||a[i]=='U')
a[i]='*';
}
for(i=0;b[i]!='\0';i++)
{
if((b[i]>='a'&&b[i]<='z') || (b[i]>='A'&&b[i]<='Z'))
if(!(b[i]=='a'||b[i]=='e'||b[i]=='i'||b[i]=='o'||b[i]=='u'||b[i]=='A'||b[i]=='E'||b[i]=='I'||b[i]=='O'||b[i]=='U'))
b[i]='@';
}
for(i=0;c[i]!='\0';i++)
{
if(c[i]>='a'&&c[i]<='z')
c[i]=c[i]-32;
}
printf("%s%s%s",a,b,c);
return 0;
}
Solution in C++
#include<iostream>
#include<string.h>
int main()
{
int i;
char a[100],b[100],c[100];
cin >> a;
cin >> b;
cin >> c;
for(i=0;a[i]!='\0';i++)
{
if(a[i]=='a'||a[i]=='e'||a[i]=='i'||a[i]=='o'||a[i]=='u'||a[i]=='A'||a[i]=='E'||a[i]=='I'||a[i]=='O'||a[i]=='U')
a[i]='*';
}
for(i=0;b[i]!='\0';i++)
{
if((b[i]>='a'&&b[i]<='z') || (b[i]>='A'&&b[i]<='Z'))
if(!(b[i]=='a'||b[i]=='e'||b[i]=='i'||b[i]=='o'||b[i]=='u'||b[i]=='A'||b[i]=='E'||b[i]=='I'||b[i]=='O'||b[i]=='U'))
b[i]='@';
}
for(i=0;c[i]!='\0';i++)
{
if(c[i]>='a'&&c[i]<='z')
c[i]=c[i]-32;
}
Solution in C
#include<stdio.h>
int main()
{
int i, n, a=0, b=0;
printf("enter number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(i%2!=0)
{
if(i>1)
a = a + 2;
}
else
{
b = a/2;
}
}
if(n%2!=0)
{
printf("%d",a);
}
else
{
printf("%d",b);
}
return 0;
}
Solution in C++
#include<iostream>
using namespace std;
int main()
{
int i, n, a=0, b=0;
cout << "enter number : ";
cin >> n;
for(i=1;i<=n;i++)
{
if(i%2!=0)
{
if(i>1)
a = a + 2;
}
else
{
b = a/2;
}
}
if(n%2!=0)
{
cout << a;
}
else
{
cout << b;
}
return 0;
}
Solution in Java
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a = 0, b = 0;
if(n % 2 == 0)
{
for(int i = 1 ; i <= (n-2) ; i = i+2)
{
a = a + 2;
b = a / 2;
}
System.out.print(b);
}
else
{
for(int i = 1 ; i < (n-2) ; i = i+2)
{
a = a + 2;
b = a / 2;
}
a = a + 2;
System.out.print(a);
}
}
}
Solution in Python
n = int(input('enter the number:'))
a=0
b=0
for i in range(1,n+1):
if(i%2!=0):
a= a+2
else:
b= b+1
if(n%2!=0):
print('{}'.format(a-2))
else:
print('{}'.format(b-1))