TCS Coding Questions with Answers

coding

TCS Programming Questions with Answers for Freshers

TCS Programming Test 2021 Questions  are not like a general Coding Round Questions with Solutions it is all together different from C programming. We have analysed over 100+ TCS Programming Questions. Below you will find Similar pattern based TCS Programming Round Questions, TCS Coding Questions that are asked constantly in TCS Placement test. You must prepare coding section of TCS NQT very well to score TCS NQT test. The languages that you can use in the test are –

  • C
  • C++
  • Java
  • Python
  • Perl

Practice Prime MOCK for Coding Section here:

IMPORTANT NOTE:

  1. There will be no negative marking.
  2. TCS NQT is adaptive this year
  3. You will not get any extra rough paper in the exam as a calculator and Rough Paper will be available on your Desktop Screen. You are not allowed to move your eyes down while giving the examination.

Subscribe on YouTube

TCS Coding Questions

Coding SectionNo. of QuestionsTime Limit
Hands On (Coding 1)1 Question15 mins
Hands On (Coding 2)1 Question30 mins

TCS NQT Coding Question 2020 – Day 1 – Slot 1

There is a JAR full of candies for sale at a mall counter. JAR has the capacity N, that is JAR can contain maximum N candies when JAR is full. At any point of time. JAR can have M number of Candies where M<=N. Candies are served to the customers. JAR is never remain empty as when last k candies are left. JAR if refilled with new candies in such a way that JAR get full.
Write a code to implement above scenario. Display JAR at counter with available number of candies. Input should be the number of candies one customer can order at point of time. Update the JAR after each purchase and display JAR at Counter.

Output should give number of Candies sold and updated number of Candies in JAR.

If Input is more than candies in JAR, return: “INVALID INPUT”

Given, 

N=10, where N is NUMBER OF CANDIES AVAILABLE

K =< 5, where k is number of minimum candies that must be inside JAR ever.

Example 1:(N = 10, k =< 5)

  • Input Value
    • 3
  • Output Value
    • NUMBER OF CANDIES SOLD : 3
    • NUMBER OF CANDIES AVAILABLE : 7

Example : (N=10, k<=5)

  • Input Value
    • 0
  • Output Value
    • INVALID INPUT
    • NUMBER OF CANDIES LEFT : 10
#include<stdio.h>   
int main()  
{
	int n=10, k=5;
	int num;
	scanf("%d",&num);
	if(num>=1 && num<=5)
	{
    		printf("NUMBER OF CANDIES SOLD : %d\n",num);
    		printf("NUMBER OF CANDIES LEFT : %d",n-num);
	}
	else
	{
    		printf("INVALID INPUT\n");
    		printf("NUMBER OF CANDIES LEFT : %d",n);
	}
	return 0;
} 

#include <iostream.h>
using namespace std;
int main()
{
	int n=10, k=5;
	int num;
	cin>>num;
	if(num>=1 && num<=5)
	{
    	cout<< "NUMBER OF CANDIES SOLD : "<<num<<"\n";
    	cout<<"NUMBER OF CANDIES LEFT : "<<n-num;
	}
	else
	{
    	cout<<"INVALID INPUT\n";
    	cout<<"NUMBER OF CANDIES LEFT : "<<n;
	}
	return 0;
}
import java.util.Scanner;
class Main{
    public static void main(String[] args) {
   	 int n = 10, k = 5;
   	 int num;
   	 Scanner sc = new Scanner(System.in);
   	 num = sc.nextInt();
   	 if(num >= 1 && num <= 5) {
   		 System.out.println("NUMBER OF CANDIES SOLD : " + num);
   		 System.out.print("NUMBER OF CANDIES LEFT : " + (n - num));
   	 } else {
   		 System.out.println("INVALID INPUT");
   		 System.out.print("NUMBER OF CANDIES LEFT : " + n);
   	 }
    }
}
total_candies = 10
no_of_candies = int(input())
if no_of_candies in range(1, 6):
	print('No. of Candies Sold:',no_of_candies)
	print('No. of Candies Left:',total_candies-no_of_candies)
else:
	print("Invalid Input")
	print('No. of Candies Left:',total_candies)

TCS NQT Coding Question 2020 – Day 1 – Slot 1

Selection of MPCS exams include a fitness test which is conducted on ground. There will be a batch of 3 trainees, appearing for running test in track for 3 rounds. You need to record their oxygen level after every round. After trainee are finished with all rounds, calculate for each trainee his average oxygen level over the 3 rounds and select one with highest oxygen level as the most fit trainee. If more than one trainee attains the same highest average level, they all need to be selected.

Display the most fit trainee (or trainees) and the highest average oxygen level.

Note:

  • The oxygen value entered should not be accepted if it is not in the range between 1 and 100.
  • If the calculated maximum average oxygen value of trainees is below 70 then declare the trainees as unfit with meaningful message as “All trainees are unfit.
  • Average Oxygen Values should be rounded.

Example 1:

  • INPUT VALUES

            95

            92

            95

            92

            90

            92

            90

            92

            90

  • OUTPUT VALUES
    • Trainee Number : 1
    • Trainee Number : 3

Note:

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”

