0% found this document useful (0 votes)
2 views32 pages

Tcs Coding

The document outlines multiple programming problems involving vehicle production, string validation, array element counting, parking lot management, and guest tracking at a party. Each problem includes a detailed problem statement, input/output specifications, and example scenarios. The document also provides sample code snippets for each problem to illustrate potential solutions.

Uploaded by

ultronverse01
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views32 pages

Tcs Coding

The document outlines multiple programming problems involving vehicle production, string validation, array element counting, parking lot management, and guest tracking at a party. Each problem includes a detailed problem statement, input/output specifications, and example scenarios. The document also provides sample code snippets for each problem to illustrate potential solutions.

Uploaded by

ultronverse01
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

> Problem Statement – An automobile company manufactures both a two wheeler (TW) cout << "Enter the total number of vehicles: ";
and a four wheeler (FW). A company manager wants to make the production of both cin >> v;
types of vehicle according to the given data below: cout << "Enter the total number of wheels: ";
cin >> w;
1st data, Total number of vehicle (two-wheeler + four-wheeler)=v
2nd data, Total number of wheels = W // Check constraints
The task is to find how many two-wheelers as well as four-wheelers need to if (w < 2 || w % 2 != 0 || v >= w)
manufacture as per the given data. {
Example : cout << "INVALID INPUT";
return 0;
Input : }
200 -> Value of V
540 -> Value of W // Calculate the number of two-wheelers and four-wheelers
tw = (4*v-w)/2;
Output : fw = v - tw;
TW =130 FW=70
// Print the output
Explanation: cout << "TW = " << tw << " FW = " << fw;
130+70 = 200 vehicles
(70*4)+(130*2)= 540 wheels return 0;
}
Constraints :

2<=W Output:-
W%2=0 Enter the total number of vehicles: 200
V<W Enter the total number of wheels: 540
Print “INVALID INPUT” , if inputs did not meet the constraints. TW = 130 FW = 70

The input format for testing


The candidate has to write the code to accept two positive numbers separated by a
new line.

First Input line – Accept value of V.


Second Input line- Accept value for W.
The output format for testing

Written program code should generate two outputs, each separated by a single space
character(see the example)
Additional messages in the output will result in the failure of test case

Ans =
#include <iostream>
using namespace std;

