Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

TCS Ninja Coding Questions and Answers 2022

TCS Ninja Coding Questions and answers
Time45 mins
Questions2
Negative MarkingNo
LanguagesC, C++, Java, Perl, Python

TCS Ninja Coding Questions and Answers 2022

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.

  • No Of Questions:- 2 Question
  • Time – 45 mins 

TCS Coding Question Day 1 Slot 1 – Question 1

A chocolate factory is packing chocolates into the 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

Output:

  • 6 1 8 2 0 0
#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]<<" ";
}
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] + " ");
}
}
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=" ")

TCS Coding Question Day 1 Slot 1 – Question 2

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

#include <bits/stdc++.h>
using namespace std;

int main()
{
int n; cin>>n;
int k=(1<<(int)floor(log2(n))+1)-1;
cout<<(n^k);
}
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);
}
}
import math
n=int(input())
k=(1<<int(math.log2(n))+1)-1
print(n^k)

TCS Coding Question Day 1 Slot 2 – Question 1

Airport security officials have confiscated several item of the passengers at the security check point. 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 represent 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();

int countZero=0,countOne=0,countTwo=0;
for(int i=0;i<n;i++)
{
if(arr[i]==0)
countZero++;
else if(arr[i]==1)
countOne++;
else if(arr[i]==2)
countTwo++;
}
int j=0;
while(countZero>0)
{
arr[j++]=0;
countZero--;
}

while(countOne>0)
{
arr[j++]=1;
countOne--;
}

while(countTwo>0)
{
arr[j++]=2;
countTwo--;
}

for(int i=0;i<n;i++)
System.out.print(arr[i]+" ");
}
}

TCS Coding Question Day 1 Slot 2 – Question 2

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


Output :

34

import java.util.*;
class Solution
{
public static int solve (int arr[], int n)
{
PriorityQueue <Integer> queue = new PriorityQueue<Integer>();

for (int i = 0; i < n; i++)
queue.add (arr[i]);

int sum = 0, temp1, temp2;

while (queue.size () >= 2)
{
temp1 = queue.poll ();
temp2 = queue.poll ();
sum += temp1 + temp2;
queue.add (temp1 + temp2);
}
return sum;
}

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 ();

System.out.println (solve (arr, n));
}
}

TCS Coding Question Day 2 Slot 1 – Question 1

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]).

#include <bits/stdc++.h>
using namespace std;

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;
}
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);
}
}
n = int (input ()) 
L =[] 
sum = 0 
c = 0 
for _ in range (n):
    a = (input ()) 
    if a:
      sum += c 
    else:
      c += 1 
print (sum)

TCS Coding Question Day 2 Slot 1 – Question 2

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

ValueTotal ValueWeightTotal Weight

Valid (total weight(<C)

Invalid (total weight>C)

10+455515+2035Valid
10+607015+3045Valid
10+9010015+4055Valid
45+6010520+3050Valid
45+9013520+4060Valid
60+9015020+4070Valid
10+45+6011520+4065Valid
10+60+9016020+4085Invalid
10+45+9014520+4075Valid

 

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)

Constraints:

  • 0<=N<=10
  • 0 <= C<=500
  • 1<=V[i]<=500
import java.util.*;
class Solution
{
public static int solve(int c,int w[],int val[],int n)
{
if(n==0 || c==0)
return 0;
if(c<w[n-1])
return solve(c,w,val,n-1);
else
return Math.max(solve(c,w,val,n-1),val[n-1]+solve(c-w[n-1],w,val,n-1));
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int c=sc.nextInt();
int v[]=new int[n];
int w[]=new int[n];

for(int i=0;i<n;i++)
v[i]=sc.nextInt();
for(int i=0;i<n;i++)
w[i]=sc.nextInt();
System.out.println(solve(c,w,v,n));
}
}

Program 1

Word is the Key

Word is the Key 💖 (Link to this question)

(TCS Ninja – Aug 2020 Slot 1)

One programming language has the following keywords that cannot be used as identifiers:

break, case, continue, default, defer, else, for, func, goto, if, map, range, return, struct, type, var

Write a program to find if the given word is a keyword or not

Test cases