#include <stdio.h>   
int main()  
{
	int trainee[3][3];
	int average[3] = {0};
	int i, j, max=0;
	for(i=0; i<3; i++)
	{
    		for(j=0; j<3; j++)
    		{
        		scanf("%d",&trainee[i][j]);
        		if(trainee[i][j]<1 || trainee[i][j]>100)
        		{
            		trainee[i][j] = 0;
        		}
    		}
	}
	for(i=0; i<3; i++)
	{
    		for(j=0; j<3; j++)
    		{
        			average[i] = average[i] + trainee[j][i];
    		}
    		average[i] = average[i] / 3;
	}
	for(i=0; i<3; i++) { if(average[i]>max)
    		{
        			max = average[i];
    		}
	}
	for(i=0; i<3; i++)
	{
    		if(average[i]==max)
    		{
        			printf("Trainee Number : %d\n",i+1);
    		}
    		if(average[i]<70)
    		{
        			printf("Trainee is Unfit");
    		}
	}
	return 0;
}  
#include<iostream.h> 
using namespace std;
int main()  
{
	int trainee[3][3];
	int average[3] = {0};
	int i, j, max=0;
	for(i=0; i<3; i++)
	{
        	for(j=0; j<3; j++) { cin>>trainee[i][j];
                	if(trainee[i][j]<1 || trainee[i][j]>100)
                	{
                    	trainee[i][j] = 0;
            	}
        	}
	}
	for(i=0; i<3; i++)
	{
        	for(j=0; j<3; j++)
        	{
                	average[i] = average[i] + trainee[j][i];
        	}
        	average[i] = average[i] / 3;
	}
	for(i=0; i<3; i++) { if(average[i]>max)
        	{
                	max = average[i];
        	}
	}
	for(i=0; i<3; i++)
	{
        	if(average[i]==max)
        	{
                	cout<<"Trainee Number : "<<i+1<<"\n";
        	}
        	if(average[i]<70)
        	{
                	cout<<"Trainee is Unfit";
        	}
	}
	return 0;
} 

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
   	 int[][] trainee = new int[3][3];
   	 int[] average = new int[3];
   	 int max = 0;
   	 Scanner sc = new Scanner(System.in);
   	 for(int i = 0; i < 3; i++) {
   		 for(int j = 0; j < 3; j++) {
   			 trainee[i][j] = sc.nextInt();
   			 if(trainee[i][j] < 1 || trainee[i][j] > 100) {
   				 trainee[i][j] = 0;
   			 }
   		 }
   	 }
   	 for(int i = 0; i < 3; i++) {
   		 for(int j = 0; j < 3; j++) {
   			 average[i] = average[i] + trainee[j][i];
   		 }
   		 average[i] = average[i] / 3;
   	 }
   	 for(int i = 0; i < 3; i++) {
   		 if(average[i] > max) {
   			 max = average[i];
   		 }
   	 }
   	 for(int i = 0; i < 3; i++) {
   		 if(average[i] == max) {
   			 System.out.println("Trainee Number : " + (i + 1));
   		 }
   		 if(average[i] <70) {
   			 System.out.print("Trainee is Unfit");
   		 }
   	 }
    }

}

trainee = [[],[],[],[]]
for i in range(3):
	for j in range(3):
    		trainee[i].append(int(input()))
    		if (trainee[i][-1]) not in range(1,101):
        			print("invalid input")