int main() {
// Declare variables
int v, w, tw, fw;

// Get input from user


2.> Problem Statement – Given a string S(input consisting) of ‘*’ and ‘#’. The
length of the string is variable. The task is to find the minimum number of ‘*’ or return 0;
‘#’ to make it a valid string. The string is considered valid if the number of ‘*’ }
and ‘#’ are equal. The ‘*’ and ‘#’ can be at any position in the string.
Note : The output will be a positive or negative integer based on number of ‘*’ and
‘#’ in the input string.
Output:-
(*>#): positive integer Enter the string: ***###
(#>*): negative integer The minimum number of characters to make the string valid is: 0
(#=*): 0
Example 1:
Input 1:

###*** -> Value of S


Output :

0 → number of * and # are equal

Ans =
#include <iostream>
using namespace std;

int main() {
// Declare variables
string s;
int count_star, count_hash;

// Get input from user


cout << "Enter the string: ";
cin >> s;

// Initialize the counters


count_star = 0;
count_hash = 0;

// Iterate over the string


for (char c : s) {
if (c == '*') {
count_star++;
} else if (c == '#') {
count_hash++;
}
}

// Calculate the minimum number of `*` or `#`


int diff = count_star - count_hash;

// Print the output


cout << "The minimum number of characters to make the string valid is: " << diff;
3.> Given an integer array Arr of size N the task is to find the count of elements int max_so_far = Arr[0]; // Initialize the maximum element found so far with
whose value is greater than all of its prior elements. the first element

Note : 1st element of the array should be considered in the count of the result. for (int i = 1; i < n; i++) {
if (Arr[i] > max_so_far) {
For example, count++;
Arr[]={7,4,8,2,9} max_so_far = Arr[i];
As 7 is the first element, it will consider in the result. }
8 and 9 are also the elements that are greater than all of its previous elements. }
Since total of 3 elements is present in the array that meets the condition.
Hence the output = 3. return count;
Example 1: }

Input int main() {


5 -> Value of N, represents size of Arr int N;
7-> Value of Arr[0] cout << "Enter the size of the array (N): ";
4 -> Value of Arr[1] cin >> N;
8-> Value of Arr[2]
2-> Value of Arr[3] vector<int> Arr(N);
9-> Value of Arr[4] cout << "Enter " << N << " elements: ";
for (int i = 0; i < N; i++) {
Output : cin >> Arr[i];
3 }

Example 2: int result = countElementsGreaterThanPrior(Arr);


5 -> Value of N, represents size of Arr cout << "The count of elements greater than all of their prior elements is: "
3 -> Value of Arr[0] << result << endl;
4 -> Value of Arr[1]
5 -> Value of Arr[2] return 0;
8 -> Value of Arr[3] }
9 -> Value of Arr[4]

Output :
5 Ans 2.=
#include <iostream>
Constraints using namespace std;

1<=N<=20 int countElementsGreaterThanPrior(int Arr[], int N) {


1<=Arr[i]<=10000 int count = 1; // Initialize count to 1 to include the first element
int max_so_far = Arr[0]; // Initialize the maximum element found so far with
the first element

Ans 1.= for (int i = 1; i < N; i++) {


#include <iostream> if (Arr[i] > max_so_far) {
#include <vector> count++;
using namespace std; max_so_far = Arr[i];
}
int countElementsGreaterThanPrior(vector<int>& Arr) { }
int n = [Link]();
int count = 1; // Initialize count to 1 to include the first element return count;
} 4.> A parking lot in a mall has RxC number of parking spaces. Each parking space
will either be empty(0) or full(1). The status (0/1) of a parking space is
int main() { represented as the element of the matrix. The task is to find index of the
int N; prpeinzta row(R) in the parking lot that has the most of the parking spaces
cout << "Enter the size of the array (N): "; full(1).
cin >> N;
Note :
int Arr[N]; RxC- Size of the matrix
cout << "Enter " << N << " elements: "; Elements of the matrix M should be only 0 or 1.
for (int i = 0; i < N; i++) {
cin >> Arr[i]; Example 1:
} Input :
3 -> Value of R(row)
int result = countElementsGreaterThanPrior(Arr, N); 3 -> value of C(column)
cout << "The count of elements greater than all of their prior elements is: " [0 1 0 1 1 0 1 1 1] -> Elements of the array M[R][C] where each element is
<< result << endl; separated by new line.
Output :
return 0; 3 -> Row 3 has maximum number of 1’s
}
Example 2:
input :
4 -> Value of R(row)
Output:- 3 -> Value of C(column)
Enter the size of the array: 5 [0 1 0 1 1 0 1 0 1 1 1 1] -> Elements of the array M[R][C]
Enter the elements of the array: 7 Output :
4 4 -> Row 4 has maximum number of 1’s
8
2
9 Ans 1. =
The count of elements whose value is greater than all of its prior elements is: 3
#include <iostream>
using namespace std;

int findMaxRow(int** matrix, int row, int col) {


int maxCount = 0;
int maxRow = 0;
for (int i = 0; i < row; i++) {
int count = 0;
for (int j = 0; j < col; j++) {
if (matrix[i][j] == 1) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
maxRow = i+1;
}
}
return maxRow;
}
}
int main() { if (count > maxCount) {
int row, col; maxCount = count;
cout << "Enter the number of rows: "; maxRow = i+1;
cin >> row; }
cout << "Enter the number of columns: "; }
cin >> col; return maxRow;
}
int** matrix = new int*[row];
for (int i = 0; i < row; i++) { int main() {
matrix[i] = new int[col]; int row, col;
} cout << "Enter the number of rows: ";
cin >> row;
cout << "Enter the elements of the matrix: " << endl; cout << "Enter the number of columns: ";
for (int i = 0; i < row; i++) { cin >> col;
for (int j = 0; j < col; j++) {
cin >> matrix[i][j]; vector<vector<int>> matrix(row, vector<int>(col));
}
} cout << "Enter the elements of the matrix: " << endl;
for (int i = 0; i < row; i++) {
int maxRow = findMaxRow(matrix, row, col); for (int j = 0; j < col; j++) {
cout << "The row with the maximum number of 1s is: " << maxRow << endl; cin >> matrix[i][j];
}
// // Free memory }
// for (int i = 0; i < row; i++) {
// delete[] matrix[i]; int maxRow = findMaxRow(matrix, row, col);
// } cout << "The row with the maximum number of 1s is: " << maxRow << endl;
// delete[] matrix;
return 0;
return 0; }
}

Output :-
Ans 2. = Enter the number of rows: 3
Enter the number of columns: 3
#include <iostream> Enter the elements of the matrix:
#include <vector> 1
0
using namespace std; 0
1
int findMaxRow(const vector<vector<int>>& matrix, int row, int col) { 1
int maxCount = 0; 0
int maxRow = -1; 1
for (int i = 0; i < row; i++) { 1
int count = 0; 1
for (int j = 0; j < col; j++) { The row with the maximum number of 1s is: 3
if (matrix[i][j] == 1) {
count++;
}
5.> A party has been organised on cruise. The party is organised for a limited
time(T). The number of guests entering (E[i]) and leaving (L[i]) the party at every Explanation:
hour is represented as elements of the array. The task is to find the maximum Hour 1:
number of guests present on the cruise at any given instance within T hours. Entry: 3 Exit: 0
No. of guests on ship: 3
Example 1:
Input : Hour 2:
Entry : 5 Exit : 2
5 -> Value of T No. of guest on ship: 3+5-2=6
[7,0,5,1,3] -> E[], Element of E[0] to E[N-1], where input each element is
separated by new line Hour 3:
[1,2,1,3,4] -> L[], Element of L[0] to L[N-1], while input each element is Entry : 2 Exit: 4
separate by new line. No. of guests on ship: 6+2-4= 4
Output :
8 -> Maximum number of guests on cruise at an instance. Hour 4:
Entry: 0 Exit : 4
Explanation: No. of guests on ship : 4+0-4=0

1st hour: Hence, the maximum number of guests within 5 hours is 6.


Entry : 7 Exit: 1 The input format for testing
No. of guests on ship : 6 The candidate has to write the code to accept 3 input.
First input- Accept value for number of T(Positive integer number)
2nd hour : Second input- Accept T number of values, where each value is separated by a new
Entry : 0 Exit : 2 line.
No. of guests on ship : 6-2=4 Third input- Accept T number of values, where each value is separated by a new
line.
Hour 3: The output format for testing
Entry: 5 Exit: 1 The output should be a positive integer number or a message as given in the problem
No. of guests on ship : 4+5-1=8 statement(Check the output in Example 1 and Example 2)

Hour 4: Constraints:
Entry : 1 Exit : 3
No. of guests on ship : 8+1-3=6 1<=T<=25
0<= E[i] <=500
Hour 5: 0<= L[i] <=500
Entry : 3 Exit: 4
No. of guests on ship: 6+3-4=5
Hence, the maximum number of guests within 5 hours is 8.
Ans 1.=
Example 2:
Input: #include <iostream>
4 -> Value of T
[3,5,2,0] -> E[], Element of E[0] to E[N-1], where input each element is using namespace std;
separated by new line.
[0,2,4,4] -> L[], Element of L[0] to L[N-1], while input each element in int findMaxGuests(int entry[], int exit[], int T) {
separated by new line int currentGuests = 0;
int maxGuests = 0;
Output:
6 for (int i = 0; i < T; i++) {
Cruise at an instance currentGuests = currentGuests + entry[i] - exit[i];
if (currentGuests > maxGuests) { Maximum number of guests on the cruise at any given instance: 8
maxGuests = currentGuests;
}
}
Ans 2.=
return maxGuests;
} #include <iostream>
#include <vector>
int main() {
int T; using namespace std;
cout << "Enter the value of T: ";
cin >> T; int findMaxGuests(const vector<int>& entry, const vector<int>& exit, int T) {
int currentGuests = 0;
int entry[T]; int maxGuests = 0;
int exit[T];
for (int i = 0; i < T; i++) {
cout << "Enter the values for guests entering the party:\n"; currentGuests = currentGuests + entry[i] - exit[i];
for (int i = 0; i < T; i++) { if (currentGuests > maxGuests) {
cin >> entry[i]; maxGuests = currentGuests;
} }
}
cout << "Enter the values for guests leaving the party:\n";
for (int i = 0; i < T; i++) { return maxGuests;
cin >> exit[i]; }
}
int main() {
int maxGuests = findMaxGuests(entry, exit, T); int T;
cout << "Maximum number of guests on the cruise at any given instance: " << cout << "Enter the value of T: ";
maxGuests << endl; cin >> T;

return 0; vector<int> entry(T);


} vector<int> exit(T);

cout << "Enter the values for guests entering the party:\n";
for (int i = 0; i < T; i++) {
Output :- cin >> entry[i];
}
Enter the value of T: 5
Enter the values for guests entering the party: cout << "Enter the values for guests leaving the party:\n";
7 for (int i = 0; i < T; i++) {
0 cin >> exit[i];
5 }
1
3 int maxGuests = findMaxGuests(entry, exit, T);
Enter the values for guests leaving the party: cout << "Maximum number of guests on the cruise at any given instance: " <<
1 maxGuests << endl;
2
1 return 0;
3 }
4
6.> At a fun fair, a street vendor is selling different colours of balloons. He First input: Accept value for number of N(Positive integer number).
sells N number of different colours of balloons (B[]). The task is to find the Second Input : Accept N number of character values (B[]), where each value is
colour (odd) of the balloon which is present odd number of times in the bunch of separated by a new line.
balloons. Output format for testing
The output should be a single literal (Check the output in example 1 and example 2)
Note: If there is more than one colour which is odd in number, then the first
colour in the array which is present odd number of times is displayed. The colours Constraints:
of the balloons can all be either upper case or lower case in the array. If all the
inputs are even in number, display the message “All are even”. 3<=N<=50
B[i]={{a-z} or {A-Z}}
Example 1:

7 -> Value of N
[r,g,b,b,g,y,y] -> B[] Elements B[0] to B[N-1], where each input element is
sepārated by ṉew line. Ans =
Output :
#include <iostream>
r -> [r,g,b,b,g,y,y] -> “r” colour balloon is present odd number of times in the #include <unordered_map>
bunch. using namespace std;
Explanation:
From the input array above: char findOddColor(char B[], int N) {
unordered_map<char, int> colorCount;
r: 1 balloon
g: 2 balloons for (int i = 0; i < N; i++) {
b: 2 balloons colorCount[B[i]]++;
y : 2 balloons }
Hence , r is only the balloon which is odd in number.
Example 2: for (int i = 0; i < N; i++) {
Input: if (colorCount[B[i]] % 2 != 0) {
return B[i];
10 -> Value of N }
[a,b,b,b,c,c,c,a,f,c] -> B[], elements B[0] to B[N-1] where input each element is }
separated by new line.
Output : return 0;
b-> ‘b’ colour balloon is present odd number of times in the bunch. }

Explanation: int main() {


From the input array above: int N;
cout << "Enter the value of N: ";
a: 2 balloons cin >> N;
b: 3 balloons
c: 4 balloons char B[N];
f: 1 balloons cout << "Enter the colors of the balloons (characters):" << endl;
Here, both ‘b’ and ‘f’ have odd number of balloons. But ‘b’ colour balloon occurs for (int i = 0; i < N; i++) {
first. cin >> B[i];
Hence , b is the output. }

Input Format for testing char oddColor = findOddColor(B, N);


The candidate has to write the code to accept: 2 input if (oddColor != '\0') {
cout << "The color of the balloon that is present an odd number of times: "
<< oddColor << endl; 7.>There is a JAR full of candies for sale at a mall counter. JAR has the capacity
} else { N, that is JAR can contain maximum N candies when JAR is full. At any point of
cout << "All colors are even." << endl; 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.
return 0; 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.
Output :-
Enter the value of N: 10 If Input is more than candies in JAR, return: “INVALID INPUT”
Enter the colors of the balloons (characters): Given,
a N=10, where N is NUMBER OF CANDIES AVAILABLE
b K =< 5, where k is number of minimum candies that must be inside JAR ever.
b Example 1:(N = 10, k =< 5)
b
c Input Value
c 3
c Output Value
a NUMBER OF CANDIES SOLD : 3
f NUMBER OF CANDIES AVAILABLE : 7
c
The color of the balloon that is present an odd number of times: b Example : (N=10, k<=5)

Input Value
0
Output Value
INVALID INPUT NUMBER OF
CANDIES LEFT : 10

Ans =

#include <iostream>
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; 8.> 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
return 0; 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:
Input should be 9 integer values representing oxygen levels entered in order as

Round 1

Oxygen value of trainee 1


Oxygen value of trainee 2
Oxygen value of trainee 3
Round 2

Oxygen value of trainee 1


Oxygen value of trainee 2
Oxygen value of trainee 3
Round 3

Oxygen value of trainee 1


Oxygen value of trainee 2
Oxygen value of trainee 3
Output must be in given format as in above example. For any wrong input final
output should display “INVALID INPUT”
Output :-

95
Ans 1.= 92
95
#include <iostream> 92
using namespace std; 90
int main() 92
{ 90
int trainee[3][3]; 92
int average[3] = {0}; 90
int i, j, max=0; Trainee Number : 1
for(i=0; i<3; i++) Trainee Number : 3
{
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;
}
9.> A washing machine works on the principle of Fuzzy System, the weight of clothes return "Time Estimated: 35 minutes";
put inside it for washing is uncertain But based on weight measured by sensors, it } else if (weight > 4000 && weight <= 7000) {
decides time and water level which can be changed by menus given on the machine return "Time Estimated: 45 minutes";
control area. } else {
return "OVERLOADED";
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 int main() {
is between 2001 grams and 4000 grams. int weight;
cout << "Enter the weight in grams: ";
For high level water, the time estimate is 45 minutes, where approximately weight cin >> weight;
is above 4000 grams.
if (weight >= 0 && weight <= 7000) {
Assume the capacity of machine is maximum 7000 grams cout << estimateTime(weight) << endl;
} else {
Where approximately weight is zero, time estimate is 0 minutes. cout << "INVALID INPUT" << endl;
}
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 return 0;
output statement is }

“INVALID INPUT”.

Input should be in the form of integer value – Ans 2.=

Output must have the following format – #include<bits/stdc++.h>


using namespace std;
Time Estimated: Minutes void calculateTime (int n)
{
Example: if (n == 0)
Input value cout << "Time Estimated : 0 Minutes";
2000
Output value else if (n > 0 && n <= 2000)
Time Estimated: 25 minutes cout << "Time Estimated : 25 Minutes";

else if (n > 2000 && n <= 4000)


cout << "Time Estimated : 35 Minutes";

Ans 1.= else if (n > 4000 && n <= 7000)


cout << "Time Estimated : 45 Minutes";
#include <iostream>
using namespace std; else
cout << "INVALID INPUT";
string estimateTime(int weight) { }
if (weight == 0) {
return "Time Estimated: 0 minutes"; int main ()
} else if (weight > 0 && weight <= 2000) { {
return "Time Estimated: 25 minutes"; int Weight;
} else if (weight > 2000 && weight <= 4000) { cin >> Weight;
10.> The Caesar cipher is a type of substitution cipher in which each alphabet in
calculateTime (Weight); the plaintext or messages is shifted by a number of places down the alphabet.
return 0; 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 OFFSET 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 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:
Enter your PlainText: All the best
Enter the Key: 1

The encrypted Text is: Bmm uif Cftu

Write a function CustomCaesarCipher(int key, String message) which will accept


plaintext and key as input parameters and returns its cipher text as output.

Ans =

#include <iostream>
#include <string>
using namespace std;

string CustomCaesarCipher(int key, const string& message) {


if (key < 0) {
return "INVALID INPUT";
}

string encryptedText = "";

for (char ch : message) {


if (isalpha(ch)) { // If the character is an alphabet
char base = isupper(ch) ? 'A' : 'a';
char shiftedChar = (ch - base + key) % 26 + base;
encryptedText += shiftedChar;
} else if (isdigit(ch)) { // If the character is a numeric digit
int digit = ch - '0';
int shiftedDigit = (digit + key) % 10;
encryptedText += to_string(shiftedDigit);
} else { // For non-alphabetic and non-numeric characters, keep them
unchanged
encryptedText += ch; }
} }
} else if (s[i] >= 65 && s[i] <= 90)
{
return encryptedText; if (s[i] + key <= 90)
} {
s[i] = s[i] + key;
int main() { }
int key; else
string plaintext; {
int left = (s[i] + key) - 90;
cout << "Enter your PlainText: "; s[i] = 64 + left;
getline(cin, plaintext); }
}
cout << "Enter the Key: "; else if (s[i] >= 97 && s[i] <= 122)
cin >> key; {
if (s[i] + key <= 122)
string encryptedText = CustomCaesarCipher(key, plaintext); {
cout << "The encrypted Text is: " << encryptedText << endl; s[i] = s[i] + key;
}
return 0; else
} {
int left = (s[i] + key) - 122;
s[i] = 96 + left;
}
Ans 2.= }
}
#include <bits/stdc++.h> }
using namespace std; cout << "The Encrypted Text is:" << s;
void ceaser(string s, int key) }
{
if (key == 0) int main()
{ {
printf("INVALID INPUT"); string s;
} int key;
else
{ cout << "Enter the plain text :";
for (int i = 0; i < [Link](); i++) getline(cin, s);
{
cout << "\nEnter the key :";
if (isdigit(s[i])) cin >> key;
{
if (s[i] + key <= 57) ceaser(s, key);
{ return 0;
s[i] = s[i] + key; }
}
else
{ Output:-
int left = (s[i] + key) - 57; Enter the plain text :AKASH KUMAR
s[i] = 47 + left;
Enter the key :1 11.> We want to estimate the cost of painting a property. Interior wall painting
The Encrypted Text is:BLBTI LVNBS cost is Rs.18 per [Link]. and exterior wall painting cost is Rs.12 per [Link].

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 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
Note: Follow in input and output format as given in above example

Ans =

#include <iostream>
using namespace std;

int main() {
int ni, ne, i = 0;
float int_p = 18, ext_p = 12, cost = 0, temp;

cin >> ni; // Remove endl from here


cin >> ne; // Remove endl from here

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++) { 12.> A City Bus is a Ring Route Bus which runs in circular [Link] is, Bus
cin >> temp; once starts at the Source Bus Stop, halts at each Bus Stop in its Route and at the
cost += ext_p * temp; 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
cout << "Total estimated Cost : " << cost; Bus Stop, the next stop in the Route will be Bus Stop number 1 always.
} If there are n stops, there will be n [Link] path connects two stops. Distances
return 0; (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 following criteria:

If d =1000 metres, 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)
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-
“THANERAILWAYSTN” = ”TH”, “GAONDEVI” = “GA”, “ICEFACTROY” = “IC”, “HARINIWASCIRCLE”
= “HA”, “TEENHATHNAKA” = “TE”, “LUISWADI” = “LU”, “NITINCOMPANYJUNCTION” = “NI”,
“CADBURRYJUNCTION” = “CA”

Given, n=8, where n is number of total BusStops.


BusStops = [ “TH”, ”GA”, ”IC”, ”HA”, ”TE”, ”LU”, ”NI”,”CA” ]

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
Note: Input and Output should be in format given in example.
Input should not be case sensitive and output should be in the format INR

Ans =
13.> There are total n number of Monkeys sitting on the branches of a huge Tree. As
#include <bits/stdc++.h> travelers offer Bananas and Peanuts, the Monkeys jump down the Tree. If every
using namespace std; 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
int main() 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
string s, d; road. The Monkey who climbed down does not climb up again after eating until the
cin >> s >> d; other Monkeys finish eating.
string arrs[8] = {"TH", "GA", "IC", "HA", "TE", "LU", "NI", "CA"}; Monkey can either eat k Bananas or j Peanuts. If for last Monkey there are less
float arr[8] = {800, 600, 750, 900, 1400, 1200, 1100, 1500}; than k Bananas left on the ground or less than j Peanuts left on the ground, only
float res = 0; that Monkey can eat Bananas(<k) along with the Peanuts(<j).
int st, ed; Write code to take inputs as n, m, p, k, j and return the number of Monkeys left
for (int i = 0; i < 8; i++) on the Tree.
{ Where, n= Total no of Monkeys
if (s == arrs[i]) k= Number of eatable Bananas by Single Monkey (Monkey that jumped down last
st = i; may get less than k Bananas)
if (d == arrs[i]) j = Number of eatable Peanuts by single Monkey(Monkey that jumped down last
ed = i; may get less than j Peanuts)
} m = Total number of Bananas
if (st == ed) p = Total number of Peanuts
{ Remember that the Monkeys always eat Bananas and Peanuts, so there is no
cout << " INVALID INPUT"; possibility of k and j having a value zero
return 0;
} Example 1:
else Input Values
{ 20
int i = st + 1; 2
3
while (i != ed + 1) 12
{ 12
res = res + arr[i];
i = (i + 1) % 8; Output Values
} Number of Monkeys left on the tree:10
res = (float)res / 200; 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
//printf("%.1f INR", ceil(res)); Monkeys left on the Tree:)
cout << fixed << setprecision(1) << ceil(res) << " INR" << endl; For any wrong input display INVALID INPUT

return 0;
}
} Ans =

#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,k,j,m,p;
float atebanana=0.0, atepeanut=0.0;
cin>>n>>k>>j>>m>>p;
if(n<0 or k<0 or j<0 or m<0 or p<0)
{ 14.> Chain Marketing Organization has has a scheme for income generation, through
cout<<"INVALID INPUT"; 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
else 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.
if(k>0) 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%.
atebanana =(float)(m/k); Take name of the members joining the scheme as input.
m=m%k; Display how many members joined the scheme including parent [Link] the
} Total commission gained by each members in the scheme. The fixed amount for joining
if(j>0) the scheme is Rs.5000 on which commission will be generated
{ SchemeAmount = 5000
atepeanut =(float) (p/j);
p=p%j; Example 1: When there are more than one child members
} Input : (Do not give input [Link] values as follows. )
n=n-atebanana-atepeanut; Amit //Enter parent Member as this
if((m!=0) || (p!=0)) Y //Enter Y if Parent member has child members otherwise
n=n-1; enter N
cout<<"Number of Monkeys left on the Tree: "<<n; Rajesh,Virat //Enter names of child members of Amit in comma separated
} Output:(Final Output must be in format given below.)
return 0; TOTAL MEMBERS:3
} COMISSION DETAILS
Amit: 1000 INR
Rajesh :250 INR
Virat: 250 INR

Example 2: When there is only one child member in the hierarchy


Input :
Amit
Y
Rajesh
Output:
Total Members: 2
Comission Details
Amit: 500 INR
Rajesh: 250 INR

Ans =

#include <iostream>
#include <vector>
using namespace std;

int main() {
string par;
cin >> par;
string x;
cin >> x;
if (x == "N") { 15.> FULLY AUTOMATIC VENDING MACHINE – dispenses your cuppa on just press of
cout << "TOTAL MEMBERS: 1" << endl; button. A vending machine can serve range of products as follows:
cout << "COMMISSION DETAILS" << endl;
cout << par << ": 250 INR" << endl; Coffee
} else {
string child; Espresso Coffee
cin >> child; Cappuccino Coffee
vector<string> v; // Specify the template type as string for vector v Latte Coffee
string temp = ""; Tea
for (int i = 0; i < [Link](); i++) {
if (child[i] == ',') { Plain Tea
v.push_back(temp); Assam Tea
temp = ""; Ginger Tea
} else if (child[i] != ' ') Cardamom Tea
temp += child[i]; Masala Tea
} Lemon Tea
v.push_back(temp); Green Tea
cout << "TOTAL MEMBERS: " << [Link]() + 1 << endl; Organic Darjeeling Tea
cout << "COMMISSION DETAILS" << endl; Soups
cout << par << ": " << [Link]() * 500 << " INR" << endl;
for (auto a : v) { Hot and Sour Soup
cout << a << ": 250 INR" << endl; Veg Corn Soup
} Tomato Soup
} Spicy Tomato Soup
return 0; Beverages
}
Hot Chocolate Drink
Badam Drink
Badam-Pista Drink
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!
16.> A doctor has a clinic where he serves his patients. The doctor’s consultation
Ans = 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
#include <bits/stdc++.h> 40, fees is 400 INR. If patient’s age is above 40, fees is 300 INR. Write a code to
using namespace std; calculate earnings in a day for which one array/List of values representing age of
patients visited on that day is passed as input.
int main() Note:
{
string c[3]={"Espresso Coffee","Cappuccino Coffee","Latte Coffee"}; Age should not be zero or less than zero or above 120
Doctor consults a maximum of 20 patients a day
string t[8]={"Plain Tea","Assam Tea","Ginger Tea","Cardamom Tea","Masala Enter age value (press Enter without a value to stop):
Tea","Lemon Tea","Green Tea","Organic Darjeeling Tea"}; Example 1:
Input
string s[4]={"Hot and Sour Soup","Veg Corn Soup","Tomato Soup","Spicy Tomato 20
Soup"}; 30
40
string b[3]={"Hot Chocolate Drink","Badam Drink","Badam-Pista Drink"}; 50
2
char ch; 3
int n; 14
Output
string res = ""; Total Income 2000 INR
Note: Input and Output Format should be same as given in the above example.
cin>>ch>>n; For any wrong input display INVALID INPUT
Output Format
if(ch=='c' and n <= 3) Total Income 2100 INR
res = c[n-1];

else if(ch=='t' and n <= 8)


res = t[n-1]; Ans =

else if(ch=='s' and n <= 4) #include <bits/stdc++.h>


res = s[n-1]; using namespace std;

else if(ch=='b' and n <= 3) int main()


res = b[n-1]; {
int x, count = 0, flag = 0, fee_sum = 0;
else res = "Invalid Input";
while (cin >> x)
if(res != "Invalid Input" ) {
cout<<"Welcome to CCD!<<endl<<Enjoy your "<<res;
if (x <= 0 and x > 120)
else cout<<res; {
flag = 1;
return 0; break;
} }

count++;

if (x < 17)
fee_sum += 200; 17.> To check whether a year is leap or not
Step 1:
else if (x >= 17 and x <= 40)
fee_sum += 400; We first divide the year by 4.
If it is not divisible by 4 then it is not a leap year.
else If it is divisible by 4 leaving remainder 0
fee_sum += 300; Step 2:
}
We divide the year by 100
if (count > 20 and flag != 1) If it is not divisible by 100 then it is a leap year.
cout << "INVALID INPUT"; If it is divisible by 100 leaving remainder 0
Step 3:
else
cout << "Total income : " << fee_sum << " INR"; We divide the year by 400
return 0; If it is not divisible by 400 then it is a leap year.
} If it is divisible by 400 leaving remainder 0
Then it is a leap year

Ans =

#include <iostream>
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;
}
18.>Prime Numbers with a Twist cout << n << " is not a prime number.\n";
Ques. 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 return 0;
or not? }

Whether the number is positive or not, if it is negative then print the message
“please enter the positive number”
It is positive then call the function prime and check whether the take positive
number is prime or not.

Ans =

#include <iostream>
using namespace std;

bool check(int n) {
if (n < 0) {
cout << "Please enter a positive number.\n";
return false;
}
return true;
}

bool prime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}

int main() {
int n;
cout << "Enter a number: ";
cin >> n;

if (!check(n)) {
return 0;
}

if (prime(n)) {
cout << n << " is a prime number.\n";
} else {
19.> Find the 15th term of the series? 30.> Question. Find the nth term of the series.
0,0,7,6,14,12,21,18, 28 1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243,64, 729, 128, 2187 ….
Explanation : This series is a mixture of 2 series – all the odd terms in this series form a
In this series the odd term is increment of 7 {0, 7, 14, 21, 28, 35 – – – – – – } geometric series and all the even terms form yet another geometric series. Write a
And even term is a increment of 6 {0, 6, 12, 18, 24, 30 – – – – – – } program to find the Nth term in the series.

The value N in a positive integer that should be read from STDIN.


Ans = The Nth term that is calculated by the program should be written to STDOUT.
Other than value of n th term,no other character / string or message should be
#include <iostream> written to STDOUT.
using namespace std; For example , if N=16, the 16th term in the series is 2187, so only value 2187
int main() should be printed to STDOUT.
{ You can assume that N will not exceed 30.
// initialising variables
int n, d; Link to this Question
cout << "Enter the position: "; Test Case 1
// user input Input- 16
cin >> n; Expected Output – 2187
// logic to find nth element of the series
if (n == 1 || n == 2) Test Case 2
{ Input- 13
cout << 0; Expected Output – 64
return 0; (TCS Ninja – Dec 2018 Slot 2)
}
else if (n % 2 == 0) Explanation
{ 1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243,64, 729, 128, 2187 can represented as :
n = n / 2; 2(0), 3(0),2(1), 3(1),2(2), 3(2),2(3), 3(3),2(4), 3(4),2(5), 3(5),2(6), 3(6) ….
d = 6; There are two consecutive sub GP’s at even and odd positions
}
else (GP-1) At Odd Positions (Powers of 2) – 1, 2, 4, 8, 16, 32, 64, 128
{ (GP-2) At Even Positions (Powers of 3) – 1, 3, 9, 27, 81, 243, 729, 2187
n = n / 2 + 1; Clearly, for calculating Nth position value
d = 7;
} If N is Even, Find (N/2) position in sub GP – 2
// logic ends here If N is Odd, Find (N/2 + 1) position in sub GP – 1
// printing output
cout << (n - 1) * d;
return 0;
} Ans 1.=

#include<iostream>
#include<math.h>
using namespace std;
int three(int n)
{
int x;
x = pow(3,n-1); //n-1 because powers start from 0 not 1
cout<< x;
}
int two(int n) {
{ n = n / 2 - 1;
int x; r = 3;
x = pow(2,n-1); //n-1 because powers start from 0 not 1 }
cout<< x; else
} {
n = n / 2;
int main() r = 2;
{ }
int n; // logic ends here
cin >> n; // printing output
cout << (int)(pow(r, n));
//Checking of the nth term will be at even position or odd position return 0;
}
if(n%2==0) //Even positions are powers of 3
{

three(n/2); //nth position(if even) will be at n/2 position for sub


GP-2
}
else //Odd positions are powers of 2
{

two(n/2 + 1); //nth position(if odd) will be at (n/2 + 1) position for


sub GP-1
}
return 0;
}

Ans 2.=

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
// initialising variables
int n, r, term;
cout << "Enter the position: ";
// user input
cin >> n;
// logic to find nth element of the series
if (n == 1 || n == 2)
{
cout << 1;
return 0;
}
else if (n % 2 == 0)
21.> Consider the below series : return 0;
}
0, 0, 2, 1, 4, 2, 6, 3, 8, 4, 10, 5, 12, 6, 14, 7, 16, 8

This series is a mixture of 2 series all the odd terms in this series form even
numbers in ascending order and every even terms is derived from the previous term Ans 2.=
using the formula (x/2)
Write a program to find the nth term in this series. #include <iostream>
The value n in a positive integer that should be read from STDIN the nth term that using namespace std;
is calculated by the program should be written to STDOUT. Other than the value of int main()
the nth term no other characters /strings or message should be written to STDOUT. {
int n;
For example if n=10,the 10 th term in the series is to be derived from the 9th term cin >> n;
in the series. The 9th term is 8 so the 10th term is (8/2)=4. Only the value 4
should be printed to STDOUT. You can assume that the n will not exceed 20,000. if (n % 2 == 1)
{
int a = 1;
int r = 2;
Ans 1.= int term_in_series = (n + 1) / 2;
int res = 2 * (term_in_series - 1);
#include<bits/stdc++.h> cout << res;
using namespace std; }
int main()
{ else
int i, n, a = 0, b = 0; {
cout << "enter number : "; int a = 1;
cin >> n; int r = 3;
int term_in_series = n / 2;
for (i = 1; i <= n; i++) int res = term_in_series - 1;
{ cout << res;
if (i % 2 != 0) }
{
if (i > 1) return 0;
a = a + 2; }
}
else
{
b = a / 2;
}
}

if (n % 2 != 0)
{
cout << a;
}
else
{
cout << b;
}
22.> The program will recieve 3 English words inputs from STDIN 'u')
{
These three words will be read one at a time, in three separate line a[i] = '%';
The first word should be changed like all vowels should be replaced by % }
The second word should be changed like all consonants should be replaced by # if (a[i] == 'A' || a[i] == 'E' || a[i] == 'I' || a[i] == 'O' || a[i] ==
The third word should be changed like all char should be converted to upper case 'U')
Then concatenate the three words and print them {
Other than these concatenated word, no other characters/string should or message a[i] = '%';
should be written to STDOUT }
}
For example if you print how are you then output should be h%wa#eYOU. for (j = 0; j < y; j++)
You can assume that input of each word will not exceed more than 5 chars {
if (b[j] == 'b' || b[j] == 'c' || b[j] == 'd' || b[j] == 'f' || b[j] == 'g'
Test Cases || b[j] == 'h' || b[j] == 'j' || b[j] == 'k' || b[j] == 'l' || b[j] == 'm' || b[j]
Case 1 == 'n' || b[j] == 'p' || b[j] == 'q' || b[j] == 'r' || b[j] == 's' || b[j] == 't'
Input || b[j] == 'v' || b[j] == 'w' || b[j] == 'x' || b[j] == 'y' || b[j] == 'z')
{
how b[j] = '#';
are }
you if (b[j] == 'B' || b[j] == 'C' || b[j] == 'D' || b[j] == 'F' || b[j] == 'G'
Expected Output : h*wa@eYOU || b[j] == 'H' || b[j] == 'J' || b[j] == 'K' || b[j] == 'L' || b[j] == 'M' || b[j]
== 'N' || b[j] == 'P' || b[j] == 'Q' || b[j] == 'R' || b[j] == 'S' || b[j] == 'T'
Case 2 || b[j] == 'V' || b[j] == 'W' || b[j] == 'X' || b[j] == 'Y' || b[j] == 'Z')
Input {

how b[j] = '#';


999 }
you }
Expected Output : h*w999YOU z = 0;
while (c[z] != '\0')
{
if (c[z] >= 'a' && c[z] <= 'z')
Ans = {
c[z] = c[z] - 32;
#include<bits/stdc++.h> }
#include <math.h> z++;
using namespace std; }
int main() cout << a << b << c;
{
char a[10], b[10], c[10]; return 0;
int i, j; }
int x, y, z;
cin >> a;
cin >> b;
cin >> c;
x = strlen(a);
y = strlen(b);
for (i = 0; i < x; i++)
{
if (a[i] == 'a' || a[i] == 'e' || a[i] == 'i' || a[i] == 'o' || a[i] ==
23.> Addition of two numbers a Twist 26.> He first turns and travels 10 units of distance
Using a method, pass two variables and find the sum of two numbers. His second turn is upward for 20 units
Test case: Third turn is to the left for 30 units
Number 1 – 20 Fourth turn is the downward for 40 units
Number 2 – 20.38 Fifth turn is to the right(again) for 50 units
Sum = 40.38 … And thus he travels, every time increasing the travel distance by 10 units.

There were a total of 4 test cases. Once you compile 3 of them will be shown to you Test Cases
and 1 will be a hidden one. You have to display error message if numbers are not Case 1
numeric. Input : 3
Expected Output :-20 20
Case 2
Ans = Input: 4
Expected Output: -20 -20
#include<bits/stdc++.h> Case 3
using namespace std; Input : 5
Expected Output : 30 -20
float sum(int a, float b) Case 4
{ Input : 7
return (float)(a+b); Expected Output : 90 -20
}
int main()
{
int a; Ans 1.=
float b;
cout<<"Enter two numbers"; #include <iostream>
cin>>a; using namespace std;
cin>>b;
cout<<"Sum of "<<a<<" and "<<b<<" is "<<sum(a,b); int main() {
return 0; int n;
} cin >> n;

char c = 'R';
Output:- int x = 0, y = 0;
int distance = 10;
Enter two numbers14
14.50 while (n) {
Sum of 14 and 14.5 is 28.5 if (c == 'R') {
x = x + distance;
c = 'U';
distance = distance + 10;
} else if (c == 'U') {
y = y + distance;
c = 'L';
distance = distance + 10;
} else if (c == 'L') {
x = x - distance;
c = 'D';
distance = distance + 10;
} else if (c == 'D') {
y = y - distance; c = 'D';
c = 'A'; distance = distance + 10;
distance = distance + 10; break;
} else if (c == 'A') {
x = x + distance; case 'D':
c = 'R'; y = y - distance;
distance = distance + 10; c = 'A';
} distance = distance + 10;
break;
n--;
} case 'A':
x = x + distance;
cout << x << " " << y << endl; c = 'R';
return 0; distance = distance + 10;
} break;
}
n--;
}

Ans 2.= cout << x << " " << y <<endl;


return 0;
#include <iostream> }
using namespace std;
int main()
{
int n;
cin >> 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;
25.> Sweet Seventeen Problem Statement
Given a maximum of four digit to the base 17 (10 – A, 11 – B, 12 – C, 13 – D … 16 – val = hex[i] - 97 + 10;
G} as input, output its decimal value. }
else if(hex[i]>='A'&& hex[i]<='G'){
Test Cases
Case 1 //similarly, 65 to 71 are values of A - G
Input – 1A val = hex[i] - 65 + 10;
Expected Output – 27 }
Case 2
Input – 23GF decimal = decimal + val * pow(17,len);
Expected Output – 10980 len--;
}

Ans = cout<< decimal;

#include <iostream> return 0;


#include <math.h> }
#include <string.h>

using namespace std;


int main(){

char hex[17];
long long decimal, place;

int i = 0, val, len;


decimal = 0;
place = 1;

cin>> hex;

len = strlen(hex);
len--;

for(i = 0;hex[i]!='\0';i++)
{
if(hex[i]>='0'&& hex[i]<='9'){

//48 to 57 are ascii values of 0 - 9


//say value is 8 its ascii will be 56
//val = hex[i] - 48 => 56 - 48 => val = 8

val = hex[i] - 48;


}
else if(hex[i]>='a'&& hex[i]<='g'){

//97 to 103 are ascii values of a - g


//say value is g its ascii will be 103
//val = hex[i] - 97 + 10 => 103 - 97 + 10=> val = 16
//10 is added as g value is 16 not 6 or a value is 10 not 0
26.> Oddly Even Problem Statement n--;
Given a maximum of 100 digit numbers as input, find the difference between the sum i=0;
of odd and even position digits }
}
Test Cases cout<< abs(a-b); //print the difference of odd and even
Case 1
Input: 4567 return 0;
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
Ans 2.=
Case 2 Solution
Input: 5476 (When using long long as input)
Expected Output: 2
Case 3 #include<iostream>
Input: 9834698765123 #include<string.h>
Expected Output: 1 #include <stdlib.h>
Given a maximum of 100 digit numbers as input
using namespace std;

Ans = int main()


Solution {
(When using Strings as input) int odd = 0,even = 0,i = 0, n,diff;
long long num;
#include <iostream> cin>>num; //get the input up to 100 digit
#include <string.h>
#include <stdlib.h> while(num != 0){
if(i%2==0){
using namespace std; even = even + num%10;
num = num/10;
int main() i++;
{ }
int a = 0,b = 0,i = 0, n; else{
char num[100]; odd = odd + num%10;
num = num/10;
cout<< "Enter the number:"; i++;
cin>> num; //get the input up to 100 digit }
n = strlen(num);
while(n>0) }
{
if(i==0) //add even digits when no of digit is even and vise versa cout<< abs(odd - even);
{
a+=num[n-1]-48; return 0;
n--; }
i=1;
}
else //add odd digits when no of digit is even and vice versa
{
b+=num[n-1]-48;
27.> 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

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

Ans =

#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;
28.> Consider the below series: {
1, 2, 1, 3, 2, 5, 3, 7, 5, 11, 8, 13, 13, 17….. //number is not prime
flag = 1;
This series is a mixture of 2 series fail the odd terms in this series form a break;
Fibonacci series and all the even terms are the prime numbers in ascending order }
Write a program to find the Nth term in this series }
//is prime
The value N in a positive integer that should be read from mm. The Nth term that is if (flag == 0){
calculated by the program should be written to STDOUT Otherthan the value of Nth //if found the nth prime number
term , no other characters / string or message should be written to STDOUT. if(++count == n)
For example, when N:14, the 14th term in the series is 17 So only the value 17 {
should be printed to STDOUT. cout<< i;
break;
}
}
Ans = }
}
#include<iostream> int main(){
#define MAX 99999 int n;
using namespace std; cin >> n;

void fibonacci(int n) /*if n is odd


{ nth number in main series will be found at (n/2 + 1) position
/* Variable initialization */ in fibonacci sub series
int a = 0, b = 1, next; else
//the below code is for fibonacci series till nth position if n is even then it will be found in (n/2) position in prime sub series */
for (int i = 1; i<=n; i++)
{ if(n%2 == 1)
next = a + b; fibonacci (n/2 + 1);
a = b; else
b = next; prime(n/2);
}
//will print a not b or next as they are stored to calculate next and next to return 0;
next term }
cout<< a;
}

void prime(int n)
{
int i, j, flag, count =0;
//as prime numbers in given question start from 2
for (i=2; i<=MAX; i++)
{
flag = 0;
//to check if divisible apart from 1 & itself
//loop starts from 2 to ignore divisibilty by 1 & ends before the number
itself
for (j=2; j<i; j++)
{
if(i%j == 0)

You might also like