TCS Ninja coding questions answers 2022 is available here. TCS Ninja coding questions paper with solutions is very important for TCS ninja exam. Also, you will find TCS ninja coding questions with solved papers. On PrepInsta you will find the Accurate TCS Ninja coding exam Pattern 2022.
Mike has arranged a small party for the inauguration of his new startup. He has invited all of his fellow employees who are N in number. These employees are indexed with an array starting from 1 to N. In this startup, everyone knows each other’s salary. We will represent salary by an integer value. Mike has to arrange tables, where he will accommodate everyone. But he is a little thrifty in that, he wants to adjust everyone in as few tables as he can. Tables of various seating are available. Let’s say the cost of renting each table is K. All the employees have to seat in the order of the index. The only problem is that the employees with the same salary can get into arguments which can ruin the party. Mike came across the term inefficiency of arrangement, which can be defined as the sum of the cost of tables + the total number of people getting into arguments. Given the number of employees, N, and their salaries in array a[ ], he wants to find the optimal inefficiency, i.e., the smallest possible value for the inefficiency of arranging the N employees.
Let’s understand it with an example. Number of employees invited N = 5 A a = {5 1 3 3 3} K = 1
Now let’s check all the combinations and how in-efficient is all of them.
When we make 1st, 2nd, and 3rd employee on table-1 and 4th and 5th on table-2 Cost of 2 tables = 2*1 Number of people getting into arguments = 2 (two 3’s: 4th and 5th employee) Total = 2 + 2 = 4
When we make 1st, 2nd, 3rd, and 4th employees on table-1 and 5th on table-2 Cost of 2 tables = 2*1 Number of people getting into arguments = 2 (two 3’s: 4th and 5th employee) Total = 2 + 2 = 4
When we make all of them sit at 1 table, then inefficiency will be Cost of 1 table = 1 Number of people getting into arguments = 3 (all 3’s: 3rd, 4th and 5th employee) Total = 1 + 3 = 4
When we make 1st, 2nd and 3rd employee on table-1 and 4th on table-2 and 5th on table-3 Cost of 3 tables = 3*1 Number of people getting into arguments = 0 (all 3’s are. sitting at different tables) Total = 3 + 0 = 3
Hence the optimal in-efficiency is 3. So, the output will be 3.
Example 1:
Input: 5 1 -> Input Integer, N and K {5, 1, 3, 3, 3) Input Integer, array elements a[i].
Output: 3 -> Output
Explanation: Below is the seating for each case: Case 1: Table 1: 1st, 2nd, and 3rd Table 2: 4th and 5th Number of people getting into arguments: 2 Total in-efficiency: 2*1 + 2 = 4 Case 2: Table 1: 1st, 2nd, 3rd, and 4th Table 2: 5th Number of people getting into arguments: 2 Total in-efficiency: 2*1 + 2 = 4 Case 3: Table 1: 1st, 2nd, 3rd, 4th, and 5th Number of people getting into arguments: 3 Total in-efficiency: 1*1 + 3 = 4 Case 4: Table 1: 1st, 2nd, and 3rd Table 2: 4th Table 3: 5th Number of people getting into arguments: 0 Total in-efficiency: 3*1 + 0 = 3 Choosing the minimum which is 3. So, the answer is 3.
Example 2:
Input: 5 14 -> Input Integer, N and K. {1, 4, 2, 4, 4} -> Input Integer, array elements a[i].
Output: 17 -> Output
Explanation: Below is the seating for each case: Case 1: Table 1: 1st, 2nd, and 3rd Table 2: 4th and 5th Number of people getting into arguments: 2 Total in-efficiency: 2*14 + 2 = 30 Case 2: Table 1: 1st, 2nd, 3rd, and 4th Table 2: 5th Number of people getting into arguments: 2 Total in-efficiency: 2*14 + 2 = 30 Case 3: Table 1: 1st, 2nd, 3rd, 4th, and 5th Number of people getting into arguments: 3 Total in-efficiency: 1*14+3 = 17 Case 4: Table 1: 1st, 2nd, and 3rd Table 2: 4th Table 3: 5th Number of people getting into arguments: 3 Total in-efficiency: 3*14+ 0 = 42 Chose the minimum which is 17. So, the answer is 17.
n, k = map(int, input().split())
arr = list(map(int, input().split()))
print(min((n - len(set(arr)) + 1) * k, k + (n - len(set(arr)) + 1)))
TCS Coding Question Day 1 Slot 1 – Question 2
Jack and Jill are playing a string game. Jack has given Jill two strings A and B. Jill has to derive a string C from A, by deleting elements from string A, such that string C does not contain any element of string B. Jill needs help to do this task. She wants a program to do this as she is lazy. Given strings A and B as input, give string C as Output.
Example 1:
Input: tiger -> input string A ti -> input string B
Output: ger -> Output string C
Explanation: After removing “t” and “i” from “tiger”, we are left with “ger”. So, the answer is “ger”.
Example 2:
Input: processed -> input string A esd -> input string B
Output: proc -> Output string C
Explanation: After removing “e” “s” and “d” from “processed”, we are left with “proc”. So, the answer is “proc”.
Example 3:
Input: talent -> input string A tens -> input string B
Output: al -> Output string C
Explanation: After removing “t” “e” and “n” from “talent”, we are left with “al”. So, the answer is “al”.
a = input()
b = input()
c = ""
for i in a:
if i in b:
continue
else:
c += i
print(c)
TCS Coding Question Day 1 Slot 2 – Question 1
Mahesh and Suresh are playing a new game “Checkers“. This is a very simple game but becomes challenging when more expert players are playing. Below is the description of the game and rules: The game is played by 2 players. This game consists of an N*M matrix. Each of the cells is background lit by lights. And these cells are either Green or Black. The green and black cells are randomly lit and will be represented with 1’s and 0’s respectively. Green cells are the cells that need to be captured. Black cells cannot be captured. Everyone is in the race to capture the maximum number of cells possible. In a single chance, a player can capture all those adjacent cells which share an edge. Once there is no adjacent edge the chance breaks and the next player will play. Mahesh always starts the game and Suresh is second. Both players are playing optimally, find out how many cells Suresh captures.
Input: N and M, size of the matrix A[i][j] for all 1<=i<=N and 1<=j<=M
Let us try to understand it with an example
Consider the matrix below N = 4 M = 4 A = 1001 0110 0110 1001
If Mahesh plays first, he will try to capture most of the 1’s, he will capture A[2][2], A[2][3], A[3][2], and A[3][3]. Now there are no adjacent cells left. So, the chance will be given to Suresh. Now Suresh’s turn. He can capture either A[1][1] or A[4][1] or A[4][7] or A[4][4]. He will capture any one cell, and as there is no adjacent deft, the chance will now be given to Mahesh. The game proceeds and then again Suresh’s turn will come, and he will again be able to choose only 1 cell finally Mahesh will end the game by choosing the final cell. Like this Mahesh has captured 6 cells and Suresh has captured only 2 cells. Hence 2 is the answer.
Example 1:
Input: 2 2 -> Input integer, N, M 1 1 -> Input integer, A[i] 1 1 -> Input integer, A[N]
Output: 0 -> Output
Explanation: In the above scenario, it is very clear that if Mahesh plays first, he will capture all the cells as all the cells are adjacent to each other. There will be nothing left for Suresh. Hence the cells captured by Suresh will be 0. Hence the answer is 0.
Explanation: If Mahesh plays first, he will try to cover most of the 1’s, he will cover A[2][2], A[2][3], A[3][2], and A[3][3]. Now there are no adjacent cells left. So, the chance will be given to Suresh. Now Suresh’s turn. He can capture either of A[1][1] or A[4][1] or A[4][1] or A[4][4]. He will capture any one cell, and as there is no adjacent left, the chance will now be given to Mahesh. The game proceeds and then again Suresh’s turn will come, and he will again be able to choose only 1 cell, and finally, Mahesh will end the game by choosing the final cell. Like this Mahesh has captured 6 cells and Suresh has captured only 2 cells. Hence 2 is the answer.
n, m = map(int, input().split())
a = []
for i in range(n):
a.append(list(map(int, input().split())))
ans = 0
for i in range(n-2):
for j in range(m):
if a[i][j] == a[i + 1][j]:
continue
elif a[i + 1][j] == 1 and a[i + 2][j] == 1:
ans += 1
print(ans)
TCS Coding Question Day 1 Slot 2 – Question 2
Joe was reading an interesting novel when all of a sudden, his 5-year-old son came to him and started asking a few questions about functions. He tried making him understand various functions, but his son didn’t get find it interesting. Then he created his function Absent number function A(S) According to this function, there is always the smallest positive integer number in a sequence that is not available. In simple words, if you sort the given sequence, then the smallest integer number (other than 0) which is not present in the sequence is the Absent number. Consider a sequence S= [1, 2, 3], then B(S)=4. The minimum value greater than 0 which is not present here in the sequence is 4. Now his son found it interesting, so Joe extended this logic to sub-sequence. If there is a given sequence S, you have to find the Absent Number for each sub-sequence and then sum it up. If the answer is large, print the result modulo, 109 +7.
Let say there exist a sequence with N = 3, and sequence S = [1, 2, 1] Below are the various sub-sequences of it,
Total sum of all B(S) = 1+2+1+2+3+3+2+3 = 17. Hence the answer is 17.
Example 1:
Input: 2 -> input Integer, N 1 1 -> input Integer, S
Output: 7 -> Output
Explanation: In the above scenario below are the various sub-sequence and their respective functions of it: [ ] : B(l) = 1 [1]: B([1])= 2 [1]: B([1]) = 2 [1,1]: B([1,1]) = 2 Total sum of all B(S) = 1+2+2+2 = 7 Hence the answer is 7.
Example 2:
Input: 3 -> Input integer, N 1 2 1 -> Input integer, S
Output: 17->Output
Explanation: In the above scenario below are the various sub-sequences and their respective functions of it. [ ] : B([ ]) = 1 [1] : B([1]) = 2 [2] : B([2]) =1 [1] : B([1]) = 2 [1, 2] : B([1, 2]) = 3 [2, 1] : B([2, 1]) = 3 [1, 1] : B([1, 1]) = 2 [1, 2, 1] : B([1, 2, 1]) = 3 Total sum of all B(S) = 1 + 2 + 1 + 2 + 3 + 3 + 2 + 3 = 17. Hence the answer is 17.
from itertools import combinations
def fun(n, s):
ans = 1
comb = []
for i in range(n):
comb += combinations(s, i + 1)
for i in comb:
a = minMis(list(i))
ans += a
return ans
def minMis(arr):
for i in range(len(arr)):
if i + 1 not in arr:
return i + 1
return len(arr) + 1
n = int(input())
s = list(map(int, input().split()))
print(fun(n, s))
TCS Coding Question Day 2 Slot 1 – Question 1
James has a sequence of N numbers. There is also an integer X which is a random number from other sources. He is allowed to perform a specific operation on this sequence X number of times. Below is the operation:
Pick exactly one element from the sequence and multiply it with -1.
Your task is to find out the number of different sequences which can be formed by performing the above operation. If the answer is large, print the result modulo 109 +7.
Let us try to understand it with an example,
N = 3 X = 2 S = [1, 2, 3]
There are 2 ways in which this operation can be performed.
Way 1: Either -1 should be multiplied to the same element 2 times, OR
Way 2: -1. Should be multiplied by two different elements once each.
Way 1: If we multiply -1, to each element 2 times. It will become +1 (-1 *-1). We will get the same sequence for each element:
Multiply -1, 2 times to S[1] : [1, 2, 3].
Multiply -1, 2 times to S[2] : [1, 2, 3].
Multiply -1, 2 times to S[3] : [1, 2, 3].
So, the unique sequence is just 1 which is [1, 2, 3].
Way 2: If we multiply -1, by two different elements just 1 time each. We get:
Multiply -1 to S[1] & S[2] : [-1, -2, 3].
Multiply -1 to S[2] & S[3] : [1, -2, -3].
Multiply -1 to S[1] & S[3] : [-1, 2, -3].
Hence, we get a total of 3 different sequences from Way 2. Total 1 + 3 = 4 different sequences.
Hence the answer is 4.000
Example 1:
Input: 3 1 -> Input integer, N, X {1, 2, 1} -> Input integer, S
Output: 3 -> Output
Explanation: In the given scenario, we have X =1. Hence, we can have this multiplication of -1 only once. So, if we multiply -1, by different elements just 1 time. We get:
Multiply -1 to S[1] & S[2] : [-1, -2, 1].
Multiply -1 to S[2] & S[3] : [1, -2, -1].
Multiply -1 to S[1] & S[3] : [-1, 2, -1].
Hence, we get a total of 3 different sequences. So, the answer is 3.
Example 2:
Input: 3 2 -> Input integer, N, X {1, 2, 3} -> Input integer, S
Output: 4 -> Output
Explanation: There are 2 ways in which this operation can be performed
Way 1: Either – 1 should be multiplied to the same element 2 times, OR
Way 2: -1 should be multiplied by different elements once.
As shown in the above Demo example, there will be a total of 4 different sequences which can be achieved from this. Hence the answer is 4.
#include<bits/stdc++.h>
using namespace std;
int ct(int a[], int n)
{
unordered_set s;
int res = 0;
for (int i = 0; i < n; i++)
{
if (s.find(a[i]) == s.end())
{
s.insert(a[i]);
res++;
}
}
return res;
}
int factorial(int n)
{
if(n == 0)
return 1;
int factorial = 1;
for (int i = 2; i <= n; i++)
factorial = factorial * i;
return factorial;
}
int total_combination(int n, int x)
{
return factorial(n) / (factorial(x) * factorial(n - x));
}
int main()
{
int n, x, ans, cnt = 0;
cin >> n >> x;
int a[n];
for(int i =0 ; i < n; i++)
{
cin >> a[i];
}
int k = ct(a,n);
if(x%2 == 0)
{
ans = 1;
ans += total_combination(k,x);
}
else
{
ans = k-1;
ans += total_combination(k,x);
}
cout << ans << "\n";
return 0;
}
n, x = map(int, input().split())
arr = list(map(int, input().split()))
ans = 0
for i in range(n - 1):
for j in range(i + 1, n):
ans += 1
if x % 2 == 0:
ans += 1
print(ans)
TCS Coding Question Day 2 Slot 1 – Question 2
Two parallel roads separated by a river are connected from cities A and B to an outer ring road. Both roads have a high flow of traffic throughout the day. People who want to travel from city A to city B or vice versa have to pass through the ring road which is a huge waste of time and money. To ease the traffic and also to make it convenient for commuters to travel from city A to city B and vice versa, the construction of a bridge over the river is planned.
The surveillance team submitted a report stating the bridge should be constructed in the following manner:
The ground or soil is stronger at certain points on the road favorable for the construction of the bridge.
The strong ground positions are given from the starting point of each road. Say, the road of city A has strong ground at 1,4 meaning there is a strong ground at a distance of 1 unit, another strong ground point at a distance of 4 units from the starting point of the road of city A.
Collate the strong ground positions of both roads. Sort them in ascending order. Calculate the middle point or median of the combined strong ground positions. The bridge should be constructed from road A as per the middle point calculated. Given the number of strong positions on roads A and B(N1 and N2 respectively) and the strong ground positions on each road, the task here is to calculate the midpoint of the combined strong positions on both roads.
NOTE: When the strong positions are combined, the repeated positions on the different roads are dropped.
Example 1:
Input: 3 -> Value of N1 3 -> Value of N2 {3,5,2} -> a[ ], Elements a[0]to a[N1-1], where each input element is separated by new line {1,2,3} -> b[ ], Elements b[0]to b[N2-1), where each input element is separated by new line
Output: 2.5
Explanation: From the inputs given above: Number of strong ground positions on road A:3 Number of strong ground positions on road B:3 The positions of strong ground from the starting point of road A are at a distance of 3,5,2 The positions of strong ground from the starting point of road B are at a distance of 1,2,3 Combining the strong ground positions of both the roads and sorting them in ascending order 1, 2, 3, 5 The Middle points are 2 and 3 2+3 = 5 5/2 = 2.5 So, the middle point from where the bridge should be constructed is 2.5. Hence, the output is 2.5
Example 2:
Input: 2 -> Value of N1 3 -> Value of N2 {2,3} -> all, Elements a[O]to a[N1-1), where each input element is separated by new line {5,6,4} -> b[ ], Elements b[O]to b[N2-1], where each input element is separated by new line
Output: 4
Explanation: From the inputs given above: Number of strong ground positions on road A: 2 Number of strong ground positions on road B: 3 The positions of strong ground from the starting point of road A are at a distance of 2, 3 The positions of strong ground from the starting point of road B are at a distance of 5, 6, and 4 Combining the strong ground positions of both the roads and sorting them in ascending order: 2, 3, 4, 5, 6 > Middle point is 4 So, the middle point from where the bridge should be constructed is 4. Hence, the output is 4.
n1 = int(input())
n2 = int(input())
a = []
b = []
for i in range(n1):
a.append(int(input()))
for i in range(n2):
b.append(int(input()))
c = list(set(a + b))
c.sort()
l = len(c)
if l % 2 == 0:
print((c[l // 2] + c[(l // 2) - 1]) / 2)
else:
print(c[l // 2])
TCS Coding Question Day 2 Slot 2 – Question 1
A chocolate factory is packing chocolates into packets. The chocolate packets here represent an array arrt of N number of integer values. The task is to find the empty packets(0) of chocolate and push it to the end of the conveyor belt(array).
For Example:
N=7 and arr = [4,5,0,1.9,0,5,0].
There are 3 empty packets in the given set. These 3 empty packets represented as O should be pushed towards the end of the array
Example 1:
Input:
7 – Value of N
[4,5,0,1,0,0,5] – Element of arr[O] to arr[N-1],While input each element is separated by newline
Output:
4 5 1 9 5 0 0
Example 2:
Input:
6
— Value of N.
[6,0,1,8,0,2] – Element of arr[0] to arr[N-1], While input each element is separated by newline
#include <bits/stdc++.h> using namespace std; int main() { int n,j=0; cin>>n; int a[n]={0}; for(int i=0;i<n;i++) { cin>>a[j]; if(a[j]!=0) j++; } for(int i=0;i<n;i++) cout<<a[i]<<" "; }
Java
import java.util.*; class Solution { public static void main (String[]args) { Scanner sc = new Scanner (System.in); int n = sc.nextInt (); int arr[] = new int[n];
for(int i = 0; i < n; i++) arr[i] = sc.nextInt ();
int count = 0;
for(int i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; for(int i = count; i < n; i++) arr[i] = 0;
for (int i = 0; i < n; i++) System.out.print (arr[i] + " "); } }
Python
n=int(input()) j=0 L=[0 for i in range(n)] for i in range(n): a=int(input()) if a!=0: L[j]=a j+=1 for i in L: print(i,end=" ")
Joseph is learning digital logic subject which will be for his next semester. He usually tries to solve unit assignment problems before the lecture. Today he got one tricky question. The problem statement is “A positive integer has been given as an input. Convert decimal value to binary representation. Toggle all bits of it after the most significant bit including the most significant bit. Print the positive integer value after toggling all bits”.
Constraints :
1<=N<=100
Example 1:
Input :
10 -> Integer
Output :
5 -> result- Integer
Explanation:
Binary representation of 10 is 1010. After toggling the bits(1010), will get 0101 which represents “5”. Hence output will print “5”.
int main() { int n; cin>>n; int k=(1<<(int)floor(log2(n))+1)-1; cout<<(n^k); }
Java
import java.util.*; class Solution { public static void main (String[]args) { Scanner sc = new Scanner (System.in); int no = sc.nextInt (); String bin = "";
while (no != 0) { bin = (no & 1) + bin; no = no >> 1; } bin = bin.replaceAll ("1", "2"); bin = bin.replaceAll ("0", "1"); bin = bin.replaceAll ("2", "0");
int res = Integer.parseInt (bin, 2); System.out.println (res); } }
Python
import math n=int(input()) k=(1<<int(math.log2(n))+1)-1 print(n^k)
Airport security officials confiscated several items of the passengers at the security checkpoint. All the items have been dumped into a huge box (array). Each item possesses a certain amount of risk[0,1,2]. Here, the risk severity of the items represents an array[] of N number of integer values. The task here is to sort the items based on their levels of risk in the array. The risk values range from 0 to 2.
Example :
Input :
7 -> Value of N
[1,0,2,0,1,0,2]-> Element of arr[0] to arr[N-1], while input each element is separated by new line.
Output :
0 0 0 1 1 2 2 -> Element after sorting based on risk severity
Example 2:
input : 10 -> Value of N
[2,1,0,2,1,0,0,1,2,0] -> Element of arr[0] to arr[N-1], while input each element is separated by a new line.
Output :
0 0 0 0 1 1 1 2 2 2 ->Elements after sorting based on risk severity.
Explanation:
In the above example, the input is an array of size N consisting of only 0’s, 1’s, and 2s. The output is a sorted array from 0 to 2 based on risk severity.
Solution in Java: import java.util.*; class Solution { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) arr[i]=sc.nextInt();
Given N gold wires, each wire has a length associated with it. At a time, only two adjacent small wires are assembled at the end of a large wire and the cost of forming is the sum of their length. Find the minimum cost when all wires are assembled to form a single wire.
For Example:
Suppose, Arr[]={7,6,8,6,1,1,}
{7,6,8,6,1,1}-{7,6,8,6,2} , cost =2
{7,6,8,6,2}- {7,6,8,8}, cost = 8
{7,6,8,8} – {13,8,8}, cost=13
{13,8,8} -{13,16}, cost=16
{13, 16} – {29}, cost =29
2+8+13+16+29=68
Hence , the minimum cost to assemble all gold wires is 68.
Constraints
1<=N<=30
1<= Arr[i]<=100
Example 1:
Input
6 -> Value of N, represent size of Arr
7 -> Value of Arr[0], represent length of 1st wire
6 -> Value of Arr[1], represent length of 2nd wire
8 -> Value of Arr[2] , represent length of 3rd wire
6 -> Value of Arr[3], represent length of 4th wire
1 -> Value of Arr[4], represent length of 5th wire
1 -> Value of Arr[5], represent length of 6th wire
Output :
68
Example 2:
Input
4 -> Value of N, represents size of Arr
12 -> Value of Arr[0], represents length of 1st wire
2 -> Value of Arr[1], represent length of 2nd wire
2 -> Value of Arr[2], represent length of 3rd wire
5 -> Value of Arr[3], represent length of 4th wire
Given an array Arr[] of size T, contains binary digits, where
0 represents a biker running to the north.
1 represents a biker running to the south.
The task is to count crossing biker in such a way that each pair of crossing biker(N, S), where 0<=N<S<T, is passing when N is running to the north and S is running to the south.
Constraints:
0<=N<S<T
Example 1:
Input :
5 -> Number of elements i.e. T
0 -> Value of 1st element.
1 -> Value of 2nd element
0 -> Value of 3rd element.
1 -> Value of 4th element.
1 -> Value of 5th element
Output :
5
Explanation:
The 5 pairs are (Arr[0], Arr[1]), (Arr[0], Arr[3]), (Arr[0], Arr[4]), (Arr[2],Arr[3]) and (Arr[2], Arr[4]).
int main () { int n, a, sum = 0, c = 0; cin >> n; for (int i = 0; i < n; i++){ cin >> a; if (a) sum += c; else c++; } cout << sum; }
Java
import java.util.*; class Solution { public static void main (String[]args) { Scanner sc = new Scanner (System.in); int a, sum = 0, c = 0; int n = sc.nextInt (); for (int i = 0; i < n; i++) { a = sc.nextInt (); if (a != 0) sum += c; else c++; } System.out.println (sum); } }
System.out.println (sum); } }
Python
n = int (input ())
L =[]
sum = 0
c = 0
for _ in range (n):
a = (input ())
if a:
sum += c
else:
c += 1
print (sum)
Mr. Rao is relocating from place A to B. The moving truck has a maximum capacity C. There are ‘N’ items in the house where each item has a corresponding value (Vi) and weight(Wi). Mr. Rao has to carry only the most valuable items whose total weight does not exceed the capacity of truck. The task here is to find those items (single or combination of items) whose total value (v) will be the maximum and their corresponding weight(w) will not exceed truck capacity(c). Here,
N= No. of items
C= Maximum capacity of the truck, an integer value,
W[0 to N-1]- An array consisting weight of each item
V[0 to N-1] – An array consisting value of each item.
Example 1:
Input :
4 -> Value of N
80 -> Value of C
[10,45,60,90] -> Elements of array v[], where each element is separated by new line.
[15,20,30,40] -> Elements of array w[], where each element is separated by new line.
Output: 150
Explanation:
Value=10 weight=15
Value=45 weight = 20
Value = 60 weight=30
Value=90 weight=40
The subsets that can be formed from the array V[], their corresponding weight W[] and comparison with c=80
Value
Total Value
Weight
Total Weight
Valid (total weight(<C)
Invalid (total weight>C)
10+45
55
15+20
35
Valid
10+60
70
15+30
45
Valid
10+90
100
15+40
55
Valid
45+60
105
20+30
50
Valid
45+90
135
20+40
60
Valid
60+90
150
20+40
70
Valid
10+45+60
115
20+40
65
Valid
10+60+90
160
20+40
85
Invalid
10+45+90
145
20+40
75
Valid
From the above table, it is perceived that particularly for the valid items, maximum value=150 and their corresponding weight is 70. So the output should be 150.
The input format for testing
First Input – Accept value for N (positive integer number).
Second input : Accept value for C (Positive integer number),
Third input – Accept N number of positive integer number for array v[0…N-1], where each value is separated by a new line.
Fourth input – Accept N positive integer numbers for array [0….N-1], where each value is separated by a new line.
The output format for testing
The output should be a positive integer number (Check the output in Example 1)
#include<stdio.h>
#include<string.h>
int main(){
char str[16][10] = {"break", "case", "continue", "default", "defer", "else","for", "func", "goto", "if", "map", "range", "return", "struct", "type", "var"};
char input[20];
int flag = 0;
scanf("%s",input);
for(int i = 0; i<16;i++){
if(strcmp(input,str[i]) == 0){
flag = 1;
break;
}
}
if(flag==1){
printf("%s is a keyword",input);
}
else{
printf("%s is not a keyword",input);
}
return 0;
}
C++
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char str[16][10] = {"break", "case", "continue", "default", "defer", "else","for",
"func", "goto", "if", "map", "range", "return", "struct", "type", "var"};
char input[20];
int flag = 0;
cin >> input;
for(int i = 0; i<16;i++){
if(strcmp(input,str[i]) == 0){
flag = 1;
break;
}
}
if(flag==1){
cout << input << " is a keyword";
}
else{
cout << input << " is not a keyword";
}
return 0;
}
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")
Java
import java.util.Scanner;
public class Prep
{
public static voidmain(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");
}
}
}
//The above is code is contributed by Jonty Chakraborty (PrepInsta Placement Cell Student)
#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'){
//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
val = hex[i] - 97 + 10;
}
else if(hex[i]>='A'&& hex[i]<='G'){
//similarly, 65 to 71 are values of A - G
val = hex[i] - 65 + 10;
}
decimal = decimal + val * pow(17,len);
len--;
}
printf("%lld",decimal);
return 0;
}
C++
#include <iostream>
#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
val = hex[i] - 97 + 10;
}
else if(hex[i]>='A'&& hex[i]<='G'){
//similarly, 65 to 71 are values of A - G
val = hex[i] - 65 + 10;
}
decimal = decimal + val * pow(17,len);
len--;
}
cout<< decimal;
return 0;
}
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))
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);
}
}
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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int a = 0,b = 0,i = 0, n;
char num[100];
printf("Enter the number:");
scanf("%s",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
{
a+=num[n-1]-48;
n--;
i=1;
}
else //add odd digits when no of digit is even and vice versa
{
b+=num[n-1]-48;
n--;
i=0;
}
}
printf("%d",abs(a-b)); //print the difference of odd and evenreturn 0;
}
using namespace std;
int main()
{
int a = 0,b = 0,i = 0, n;
char num[100];
cout<< "Enter the number:";
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
{
a+=num[n-1]-48;
n--;
i=1;
}
else //add odd digits when no of digit is even and vice versa
{
b+=num[n-1]-48;
n--;
i=0;
}
}
cout<< abs(a-b); //print the difference of odd and evenreturn 0;
}
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))
# code contributed by Shubhanshu Arya PrepInsta Placement Cell Student
Java
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
String s=sin.nextLine();
long num = 0, num1 = 0;
num=num + s.charAt(0)-'0'; for(int i=1;i<s.length();i++)
{
if(i%2==0)
num = num + s.charAt(i)-'0';
else
num1 = num1 + s.charAt(i)-'0';
}
System.out.println(Math.abs(num-num1));
}
}
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
He first turns and travels 10 units of distance
His second turn is upward for 20 units
Third turn is to the left for 30 units
Fourth turn is the downward for 40 units
Fifth turn is to the right(again) for 50 units
… And thus he travels, every time increasing the travel distance by 10 units.
#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;
}
C++
#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;
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--;
}
cout << x << " " << y <<endl;
return 0;
}
Java
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int testCase = sc.nextInt();
getDistance(testCase);
}
public static void getDistance(int a) {
int distance = 10;
int x = 0;
int y = 0;
char ch = 'R';
while(a > 0)
{
switch(ch)
{
case'R':
x = x + distance;
ch = 'U';
distance = distance+10;
break;
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);
}
}
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)
printf("Enter a year to check if it is a leap year\n");
scanf("%d", &year);
if (year%400 == 0) // Exactly divisible by 400 e.g. 1600, 2000
printf("%d is a leap year.\n", year);
else if (year%100 == 0) // Exactly divisible by 100 and not by 400 e.g. 1900, 2100
printf("%d isn't a leap year.\n", year);
else if (year%4 == 0) // Exactly divisible by 4 and neither by 100 nor 400 e.g. 2016, 2020
printf("%d is a leap year.\n", year);
else// Not divisible by 4 or 100 or 400 e.g. 2017, 2018, 2019
printf("%d isn't a leap year.\n", year);
return 0 }
C++
#includeusingnamespace std;int main(){int year =2016;if(((year %4==0)&&(year %100!=0))||(year %400==0))
cout<<year<<" is a leap year";else
cout<<year<<" is not a leap year";return0;}
Output
2016 is a leap year
In the above program, if a year is divisible by 4 and not divisible by 100, then it is a leap year. Also, if a year is divisible by 400, it is a leap year.
This is demonstrated by the following code snippet.
if(((year %4==0)&&(year %100!=0))||(year %400==0))
cout<<year<<" is a leap year";else
cout<<year<<" is not a leap year";
The program to check if a year is leap year or not can also be written using nested if statements. This is given as follows −
Java
import java.util.Scanner;publicclassDemo{publicstaticvoid main(String[] args){int year;Scanner scan =newScanner(System.in);System.out.println("Enter any Year:");
year = scan.nextInt();
scan.close();boolean isLeap =false;if(year %4==0){if( year %100==0){if( year %400==0)
isLeap =true;else
isLeap =false;}else
isLeap =true;}else{
isLeap =false;}if(isLeap==true)System.out.println(year +" is a Leap Year.");elseSystem.out.println(year +" is not a Leap Year.");}}
Perl
# perl Script # leap year print "Enter Year: "; $year=; # condition to check for leap year if( (0 == $year % 4) && (0 != $year % 100) || (0 == $year % 400) ) { print "Leap year"; } else { print "Not a leap year"; }
Output
Enter Year: 2016 Leap year
Python
# Python Program to Check Leap Year using If Statement
year = int(input("Please Enter the Year Number you wish: "))
if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
print("%d is a Leap Year" %year)
else:
print("%d is Not the Leap Year" %year)
Program 6
Prime Number with a Twist
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 or not?
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; }
C++
#include using namespace std;
void enter(); void check(int); void prime(int);
int main() { enter(); return 0;
}
void check(int num) { if(num<0) { cout<<"invalid input enter value again"<<endl; enter(); } else { prime(num); } } void enter() { int num; cout<<"Enter number:"; cin>>num; check(num); }
void prime(int num) { int i,div=0; for(i=1;i<=num;i++) { if(num%i==0) { div++; } } if(div==2) { cout<<num<<" is a prime number"; } else { cout<<" is not a prime number"; } }
Java
/* Write a progam in java and check if a number which is entered is prime number or not. However if the number happens to be negative then we must ask the user to enter a positive number again*/
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"); } }
Program 7
Number Series Type 1
Ques. Find the 15th term of the series?
0,0,7,6,14,12,21,18, 28
Please add the answer in the comment section below.
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); }
C++
//C++ Program #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; }
Java
import java.util.Scanner;
public class Series{
public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n; n=sc.nextInt(); int arr[]=new int[n]; int i,k=0; int a=0,b=0; arr[0]=a; k++; arr[1]=b; k++; for(i=1;i<=n-2;i++) {
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]);
} }
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))
This series is a mixture of 2 series – all the odd terms in this series form a geometric series and all the even terms form yet another geometric series. Write a program to find the Nth term in the series.
The value N in a positive integer that should be read from STDIN.
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 written to STDOUT.
For example , if N=16, the 16th term in the series is 2187, so only value 2187 should be printed to STDOUT.
#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);
//Checking of the nth term will be at even position or odd position //Odd positions are powers of 2 //Even positions are powers of 3if(n%2==0)
{
//nth position(if even) will be at n/2 position for sub GP-2
three(n/2);
}
else
{
//nth position(if odd) will be at (n/2 + 1) position for sub GP-1
two(n/2 + 1);
}
return 0;
}
C++
#include<iostream>
#include<math.h>
using namespace std;
int three(int n)
{
int x;
//n-1 because powers start from 0 not 1
x = pow(3,n-1);
cout<< x;
}
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;
//Checking of the nth term will be at even position or odd position //Odd positions are powers of 2 //Even positions are powers of 3if(n%2==0)
{
//nth position(if even) will be at n/2 position for sub GP-2
three(n/2);
}
else
{
//nth position(if odd) will be at (n/2 + 1) position for sub GP-1
two(n/2 + 1);
}
return 0;
}
Java
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
int n = sin.nextInt();
System.out.println(n%2==0?(int)Math.pow(3,(n-1)/2):(int)Math.pow(2,(n-1)/2));
}
}
// we have used ternary operator above condition ? value_if_true : value_if_false
Python
num = int(input())
if(num%2==0):
num = num // 2
print(3**(num-1))
else:
num = num // 2 + 1
print(2**(num-1))
#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;
}
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;
}
Java
//Java program to find nth element of the series 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); } } }
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
This series is a mixture of 2 series fail the odd terms in this series form a 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
The value N in a positive integer that should be read from mm. The Nth term that is calculated by the program should be written to STDOUT Otherthan the value of Nth term , no other characters / string or message should be written to STDOUT.
For example, when N:14, the 14th term in the series is 17 So only the value 17 should be printed to STDOUT
1. Using a method, pass two variables and find the sum of two numbers.
Test case:
Number 1 – 20
Number 2 – 20.38
Sum = 40.38
There were a total of 4 test cases. Once you compile 3 of them will be shown to you and 1 will be a hidden one. You have to display error message if numbers are not numeric.
#include<stdio.h>
#include<string.h>
int main()
{
int x;float y;
scanf("%d%f",&x,&y);
if(isnan(x) || isnan(y))
{
printf("Error");
}
else
printf("%0.2f",(float)x+y);
return 0;
}
Java
import java.util.*;
public class sum
{
public static void main (String args[])
{
System.out.println("Enter the first number for sum");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
System.out.println("Enter the first number for sum");
int b = sc.nextInt();
sum s = new sum();
s.summ(a,b);
}
void summ(int a,int b)
{
int c = a+b;
System.out.println("The sum of two numbers is "+c);
}
}
// C program to calculate GCD of two numbers
#include <stdio.h>// The code used a recursive function to return gcd of p and q
int gcd(int p, int q)
{
// checking divisibility by 0 if (p == 0)
return q;
if (q == 0)
return p;
// base case
if (p == q)
return p; // p is greater
if (p > q)
return gcd(p-q, q);
else
return gcd(p, q-p);
}
// Driver program to test above function
int main()
{ int p = 98, q = 56;
printf("GCD of %d and %d is %d ", p, q, gcd(p, q));
return 0;
}
Question 2
Binary to Decimal Conversion
/** C program to convert the given binary number into decimal**/
#include<stdio.h>
int main()
{
int num, binary_val, decimal_val = 0, base = 1, rem;
printf("Insert a binary num (1s and 0s) \n");
scanf("%d", &num); /* maximum five digits */
binary_val = num;
while (num > 0)
{
rem = num % 10;
decimal_val = decimal_val + rem * base;
//num/=10;
num = num / 10 ;
//base*=2;
base = base * 2;
}
//display binary number printf("The Binary num is = %d \n", binary_val);
//display decimal number
printf("Its decimal equivalent is = %d \n", decimal_val);
return 0;
}
Question 3
Armstrong Number
#include<stdio.h>
intmain()
{
int num ,n,n1,c=0,mul=1,sum=0,r,f,i;
printf("enter any num: \n");
scanf("%d",&num);
n=num;
n1=num;
while(n!=0)
{
r=n%10;
c++;
n=n/10;
}
while (num!=0)
{
f=num%10;
mul=1;
for(i=1;i<=c;i++)
{
mul=mul*f;
}
sum=sum+mul;
num=num/10;
}
if(n1==sum)
printf("Armstrong Number");
else
printf("Not an Armstrong Number");
return 0;
}
Question 4
Write a C program to find the area of a circle with radius provided. The value of radius positive integer passed to the program as the first command line parameter. Write the output to stdout formatted as a floating point number rounded to EXACTLY 2 decimal precision WITHOUT any other additional text. Scientific format(such as 1.00E+5) should NOT be used while printing the output. You may assume that the inputs will be such that the output will not exceed the largest possible real number that can be stored in a float type variable.
It is highly advisable to go through Command Line Arguments Post before even looking at the code. Please study this for TCS and come back to this post later.
#include<stdio.h>
int main()
{
//for initialization of radius and area in a float datatype
float radius,area,pi=3.14;
// for use user input
printf("Enter the Radius of a Circle : ");
scanf("%f",&radius);
//formula of area of circle
area = pi*radius*radius;
printf("Area of Circle is: %f",area);
return 0;
}
Question 5
Command Line Program to check if a year is Leap Year or Not
#include<stdio.h>
intmain()
{
//initialization of Yearint year;
//to take user input
printf("Enter Year for find leap year or not : ");
scanf("%d",&year);
//we use this statement for check leap yearif(((year%4==0)&&(year%100!=0)) || (year%400==0))
printf("%d is a Leap Year",year);
//not leap year else
printf("%d is not a Leap Year",year);
return 0;
}
Question 6
Fibonacci Series
#include<stdio.h>
intmain()
{
//To initialize variablesint n1=0,n2=1,n3,limit,i;
//To take user input
printf("enter a limit of series \n");
scanf( "%d",&limit);
printf("Fibonacci series %d %d ",n1,n2);
//To use this loop for given lengthfor(i=2;i<limit;i++)
{
//n1 and n2 sum store in new variable n3
n3=n1+n2;
n1=n2;
n2=n3;
//display serious
printf("%d ",n3);
}
return 0;
}
Question 7
Ques. Write a C program to find the area of a triangle given the base and the corresponding height. The values base and height are both positive integers passed to the program as the first and second command line parameters respectively. Write the output to stdout formatted as a floating point number rounded to EXACTLY 2 decimal precision WITHOUT any other additional text. Scientific format(such as 1.00E+5) should NOT be used while printing the output. You may assume that the inputs will be such that the output will not exceed the largest possible real number that can be stored in a float type variable.
#include <stdio.h>
#include <math.h>
int calcArea(int a, int b, int c);
void main()
{
int a, b, c;
double area;
printf("Enter the values of a, b and c \n");
scanf("%d %d %d", &a, &b, &c);
area=calcArea(a,b,c);
printf("Area of a triangle = %f \n", area);
}
int calcArea(int a, int b, int c)
{
double area=0.0, s=0.0;
s = (a + b + c) / 2;
area = sqrt(s * (s - a) * (s - b) * (s - c));
return area;
}
Question 8
Palindrome Number
#include<stdio.h> int main() { //Initialization of variables where rev='reverse=0' int number, rev = 0,store, n1,left;
//input a numbers for user printf("Enter the number\n"); scanf("%d", &number);
//for duplicacy of number n1=number;
store= number; //use this loop for check true condition while (number > 0) { //left is for remider are left left= number%10;
//for reverse of no. rev = rev * 10 + left;
//number /= 10; number=number/10; } //To check reverse no is a Palindrome if(n1==rev) printf("Number %d is Palindrome number",n1); else printf("it is not a Palindrome number"); return 0; }
Question 9
Decimal to Binary
#include<stdio.h>intmain()
{
//for initialize a variableslong number, dec_num, rem, base = 1, bin = 0, count = 0;
//To insert a numberprintf("Insert a decimal num \n");
scanf("%ld", &number);
dec_num = number;
while(number > 0)
{
rem = number % 2;
/* To count no.of 1s */if (rem == 1)
{
count++;
}
bin = bin + rem * base;
//number/=2;
number = number / 2;
base = base * 10;
}
//displayprintf("Input num is = %d\n", dec_num);
printf("Its binary equivalent is = %ld\n", bin);
printf("Num of 1's in the binary num is = %d\n", count);
return 0;
}
Question 10
Binary to Octal
#include<stdio.h> intmain()
{
//For initialize variables long int binary_num, octal_num = 0, j = 1, rem;
//Inserting the binary number from the userprintf("Enter a binary number: ");
scanf("%ld", &binary_num);
// while loop for number conversion
while(binary_num != 0)
{
rem = binary_num % 10;
octal_num = octal_num + rem * j;
j = j * 2;
binary_num = binary_num / 10;
}
printf("Equivalent octal value: %ld", octal_num);
return 0;
}
Question 11
Decimal to Octal
#include<stdio.h>
intmain()
{
//Variable initializationlong dec_num, rem, quotient;
int i, j, octalno[100];
//Taking input from userprintf("Enter a number for conversion: ");
//Storing the value in dec_num variable scanf("%ld",&dec_num);
quotient = dec_num;
i=1;
//Storing the octal value in octalno[] arraywhile (quotient!=0)
{
octalno[i++]=quotient%8;
quotient=quotient/8;
}
//Printing the octalno [] in reverse orderprintf("\nThe Octal of %ld is:\n\n",dec_num);
for (j=i-1;j>0;j--)
//display it printf ("%d", octalno[j]);
return 0;
}
Question 12
String Palindrome
#include <stdio.h>
#include <string.h>
int main()
{
//Initializing variable.
char str[100];
int i,length=0,flag=0;
//Accepting input.
printf("Enter the string : ");
gets(str);
length=strlen(str);
//Initializing for loop.
for(i=0;i<length/2;i++)
{
//Checking if string is palindrome or not.
if(str[i]==str[length-i-1])
flag++;
}
//Printing result.
if(flag==i)
printf("String entered is palindrome");
else
printf("String entered is not palindrome");
return 0;
}
Question 13
Reverse of a number
#include<stdio.h>
intmain()
{
//Initialization of variables where rev='reverse=0'int number, rev = 0,store, left;
//input a numbers for user
printf("Enter the number\n");
scanf("%d", &number);
store= number;
//use this loop for check true conditionwhile (number > 0)
{
//left is for remider are left
left= number%10;
//for reverse of no.
rev = rev * 10 + left;
//number /= 10;
number=number/10;
}
//To show the user value
printf("Given number = %d\n",store);
//after reverse show numbers
printf("Its reverse is = %d\n", rev);
return 0;
}
#include<stdio.h>
int main()
{
int n1,n2,avg;
printf("Enter first no:");
scanf("%d",&n1);
printf("Enter first no:");
scanf("%d",&n2);
avg=(n1+n2)/2;
printf("Average is %d",avg);
}
Question 16
Greatest of two Numbers
#include<stdio.h>
int main()
{
int no1, no2;
printf("Insert two numbers:");
scanf("%d %d",&no1, &no2);
//Condition to check which of the two number is greater
//it will compare of number where number 1 is greaterif(no1 > no2)
printf("%d is greatest",no1);
//where number 2 is greater
else if(no2 > no1)
printf("%d is greatest",no2); //for both are equalelse
printf("%d and %d are equal", no1, no2);
return 0;
}
Question 17
Write a Program to print whether the given alphabet is vowel or consonant :
#include <stdio.h>
int main ()
{
char ch; // Get the character char ch;
scanf ("%c", &ch);
if (ch >= 'A' && ch <= 'Z')
{
ch = 'a' + (ch - 'A');
}
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
printf ("Vowel");
}
else
{
printf ("Consonant");
}
return 0;
}
Question 18
Write a program to Check whether a given number is a prime number or not :
#include <stdio.h>
int main ()
{
int n, i, flag = 0;
printf ("Enter a positive integer: ");
scanf ("%d", &n);
for (i = 2; i <= sqrt (n); ++i)
{
// condition for non prime number
if (n % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
printf ("%d is a prime number", n);
else
printf ("%d is not a prime number", n);
return 0;
}
Question 19
Write a program to change the case of the given alphabet and print:
#include <stdio.h>
int main ()
{
char c;
scanf ("%c", &c);
// Upper to lower case
if ('A' <= c && c <= 'Z')
{
printf ("%c", 'a' + (c - 'A'));
}
// Lower to upper case
if('a' <= c && c <= 'z')
{
printf ("%c", 'A' + (c - 'a'));
}
return 0;
}
Question 20
Given an array and a number (say s), find whether any two elements in the array whose sum is “s”:
#include<stdio.h>
#include<stdlib.h>
void check_sum_and_diplay (int arr[], int size, int sum);
int main ()
{
// Get the size of an array
int size;
scanf ("%d", &size);
// Get the array elements
int arr[50], i;
for (i = 0; i < size; i++)
{
scanf ("%d", &arr[i]);
// Get the sum value (to check with an array elements)
int sum;
scanf ("%d", &sum);
// Function call to check the sum of any two elements in an array equal to given sum// and display the same
check_sum_and_diplay (arr, size, sum);
return 0;
}
}
void check_sum_and_diplay (int arr[], int size, int sum)
{
int i, j;
for (i = 0; i < size - 1; i++)
{
if (sum == (arr[i] + arr[j]))
{
printf ("Perfect couple: %d %d", arr[i], arr[j]);
exit (0);
}
printf ("No perfect couple found!");
}
}
Question 21
Write a program to find the most occurring character in the string.
#include<stdio.h>
#define MAX_SIZE 100
#define MAX_CHARS 26
int main ()
{
int i;
//Get a sentence
char str[MAX_SIZE];
scanf ("%d", str);
// Init Freq starting array
int freq[MAX_CHARS];
for (i = 0; i < max_chars; i++)
{
freq[i] = 0;
}
//frequency of each character is counted
for (i = 0; str[i] !='\0'; i++)
{
int isalphabet = 0, offset;
if (str[i] >= 'a' && str[i] <= 'z') { isalphabet = 1; offset = str[i] - 'a'; } else if (str[i] >= 'A' && str[i] <= 'Z')
{
isAlphabet = 1;
offset = str[i] - 'A';
}
if (isAlphabet == 1)
{
freq[offset] += 1;
}
}
// If two characters occurred the same number of time then// print lowest ASCII value character. int max_index = 0; for(i=0; i<max_chars;i++)
{
if (freq[i] > freq[max_index])
{
max_index = i;
}
}
int max_repeated_char = 'a' + max_index;
printf ("%c", max_repeated_char);
return 0;
}
The Words Like “Placement Papers” and “Previous Year Papers” are used here for Google Search Purposes only and may not be. All these questions could be freely available on the internet, we are only charging students for the PrepInsta’s Mock Test experiences and Analytics as well as preparation for the exam. Prepinsta does not guarantee any recurrence of the questions in the exam however we believe that from our practise questions the exam should atleast be similar in pattern as per syllabus or difficulty. These are only practise mock questions. PrepInsta has compiled these from various internet sources and made them as per mock experience for students ease and are offering analytics as per performance
Qs 11 may be solved in python as….
def prime(n):
i,j=0,2
while i2: return(fibo(n-1)+fibo(n-2))
n=int(input(‘Enter N:’))
if n%2==0: print(prime(n//2))
else: print(fibo(n//2+1))
Command Line will not be used as a coding language in TCS Ninja Test. However, you need to learn command line programming, it is very important that you do. As 1 MCQ question in programming Logic section will be asked from command line programming basics.
Qs 11 may be solved in python as….
def prime(n):
i,j=0,2
while i2: return(fibo(n-1)+fibo(n-2))
n=int(input(‘Enter N:’))
if n%2==0: print(prime(n//2))
else: print(fibo(n//2+1))
I think Programming 11 has some issue, plz chek it
ok Syed we’ll see to it
Please share the Code of WaterMark Solution Problem of TCS phase 2 test slot 1 on 1st sep 2019.
Will any command line programs come in TCS NQT 2020 in last round of coding section
Hi,
Command Line will not be used as a coding language in TCS Ninja Test. However, you need to learn command line programming, it is very important that you do. As 1 MCQ question in programming Logic section will be asked from command line programming basics.
Thank you sir. The questions that you gave above was repeated in my Bsc for tcs that happened on July 5, 2019. Thank you so much.
It was exact same I even knew the code as I did it a day before from your website. I hope that I clear my interview as well
what is the cut-off marks for TCS Ninja and how much we did need to score in order to get selected for TCS Digital .
Thank you sir. I got similar questions in the exam as well. Not the same question but the pattern was same.
Tcs paper pattern has changed.
They have kept args prog in mcq and coding section has changed.
Where can i get coding qstns according to the new one?