for i in range(3):
	trainee[3].append((trainee[2][i]+trainee[1][i]+trainee[0][i])//3)
maximum = max(trainee[3])
for i in range(3):
	if trainee[3][i] < 70 :
    		print("Trainee {0} is unfit".format(i+1))
	elif trainee[3][i] == maximum:
    		print("Trainee Number: ",i+1)

TCS Coding Question Day 1 Slot 2 – Question 1

Problem Statement

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

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

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

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

Assume the capacity of machine is maximum 7000 grams

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

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

“INVALID INPUT”.

Input should be in the form of integer value –

Output must have the following format –

Time Estimated: Minutes

Example:

  • Input value

2000

  • Output value

Time Estimated: 25 minutes

Solution

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

TCS Coding Question Day 1 Slot 2 – Question 2

Problem Statement

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

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

TCS Coding Question Day 2 Slot 1 – Question 1

Problem Statement

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

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

If a user enters zero  as the number of walls then skip Surface area values as 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

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

if exterior_walls:
    ext_walls = []
    for i in range(exterior_walls):
        ext_walls.append(float(input()))
if exterior_walls < 0 or interior_walls < 0:
    print(“Invalid Input”)
    exit()
if exterior_walls and interior_walls:
    print("Total estimated Cost : ",(sum(int_walls)*18+sum(ext_walls)*12),"INR")
else:
    if exterior_walls:
        print("Total estimated Cost : ",sum(ext_walls)*12,"INR")
    elif interior_walls:
         print("Total estimated Cost : ",sum(int_walls)*18,"INR")
    else:
        print("Total estimated Cost : 0.0 INR")
import java.util.Scanner;
class Main {
    public static void main(String[] args) {
       int ni, ne, i = 0;
       float intP = 18, extP = 12, cost = 0, temp;
       Scanner sc = new Scanner(System.in);
       ni = sc.nextInt();
       ne = sc.nextInt();
       if(ni < 0 || ne < 0) {
           System.out.print("INVALID INPUT");
       } else if(ni == 0 && ne == 0) {
           System.out.print("Total estimated Cost : 0.0");
       } else {
           for(i = 0; i < ni; i++) {
               temp = sc.nextFloat();
               cost += intP * temp;
           }
           for(i = 0; i < ne; i++) {
               temp = sc.nextFloat();
               cost += extP * temp;
           }
           System.out.printf("Total estimated Cost : %.1f", cost);
       }
    }
}

TCS Coding Question Day 2 Slot 1 – Question 2

Problem Statement

A City Bus is a Ring Route Bus which runs in circular fashion.That is, Bus once starts at the Source Bus Stop, halts at each Bus Stop in its Route and at the end it reaches the Source Bus Stop again.
If there are n  number of Stops and if the bus starts at Bus Stop 1, then after nth Bus Stop, the next stop in the Route will be Bus Stop number 1 always.
If there are n stops, there will be n paths.One path connects two stops. Distances (in meters) for all paths in Ring Route is given in array Path[] as given below:
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

#include <bits/stdc++.h>
using namespace std;
int main() {
string s , d;
 cin>>s>>d;
 transform(s.begin(),s.end() , s.begin(),::toupper);
 transform(d.begin(),d.end() , d.begin(),::toupper);
 string arrs[8] = {"TH" , "GA", "IC" , "HA" , "TE", "LU" ,"NI","CA"};
 float arr[8]={800,600,750,900,1400,1200,1100,1500};
 float res=0;
 int st ,ed;
 for(int i=0;i<8;i++)
 {
     if(s==arrs[i])
     st=i;
     
     if(d==arrs[i])
     ed=i;
  }
  if(st==ed)
  {
      cout<<" INVALID INPUT";
      return 0;
  }
  else
  {
      int i=st+1;
      cout<<i;
        while(i!=ed+1)
        {
            res+=(arr[i]);
            i=(i+1)%8;
        }
        cout<<(ceil)(res*0.005);
        return 0;
}
}

import math
def getFare(source,destination):
    route=[ [ "TH", "GA", "IC", "HA", "TE", "LU", "NI", "CA"],
    [800,600,750,900,1400,1200,1100,1500]
        ]
    fare = 0.0
    if not (source in route[0] and destination in route[0]):
        print("Invalid Input")
        exit()
    if route[0].index(source) < route[0].index(destination):
        for i in range(route[0].index(source),route[0].index(destination)+1):
            fare+=route[1][i]
    elif route[0].index(destination) < route[0].index(source):
        for i in range(route[0].index(source)+1,len(route[0])):
            fare+=route[1][i]
        for i in range(0,route[0].index(destination)+1):
            fare+=route[1][i]
    return float(math.ceil(fare*0.005))
  
source = input()
destination = input()
fare = getFare(source,destination)
if fare == 0:
    print("Invalid Input")
else:
    print(fare)

TCS Coding Question Day 2 Slot 2 – Question 1

Problem Statement

There are total n number of Monkeys sitting on the branches of a huge Tree. As travelers offer Bananas and Peanuts, the Monkeys jump down the Tree. If every Monkey can eat k Bananas and j Peanuts. If total m number of Bananas and p number of Peanuts are offered by travelers, calculate how many Monkeys remain on the Tree after some of them jumped down to eat.
At a time one Monkeys gets down and finishes eating and go to the other side of the road. The Monkey who climbed down does not climb up again after eating until the other Monkeys finish eating.
Monkey can either eat k Bananas or j Peanuts. If for last Monkey there are less than k Bananas left on the ground or less than j Peanuts left on the ground, only that Monkey can eat Bananas(<k) along with the Peanuts(<j).
Write code to take inputs as n, m, p, k, j and return  the number of Monkeys left on the Tree.
    Where, n= Total no of Monkeys
        k= Number of eatable Bananas by Single Monkey (Monkey that jumped down last may get less than k Bananas)
        j = Number of eatable Peanuts by single Monkey(Monkey that jumped down last may get less than j Peanuts)
        m = Total number of Bananas
        p  = Total number of Peanuts
Remember that the Monkeys always eat Bananas and Peanuts, so there is no possibility of k and j having a value zero

Example 1:
Input Values    
20
2
3
12
12

Output Values
Number of  Monkeys left on the tree:10

Note:
Kindly follow  the order of inputs as n,k,j,m,p as given in the above example. And output must include  the same format  as in above example(Number of Monkeys left on the Tree:)
For any wrong input display INVALID INPUT

#include <stdio.h>
int main()
{
    int n,k,j,m,p;
    float atebanana=0.0,atepeanut=0.0;
    scanf("%d %d %d %d %d",&n,&k,&j,&m,&p);
    if(n<0 || k<0 || j<0 || m<0 || p<0)
    {
        printf("INVALID INPUT");
    }
    else
    {
        if(k>0)
            atebanana =(float)m/k;
        if(j>0)
            atepeanut =(float) p/j;
        n=n-atebanana-atepeanut;
        printf("Number of Monkeys left on the Tree:%d",n);
    }
    return 0;
}
import java.util.*;
 class Monkeys 
{
    public static void main(String []args)
    {
    Scanner sc = new Scanner (System.in);
    int n = sc.nextInt();
    int k = sc.nextInt();
    int j = sc.nextInt();
    int m = sc.nextInt();
    int p = sc.nextInt();
    int atebanana=0 ,atepeanut=0;
    if( n<0 && k<0 || j<0 || m<0 || p<0)
    {
        System.out.println("Invalid Input");
    }
    else
    {
        if(k>0)
             atebanana =m/k;
        if(j>0)
             atepeanut = p/j;
         n=n-atebanana-atepeanut;
         System.out.println("Number of Monkeys left on the Tree: "+n);
  }
}
}

TCS Coding Question Day 2 Slot 2 – Question 2

Problem Statement

Chain Marketing Organization has has a scheme for income generation, through which its members generate income for themselves. The scheme is such that suppose A joins the scheme and makes R and V to join this scheme  then A is Parent Member of R and V who are child Members. When any member joins the scheme then the parent gets total commission of 10% from each of its child members.
Child members receive commission of 5% respectively. If a Parent member does not have any member joined under him, then he gets commission of 5%.
Take name of the members joining the scheme as input.
Display how many members joined the scheme including parent member.Calculate the Total commission gained by each members in the scheme. The fixed amount for joining the scheme is Rs.5000 on which commission will be generated
SchemeAmount = 5000

Example 1: When there are more than one child members 
Input : (Do not give input prompts.Accept values as follows. )
Amit                     //Enter parent Member as this
Y                           //Enter Y if  Parent member has child members otherwise enter N
Rajesh,Virat        //Enter names of child members of Amit in comma separated
Output:(Final Output must be in format given below.)
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

using namespace std;
int main()
{
    string par;
    cin >> par;
   string x;
  cin >> x;
    if (x == "N") {
        cout << "TOTAL MEMBERS:1\n";
        cout << "COMISSION DETAILS\n";
        cout << par << ":250 INR\n";
    } else {
        string child;
        cin >> child;
        vector<string>v;
        string temp = "";
        for (int i = 0; i < child.length(); i++) {
            if (child[i] == ',') {
                v.push_back(temp);
                temp = "";
            }
            else  if (child[i] != ' ')
                temp += child[i];
        }
        v.push_back(temp);
        cout << "TOTAL MEMBERS:" << v.size() + 1 << "\n";
        cout << "COMISSION DETAILS\n";
        cout << par << ":" << v.size() * 500 << " INR\n";
        for (auto a : v) {
            cout << a << ":" << "250 INR\n";
     }
  }
}
parent = input()
Yes_No = input()
if Yes_No == "N":
    print("TOTAL MEMBERS:1\nCOMMISSION DETAILS\n{0}: 250 INR".format(parent))
elif Yes_No == "Y":
    child=list(map(str,input().split(",")))
    print("TOTAL MEMBERS:{}".format(len(child)+1))
    print("COMMISSION DETAILS \n{0}:{1} INR".format(parent,len(child)*500))
    for i in child:
        print("{0}:250 INR".format(i))

Checking if a given year is leap year or not

Explanation:

To check whether a year is leap or not

Step 1:

  • We first divide the year by 4.
  • If it is not divisible by 4 then it is not a leap year.
  • If it is divisible by 4 leaving remainder 0 

Step 2:

  • We divide the year by 100
  • If it is not divisible by 100 then it is a leap year.
  • If it is divisible by 100 leaving remainder 0

Step 3:

  • We divide the year by 400
  • 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

 

#include<stdio.h>
int leapprog(int year)
{
//checking divisibility by 4
    if(year%4 == 0)
    {
//checking divisibility by 100
        if( year%100 == 0)
        {
//checking divisibility by 400
            if ( year%400 == 0)
                printf("%d, the year entered happens to be a leap year", year);
            else
                printf("%d is surely not a leap year", year);
        }
        else
            printf("%d, the year entered happens to be a leap year", year );
    }
    else
        printf("%d is surely not a leap year", year);
      return 0;
}
int main()
{
    int input_year, val;
    printf("Enter the year that you want to check"); //enter the year to check
    scanf("%d",&input_year);
    val = leapprog(input_year);    
return 0;
}
//C++ Program
//Leap year or not
#include<stdio.h>
using namespace std;
//main program
int main()
{
//initialising variables
int year;
cout<<"Enter year to check: ";
//user input
cin>>year;
//checking for leap year
if( ((year % 4 == 0)&&(year % 100 != 0)) || (year % 400==0) )
{
//input is a leap year
cout<<year<<" is a leap year";
}
else
{
//input is not a leap year
cout<<year<< " is not a leap year";
}
return 0;
}

Output:

Enter year to check: 2019

2019 is not a leap year

/*Java program to check whether a year entered by user is a leap year or not and a leap year is a year
which is completely divisible by 4,but the year should not be a century year except it is divisible by 400*/

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc=new Scanner(System.in);
//input year from user
System.out.println("Enter a Year");
int year = sc.nextInt();
//condition for checking year entered by user is a leap year or not
if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}
#python program to check if a year number taken from the user is a leap year or not, using nested if-else.