Case 1

  • Input – defer
  • Expected Output – defer is a keyword

Case 2

  • Input – While
  • Expected Output – while is not a keyword
#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;
}
#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;
}
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")
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)

Program 2

Sweet Seventeen

Sweet Seventeen 💖 (Link to this question)

(TCS Ninja – Aug 2019 Slot 2)

Given a maximum of four digit to the base 17 (10 – A, 11 – B, 12 – C, 13 – D … 16 – G} as input, output its decimal value.

Test Cases

Case 1

  • Input – 1A
  • Expected Output – 27

Case 2

  • Input – 23GF
  • Expected Output – 10980
#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;
}
#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;
}
'''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))
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);
	}
}

Program 3

Oddly Even

The Oddly even 💖 (Link to this question)

(TCS Ninja – Aug 2019 Slot 3)

Problem

Given a maximum of 100 digit numbers as input, find the difference between the sum of odd and even position digits

Test Cases

Case 1

  • Input: 4567
  • Expected Output: 2

Explanation : Odd positions are 4 and 6 as they are pos: 1 and pos: 3, both have sum 10. Similarly, 5 and 7 are at even positions pos: 2 and pos: 4 with sum 12. Thus, difference is 12 – 10 = 2

Case 2

  • Input: 5476
  • Expected Output: 2

Case 3

  • Input: 9834698765123
  • Expected Output: 1
#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 even

    return 0;
}
#include <iostream>
#include <string.h>
#include <stdlib.h>

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 even return 0; }
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
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));
	}
}

Program 4

Position prediction

The Sholka Problem 💖 (Link to this question)

(TCS Ninja – Aug 2019 Slot 4)

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.

Test Cases

Case 1

  • Input : 3
  • Expected Output :-20 20

Case 2

  • Input: 4
  • Expected Output: -20 -20

Case 3

  • Input : 5
  • Expected Output : 30 -20

Case 4

  • Input : 7
  • Expected Output : 90 -20
Our hoary culture had several great persons since time (1)
#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;
}
#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;
}
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);
  }

}
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)
$n=<>;
$n=$n*1;
$c=0;
$dis=10;
$x=0;
$y=0;
for(my $i=0;$i<$n;$i++)
{
    if($c==0)
    {
        $x=$x+$dis;
        $c=1;
        $dis=$dis+10;
    }
    elsif($c==1)
    {
        $y=$y+$dis;
        $c=2;
        $dis=$dis+10;
    }
    elsif($c==2)
    {
        $x=$x-$dis;
        $c=3;
        $dis=$dis+10;
        }
     elsif($c==3)
    {
        $y=$y-$dis;
        $c=4;
        $dis=$dis+10;
        }
    elsif($c==4)
    {
        $x=$x+$dis;
        $c=0;
        $dis=$dis+10;
    }
}
print $x;
print " ";
print $y;

Program 5

Leap Year or not

Program to check if a year is Leap Year or not 💖

(TCS Ninja – June 2019 Slot 1)

#include<stdio.h>

int main()

{

  int year;

  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
}
#include
using namespace 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";
   return 0; 
}

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 −

import java.util.Scanner;
public class Demo {

    public static void main(String[] args) {

    	int year;
    	Scanner scan = new Scanner(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.");
        else
            System.out.println(year + " is not a Leap Year.");
    }
}
# 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 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?

(TCS Ninja – June 2019 Slot 2)

#include<bits/stdc++.h>
using namespace std;

void prime(int num){
int count=0;
for(int i=2;i<num;i++){
if(num%i==0){
count++;
break;
}
}
if(count==0){
cout<<"prime"<<endl;
}
else{
cout<<"Not Prime"<<endl;
}
}

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;
}
#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";
}
}
/* 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.

Link to this Question

(TCS Ninja – Dec 2018 Slot 1)

#include <stdio.h>

int a1(int x);
int a2(int y);

void main()
{
int n;
scanf("%d",&n);
if(n%2==0)
a1(n/2);
else
a2(n/2+1);
}

int a1(int x)
{
int s=0;
for(int i=0;i<x-1;i++)
{
s=s+6;
}
printf("%d",s);
}

int a2(int x)
{
int s=0;
for(int i=0;i<x-1;i++)
{
s=s+7;
}
printf("%d",s);
}
//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;
}
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]);

}
}
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))

Program 8

Number Series Type 2

Problem

Question. Find the nth term of the 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.

Link to this Question

Test Case 1

  • Input- 16
  • Expected Output – 2187

Test Case 2

  • Input- 13
  • Expected Output – 64

(TCS Ninja – Dec 2018 Slot 2)

Explanation

1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243,64, 729, 128, 2187 can represented as :

  • 2(0), 3(0),2(1), 3(1),2(2), 3(2),2(3), 3(3),2(4), 3(4),2(5), 3(5),2(6), 3(6) ….

There are two consecutive sub GP’s at even and odd positions

  • (GP-1) At Odd Positions (Powers of 2) – 1, 2, 4, 8, 16, 32, 64, 128
  • (GP-2) At Even Positions (Powers of 3) – 1, 3, 9, 27, 81, 243, 729, 2187

Clearly, for calculating Nth position value

  • If N is Even, Find (N/2) position in sub GP – 2
  • If N is Odd, Find (N/2 + 1) position in sub GP – 1
#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 3
    if(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;
}
#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 3 if(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; }
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
num = int(input())
if(num%2==0):
num = num // 2
print(3**(num-1))
else:
num = num // 2 + 1
print(2**(num-1))

Program 9

String based Operation

Question

Link to this Question

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*[email protected]

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

Test Cases

Case 1

Input

  • how
  • are
  • you

Expected Output : h*[email protected]

Case 2

Input

  • how
  • 999
  • you

Expected Output : h*w999YOU

(TCS Ninja – Sep 3 2018 slot 1)

#include<stdio.h>
#include<conio.h>
#include<string.h>

int main()
{
int i;
char a[100],b[100],c[100];

    scanf("%s",a);
    scanf("%s",b);
    scanf("%s",c);

    for(i=0;a[i]!='\0';i++)
    {
        if(a[i]=='a'||a[i]=='e'||a[i]=='i'||a[i]=='o'||a[i]=='u'||a[i]=='A'||a[i]=='E'||a[i]=='I'||a[i]=='O'||a[i]=='U')
            a[i]='*';
    }

    for(i=0;b[i]!='\0';i++)
    {
if((b[i]>='a'&&b[i]<='z') || (b[i]>='A'&&b[i]<='Z')) if(!(b[i]=='a'||b[i]=='e'||b[i]=='i'||b[i]=='o'||b[i]=='u'||b[i]=='A'||b[i]=='E'||b[i]=='I'||b[i]=='O'||b[i]=='U')) b[i]='@'; } for(i=0;c[i]!='\0';i++) { if(c[i]>='a'&&c[i]<='z') c[i]=c[i]-32; } printf("%s%s%s",a,b,c); return 0; }
#include<iostream>
#include<string.h>

using namespace std;
int main() { int i; char a[100],b[100],c[100]; cin >> a; cin >> b; cin >> c; for(i=0;a[i]!='\0';i++) { if(a[i]=='a'||a[i]=='e'||a[i]=='i'||a[i]=='o'||a[i]=='u'||a[i]=='A'||a[i]=='E'||a[i]=='I'||a[i]=='O'||a[i]=='U') a[i]='*'; } for(i=0;b[i]!='\0';i++) {
if((b[i]>='a'&&b[i]<='z') || (b[i]>='A'&&b[i]<='Z')) if(!(b[i]=='a'||b[i]=='e'||b[i]=='i'||b[i]=='o'||b[i]=='u'||b[i]=='A'||b[i]=='E'||b[i]=='I'||b[i]=='O'||b[i]=='U')) b[i]='@'; } for(i=0;c[i]!='\0';i++) { if(c[i]>='a'&&c[i]<='z') c[i]=c[i]-32; } cout << a << b<< c; return 0; }

Program 10

Number Series based Iteration

Problem

Consider the below series :

0, 0, 2, 1, 4, 2, 6, 3, 8, 4, 10, 5, 12, 6, 14, 7, 16, 8

(Link to this question)

#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))

Program 11

Number Series based Operation

Question 11

Consider the below series:
1, 2, 1, 3, 2, 5, 3, 7, 5, 11, 8, 13, 13, 17…..

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

#include<stdio.h>

void fibo(int);
void prime(int);
main()
{

    int n,e;
    scanf("%d",&n);
    e=n/2;
    if(n%2==0)
        prime(e);
    else
        fibo(e+1);

}

void prime(int n)

    {
        int i,j,no,flag=0,count=0;
        for(i=1;i<=100;i++)
             {
                flag=0;
                 for(j=2;j<=i/2;j++)
                         {
                            if(i%j==0)
                               flag=0;
                            else
                                flag=1;
                         }
                  if(flag==1)
                      count++;
                  if(count==n)
                     {
                          printf("%d\n",i);
                          break;
                     }
          }
    }

void fibo(int n)

    {
        int n0=0,n1=1,n2,i;
        for(i=3;i<=n;i++)
            {
                n2=n0+n1;
                n0=n1;
                n1=n2;
            }
        printf("%d",n2);
    }

Other Important Programs

Misc

Question 

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.

(TCS Ninja – June 2019 Slot 3)

#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;
    }
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);
          }
    }

Paid Material

According to the latest syllabus of TCS

Based on Previous Year Patterns

Command Line Programs (Not asked anymore)

Command Line

Question 1:

Finding GCD of two numbers

// 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>
int main()
{ 
      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>
int main()
{
      //initialization of Year
     int year;

      //to take user input
      printf("Enter Year for find leap year or not : ");
     scanf("%d",&year);

       //we use this statement for check leap year 
     if(((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>
int main()
{
      //To initialize variables 
      int 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 length
      for(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>
int main()
{
   //for initialize a variables
    long number, dec_num, rem, base = 1, bin = 0, count = 0;
    //To insert a number
    printf("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;
    }
   //display
    printf("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>  

int main()

{
 //For initialize variables
    long int binary_num, octal_num = 0, j = 1, rem;

 //Inserting the binary number from the user

    printf("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> 

int main()
 {
//Variable initialization
     long dec_num, rem, quotient;     
     int i, j, octalno[100];
//Taking input from user
     printf("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[] array
     while (quotient!=0)
       {
        octalno[i++]=quotient%8;
        quotient=quotient/8;
       }
//Printing the octalno [] in reverse order
     printf("\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>
int main()
{
    //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 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 show the user value
      printf("Given number = %d\n",store);

      //after reverse show numbers
       printf("Its reverse is = %d\n", rev);

     return 0;
}

Question 14

Square Root without using Math.h

#include <stdio.h>

    double SqrtNumber(double num)
    {
             double min=0; 
             double max=num;
             double temp=0;                   
             int nCount = 50;

        while(nCount != 0)
        {
               temp=(min+max)/2;
               if(temp*temp==num) 
               {
                       return temp;
               }
               else if(temp*temp > num)

               {
                       max = temp;
               }
               else
               {
                       min = temp;
               }
        nCount--;
     }
        return temp;
     }

     int main()
     {
     double num;
     printf("Enter the number\n");
     scanf("%lf",&num);

     if(num < 0)
     {
     printf("Error: Negative number!");
     return 0;
     }

     printf("Square roots is: %f",SqrtNumber(num));
     return 0;
     }

Question 15

Average of two numbers

#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 greater
  if(no1 > no2)
     printf("%d is greatest",no1);
	
  //where number 2 is greater
  else if(no2 > no1)
    printf("%d is greatest",no2);	
        
  //for both are equal
  else
     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;
}

Paid Material

According to the latest syllabus of TCS

Based on Previous Year Patterns

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

10 comments on “TCS Ninja Coding Questions and Answers 2022”


  • sucharita.700

    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))


  • Pritam

    Please share the Code of WaterMark Solution Problem of TCS phase 2 test slot 1 on 1st sep 2019.


    • Prep Insta

      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.


  • Rohit Sharma

    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


  • Arun kumar

    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 .


  • Shreya

    Thank you sir. I got similar questions in the exam as well. Not the same question but the pattern was same.


  • Ali

    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?