num = int(input("Enter the year you want to check if is leap year or not: "))

#take input year from the user to check if it is a leap year

if(num%4 == 0):

 #check if the number is divisible by 4 and if true move to next loop

   if(num%100 == 0):

     #check if the input year is divisible by 100 and if true move to next loop

       if(num%400 == 0):

           print("The year {} is a leap year".format(num))

           #the input year is divisible by 4, 100 and 400, hence leap year.

       else:

           print("The year {} is Not a leap year".format(num))

   else:

       print("The year {} is a leap year".format(num))

       #if the number is divisible by both 4 and 100 it is a leap year

else:

   print("The year {} is Not a leap year".format(num))

   #if the input num is not divisible by 4 then it can not be a leap year altogether.
# 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

Prime Numbers 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?

  • 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.

 

#include<stdio.h>
void prime(int n)
{
int c=0;
    for(int i=2;i<n;i++)
    {
        if(n%i==0)
        c = c+1;
    }
    if(c>=1)
        printf("%d is not a prime number",n);
    else
        printf("%d is a prime number",n);
}
void main()
{
int n;
printf("Enter no : "); //enter the number
scanf("%d",&n);
if(n<0)
    {
    printf("Please enter a positive integer");
    }
else
    prime(n);
}
//C++ Program
//Prime Number
#include
using namespace std;
//function declaration
void enter();
void check(int);
void prime(int);
//main program
int main()
{
enter();
return 0;

}
//function to enter value
void enter()
{
int num;
cout<<"Enter number:";
cin>>num;
check(num);
}
//function to check whether the input is positive or negative
void check(int num)
{
if(num<0)
{
cout<<"invalid input enter value again"<<endl;
enter();
}
else
{
prime(num);
}
}
//function to check for prime number
void prime(int num)
{
int i,div=0;
for(i=1;i<=num;i++)
{
if(num%i==0)
{
div++;
}
}
//prime number only have two divisors
if(div==2)
{
cout<<num<<" is a prime number";
}
//not a prime number
else
{
cout<}

Output:

Enter number:29

29 is a prime number.
/*Java program to check whether a number entered by user is prime or not for only positive numbers,
if the number is negative then ask the user to re-enter the number*/

//Prime number is a number which is divisible by 1 and another by itself only.

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//input a number from user
System.out.println("Enter the number to be checked : ");
int n = sc.nextInt();
//create object of class CheckPrime
Main ob=new Main();
//calling function with value n, as parameter
ob.check(n);
}
//function for checking number is positive or negative
void check(int n)
{
if(n<0)
System.out.println("Please enter a positive integer");
else
prime(n);
}
//function for checking number is prime or not
void prime(int n)
{
int c=0;
for(int i=2;i<n;i++)
{
if(n%i==0)
++c;
}
if(c>=1)
System.out.println("Entered number is not a prime number");
else
System.out.println("Entered number is a prime number");
}
}
def prime(n):

   if n > 1:

    for i in range(2, n):

        if (n % i) == 0:

            print(n, "is not a prime number")

            break

    else:

        print(n, "is a prime number")

num = int(input("enter a number: "))

if (num > 0):

    prime(num)

else:

    print("please enter a positive number")
#Perl Script
#Prime Number or Not
print "Enter a number";
$n=<STDIN>;
$d=0;
if($n<0)
{
print "Ivalid Input!!! Enter Value Again";
}
else
{
#Loop to find number of divisors
for($c=1;$c<=$n;$c++)
{
if($n%$c==0)
{
$d=$d+1;
}
}
#checking for prime numbers
if($d==2)
{
print "Prime Number";
}
else
{
print "Not a Prime number";
}
}

Output

Enter a number31
Prime Number

Number Series with a Twist – 1

Find the 15th term of the series?

0,0,7,6,14,12,21,18, 28

Explanation : In this series the odd term is increment of 7 {0, 7, 14, 21, 28, 35 – – – – – – }

                        And even term is a increment of 6 {0, 6, 12, 18, 24, 30 – – – – – – }

 

#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)
{
           a = a + 7;
}
       else
      {    
           b = b + 6;
}
}
    if(n%2!=0)
{
           printf("%d term of series is %d\t",n,a-7);
}
      else
  {    
printf("%d term of series is %d\t",n,b-6);
}
return 0;
}
//C++ Program
#include
using namespace std;
int main()
{
//initialising variables
int n,d;
cout<<"Enter the position: ";
//user input
cin>>n;
//logic to find nth element of the series
if(n==1||n==2)
{
cout<<0;
return 0;
}
else if(n%2==0)
{
n=n/2;
d=6;
}
else
{
n=n/2+1;
d=7;
}
//logic ends here
//printing output
cout<<(n-1)*d;
return 0;
}

Output:

Enter the position: 15
49
//Java program to find 15th element of the series
class Main
{
public static void main(String[] args)
{
int a = 7, b = 0,c;
System.out.println("Series :");
for(int i = 1 ; i < 8 ; i++)
{
c = a * b;
System.out.print(c+" "+(c-b)+" ");
b++;
}
c = a * b;
System.out.println(c);
System.out.print("15th element of the series is = "+c);
}
}

Output :

Series :
0 0 7 6 14 12 21 18 28 24 35 30 42 36 49
15th element of the series is = 49
num = int(input('enter the number: '))

a=0

b=0

for i in range(1,num+1):

    if(i%2!=0):

        a= a+7

    else:

        b = b+6

if(num%2!=0):

    print(' {} term of series is {}'.format(num,a-7))

else:

    print('{} term of series is {}'.format(num,b-6))
#perl Script
print"Enter position: ";
$n=;
$term=0;
$d=0;
if($n==0||$n==1)
{
$term=0;
}
else
{
if(0==$n%2)
{
$n=($n/2);
$d=6;
}
else
{
$n=($n/2) + 0.5;
$d=7;
}
$term= ($n-1) * $d;
}
print"$term.";

Output

Enter position: 15
49.

Number Series with a Twist 2

Link to this Question

Consider the following series: 1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243, 64, 729, 128, 2187 …

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.

You can assume that N will not exceed 30.

 

#include<stdio.h>
int main()
{
   int i, n, a=1, b=1;
   printf("enter number : ");
   scanf("%d",&n);
   for(i=1;i<=n;i++)
   {
       if(i%2!=0)
       {
           a = a * 2;
       }
       else
       {    
            b = b * 3;
       }
   }
    if(n%2!=0)
       {
           printf("\n%d term of series is %d\t",n,a/2);
       }
       else
       {    
           printf("\n%d term of series is %d\t",n,b/3);
       }
return 0;
}
//C++ Program
#include
#include
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)
{
n=n/2-1;
r=3;
}
else
{
n=n/2;
r=2;
}
//logic ends here
//printing output
cout<<(int)(pow(r,n));
return 0;
}

Output:

Enter the position: 17
256

Code :

//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);
//input value of n
System.out.print("Enter the value of n : ");
int n = sc.nextInt();
int a = 1, b = 1;
//statement for even value of n
if(n % 2 == 0)
{
for(int i = 1 ; i <= (n-2) ; i = i+2)
{
a = a * 2;
b = b * 3;
}
System.out.print(n+" element of the series is = "+b);
}
//statement for odd value of n
else
{
for(int i = 1 ; i < (n-2) ; i = i+2)
{
a = a * 2;
b = b * 3;
}
a = a * 2;
System.out.print(n+" element of the series is = "+a);
}
}
}

Output :

Enter the value of n : 14
14 element of the series is = 729
n = int(input('enter the number: '))

a= 1

b= 1

for i in range(1, n+1):

    if(i%2!=0):

       

        a = a*2

    else:      

        b = b*3

if(n%2!=0):

    print('\n{} term of series is {}\t'.format(n,a/2))

else:

    print('\n{} term of series is {}\t'.format(n,a/2))
#Perl Script
$a=1;
$b=1;
print("enter number : ");
$n=<STDIN>;
for($i=1;$i<=$n;$i++)
{
if($i%2!=0)
{
$a = $a * 2;
}
else
{
$b = $b * 3;
}
}
if($n%2!=0)
{
print("$n term of series is ",$a/2);
}
else
{
print("$n term of series is ",$b/3);
}

Output

enter number : 17
17 term of series is 256

Number Series with a Twist 3

Link to this Question – 

Consider the below series :

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 using the formula (x/2)

Write a program to find the nth term in this 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 the value of the nth term no other characters /strings or message should be written to STDOUT.

For example if n=10,the 10 th term in the series is to be derived from the 9th term 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.

 

#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;
}
#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 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);
}
}
}
n = int(input('enter the number:'))

a=0
b=0

for i in range(1,n+1):
if(i%2!=0):
a= a+2
else:
b= b+1

if(n%2!=0):
print('{}'.format(a-2))
else:
print('{}'.format(b-1))

String with a Twist

Link to this Questions

1. The program will recieve 3 English words inputs from STDIN

  1. These three words will be read one at a time, in three separate line
  2. The first word should be changed like all vowels should be replaced by %
  3. The second word should be changed like all consonants should be replaced by #
  4. The third word should be changed like all char should be converted to upper case
  5. Then concatenate the three words and print them

Other than these concatenated word, no other characters/string should or message should be written to STDOUT

For example if you print how are you then output should be h%wa#eYOU.

You can assume that input of each word will not exceed more than 5 chars

 
#include <stdio.h>
#include <string.h>
int main()
{
  char a[10], b[10], c[10];
  int i,j;
  int x, y, z;

  scanf("%s",a);
  scanf("%s",b);
  scanf("%s",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]=='u')
      {
          a[i] = '%';
      }
  }
  for(j=0;j<y;j++)
  {
      if(b[j]=='b'||b[j]=='c'||b[j]=='d'||b[j]=='f'||b[j]=='g'||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'||b[j]=='v'||b[j]=='w'||
         b[j]=='x'||b[j]=='y'||b[j]=='z')
      {
          b[j] = '#';
      }
      
      if(b[j]=='B'||b[j]=='C'||b[j]=='D'||b[j]=='F'||b[j]=='G'||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'||b[j]=='V'||b[j]=='W'||
         b[j]=='X'||b[j]=='Y'||b[j]=='Z')
      {
          b[j] = '#';
      }
  }
  z=0;
   while (c[z] != '\0') {
      if (c[z] >= 'a' && c[z] <= 'z')
       {
         c[z] = c[z] - 32;
      }
      z++;
   }
   printf("%s%s%s",a,b,c);
}
#include <iostream>
#include <string.h>

using namespace std;
int main() { char a[10], b[10], c[10]; 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]=='u') { a[i] = '%'; } } for(j=0;j<y;j++) { if(b[j]=='b'||b[j]=='c'||b[j]=='d'||b[j]=='f'||b[j]=='g'||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'||b[j]=='v'||b[j]=='w'|| b[j]=='x'||b[j]=='y'||b[j]=='z') { b[j] = '#'; } if(b[j]=='B'||b[j]=='C'||b[j]=='D'||b[j]=='F'||b[j]=='G'||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'||b[j]=='V'||b[j]=='W'|| b[j]=='X'||b[j]=='Y'||b[j]=='Z') { b[j] = '#'; } } z=0; while (c[z] != '\0') { if (c[z] >= 'a' && c[z] <= 'z') { c[z] = c[z] - 32; } z++; } cout << a << b << c;

return 0; }

 

import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter three words : ");

String s1 = sc.next();
String s2 = sc.next();
String s3 = sc.next();

int l1 = s1.length();
int l2 = s2.length();

String str1 = "";
String str2 = "";
String str3 = "";
char c;
for(int i = 0 ; i < l1 ; i++)
{
c = s1.charAt(i);
if(c == 'A' || c == 'a' || c == 'E' ||
c == 'e' || c == 'I' || c == 'i' || c == 'O' || c == 'o' || c == 'U' || c == 'u')
str1 = str1 + "%";
else
str1 = str1 + c;
}
for(int i = 0 ; i < l2 ; i++)
{
c = s2.charAt(i);
if((c >= 'A' && c <= 'Z')||(c >= 'a' && c <= 'z'))
{
if(c == 'A' || c == 'a' || c == 'E' || c == 'e' ||
c == 'I' || c == 'i' || c == 'O' || c == 'o' || c == 'U' || c == 'u')
str2 = str2 + c;
else
str2 = str2 + "#";
}
else
str2 = str2 + c;
}
str3 = s3.toUpperCase();
System.out.println(str1+str2+str3);
}
}

Addition of two numbers a Twist

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>
addition(int x, float y)
{
    float ans;
    ans = (float)x + y;
    printf("Answer : %.2f",ans);
}
int main()
{
   int a;
   float b;
   printf("enter first number : ");
   scanf("%d",&a);
   printf("enter second number : ");
   scanf("%f",&b);
   addition(a, b);
}
//C++ Program
//Sum of two numbers using function
#include<stdio.h>
using namespace std;
//function to add two numbers
float sum(int a, float b)
{
return (float)(a+b);
}
//main program
int main()
{
//initialising variables
int a;
float b;
cout<<"Enter two numbers";
//user input
cin>>a;
cin>>b;
//call function to find sum
cout<<"Sum of "<<a<<" and "<<b<<" is "<<sum(a,b);
return 0;
}

Output

Enter two numbers 10
98.43
Sum of 10 and 98.43 is 108.43
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Number 1 : ");
int num1 = sc.nextInt();
System.out.print("Number 2 : ");
float num2 = sc.nextFloat();
float sum = num1 + num2;
System.out.println("Sum = "+sum);
}
}

Consider the below series :

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 using the formula (x/2)

Write a program to find the nth term in this 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 the value of the nth term no other characters /strings or message should be written to STDOUT.

For example if n=10,the 10 th term in the series is to be derived from the 9th term 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.

Code:

#include<stdio.h>

int main() {
//code
int n;
scanf(“%d”, &n);
if(n % 2 == 1)
{
int a = 1;
int r = 2;
int term_in_series = (n+1)/2;
int res = 2 * (term_in_series – 1);
printf(“%d “, res);
}
else
{
int a = 1;
int r = 3;
int term_in_series = n/2;

int res = term_in_series – 1;
printf(“%d “, res);
}

return 0;
}

Free Materials

We have a lots of free materials don’t worry. Check them out below.

TCS Coding Section used to be based on Command Line Argument based Coding Questions it is available no where else on the internet. We will try help you with learning command line argument based coding for TCS.

From this year there is no command Line programming but you have to use C, C++, Java, Python and Perl. We have the latest set of questions for the new pattern

Question 0

Find the nth term of the series.

1,1,2,3,4,9,8,27,16,81,32,243,….

#include <stdio.h>

#include <string.h>

int three(n)

{

int x,i;

for(i=0;i<100;i++)

{

x=pow(3,i);

if(i==n)

printf("%d",x);

}

}

int two(n)

{

int x,i;

for(i=0;i<100;i++)

{

x=pow(2,i);

if(i==n)

printf("%d",x);

}

}

int main()

{

int n;

scanf("%d",&n);

if(n%2==0)

three(n/2);

else

two(n/2+1);

}

Prime MOCK: Study Your TCS Coding Latest Prime MOCK Here

TCS Coding Questions and Solutions

Languages allowed – 

  1. C
  2. C++
  3. Java
  4. Perl
  5. Python

The platform will be eclipse based compiler. You can code on onlinegdb.com. All your codes working on this website would run perfectly in TCS compiler.

Paid Material

According to the latest syllabus of TCS

TCS Coding Round  2021 Questions in Test Pattern and Syllabus

  • Number of Questions – 2
  • Total time to Solve – 45 mins
  • Difficulty Level – 1 Easy Questions, 1 medium to difficult level question
  • Cut-off – Solve 1 question completely or partial output

Though command Line Programming is not there you should study it for C MCQ section as 1-2 MCQ would be there for command Line program.

TCS C Command Line Programming Basics

  • Keywords like getc, scanf, getch, getchar etc can not be used.
  • Instead we use command line arguments to fetch values.

Before reading further for TCS Coding Round Questions, I will suggest not to freak out if you don’t understand in first go. Read everything once and then when you read again things will start to make sense. It is the best resource on the internet to know about TCS command line Argument Type Questions and TCS C Programming Questions and Answers.

TCS Programming Test Facts and Questions

TCS coding test based facts and tricks, TCS Programming Questions, TCS Programming Test –
 
TCS Coding Round TopicsDifficultyTime to solve
LCM HCFMedium20 mins
Swapping and ReversalHard20 mins
Factorial and SeriesMedium20 mins
Operations on NumbersEasy20 mins
MiscMedium – Hard20 mins

TCS Coding Questions with Answers

Let us consider this, if you wanted to write a basic C program then you would’ve written a main function that would’ve looked like in compiler for TCS Coding Round Questions – 

int Main(){

// some code

}}

However in command line arguments we write like this – 

int main(int argc, char *argv[]){

  • argc – It is known as Argument Count and as clear from the name it stores the Count of number of Arguments.
  • argv[] – Pointer, contains location of all the values(arguments).
  • *argv[] – Array of values of all the arguments.
  • They are parameters/arguments supplied to the program when it is invoked.

Thus, now we have two things

  1. Total Count of number of Arguments.
  2. All the values/pointer location of arguments stored in an array.

Now, you will need one more thing i.e. atoi();

  • atoi(); – Converts string into int and atoi(argv[i]); will give the value of argument at ith location in int type format.

Now you can use an int val = atoi(argv[i]); to store the value and then print it with printf(); function.

Check out this video Below to learn how to Solve Command Line Programming.

Quick Facts

argv[0] contains the name, not the value so –

  • All for loops must start from i=1.
  • You must use the following condition

if(argc == 1){

// do nothing since, there are no arguments, maybe ask for arguments?

}else{

// code to apply logic and print values in TCS Coding Round Questions.

}

  • provided+1 +1 for file.exe
  • argv[argc] is a NULL pointer.
  • argv[0] holds the name of the program.
  • argv[1] points to the first command line argument and argv[n] points last argument.

TCS Programming Questions and Answers

TCS Coding Questions TypeNo of times askedDifficulty
String Reversals14Very High
Number Series39Medium
Matrix based51Medium
HCF/GCD Question66Medium
Command Line Arguments here – Read this properly.
 
// Program to print all value of
// command line argument
// once we get the value from command
// line we can use them to solve our problem.
#include<stdio.h>  // this is used to print the result using printf
#include<stdlib.h>  // this is used for function atoi() for converting string into int

// argc tells the number of arguments
// char *argv[] is used to store the command line 
//arguments in the pointer to char array i.e string format
int main(int argc, char *argv[])
{
  // means only one argument   exist that is file.exe
  if (argc == 1) {
     printf("No command line argument exist Please provide them first \n");
    return 0;
    } 

  else {
    int i;
    // actual arguments starts from index 1 to (argc-1)
    for (i = 1; i < argc; i++) {
      int value = atoi(argv[i]);
      // print value using stdio.h library's printf() function
      printf("%d\n", value);
    }
  return 0;
  }
}

TCS Programming Test FAQ's

What is the level of difficulty of the question asked in TCS programming round?

Ans. They are easy but you need to have good grip over basic C/C++ input/output or pattern based programs.

Logics like Recursion, For loops, If loops etc

What languages can we use in TCS Coding Round Questions?

Ans. In TCS Coding Round Questions currently you can only use C/C++ and Java for coding in TCS based Compiler that is mostly GCC type of compiler.

Is PrepInsta enough to prepare for TCS Coding Round and Questions asked in the exams?

Ans. Yes, it is the best resource out there in the internet to prepare for TCS Coding section paper.

Rules for TCS Coding Round Questions Section:

  • There is only one question for 20 minutes.
  • It has 10 attempts(We can compile only 10 times).
  • We must start our code from the scratch.
  • The coding platform is divided into two, one for writing the code and other for output. We should write the whole
    program.
  • We must only print exact output.
  • Output must not be re-framed by extra words.
  • If there is any error, the error will be shown in the output dialog box.
  • The errors are clearly mentioned.
  • If there are no errors, a message like “compiled successfully” will be printed.
  • Along with that they will mention four test cases are ‘passed’ or ‘failed’. They are indicated like private and public test cases. They have not mentioned what is the test case, which is difficult to understand.

Don’t Compile again and again since compiler takes 25 seconds and each time you compile 25 seconds will become lesser in the time you have to code in TCS Placement Papers Programming.

 

How to clear the TCS coding round?

Ans. First you must learn command line programming from our coding dashboard and then try sample questions given on the dashboard to know how to clear the tcs coding round  and TCS C Programming Questions and Answers

What are some other websites where we can find more questions?

Ans. You can find more questions on MyGeekMonkey website.

Disclaimer: 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

59 comments on “TCS Coding Questions with Answers”


    • HelpPrepInsta

      Hey Aarti, we have tried to provide all the kinds of questions in our free material, so that it can give you an idea about the question asked in the exam, but for practicing more and more questions we would suggest you to buy our Prime Course


    • HelpPrepInsta

      Hey Nilanjan, please scroll down a bit on the page, after the first few questions you’ll find a section paid material, where there’ll be links for different questions