TCS Ninja Coding Questions and Answers

TCS Ninja Coding Questions and answers
Time 30 mins
Questions 1
Negative Marking No
Languages C, C++, Java, Perl, Python

TCS Ninja Coding Questions and Answers 2019

TCS Ninja coding questions answers 2019 is available here.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 2019 and 2020.

  • For 2020 Passouts :
    • No Of Questions:- 1 Question
    • Time – 30 mins For
  • 2019 Passouts :
    • No Of Questions:- 1
    • Time – 20 mins

Get all the questions asked Today in TCS here – TCS Ninja Live Questions Dashboard BELOW

Online Classes

  1. Free Paid Materials also given
  2. Click here to join Online Live Class

PrepSter Study Material

In Online class you will get preparation paid materials access also, but if you just want materials then you can buy the ones below –

If you want to Register for Online Class Register here.

 

Minutes
Seconds

Free Material

TCS Ninja Coding Questions and Answers are graded by the TCS Server and not by the human, when you compile the program, the system checks for the following to give you marks –

a. Correct output on various test cases
b. Partial output at most obvious cases
c. logical error present in the codes
d. is the program compilation done.

There are a lot of free sections given above if you want to study more, you can buy TCS Coding Questions Paid materials which are basically command line questions.

Paid Material

Program 1

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 2

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 3

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 

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

Number Series Type 2

Find the nth term of the series.

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

Link to this Question

(TCS Ninja – Dec 2018 Slot 2)

#include<stdio.h>
#include<math.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);
}
#include <iostream>

using namespace std;

int main()
{ int n;
cout<<“Enter the value for n\n”;
cin>>n;
cout<<“1″<<” “<<“1″<<” “<<“2″<<” “;
if(n==3)
return 100;
int a[100],x;
a[0]=1;a[1]=1;a[2]=2;
int i=3;
while(i<=n){
if((a[i-2])%2!=0){
x=a[i-2]*3;
a[i]=x;
}
else{
x=a[i-2]*2;
a[i]=x;
}
i++;
}i=3;
while(i<=n){
cout<<a[i]<<” “;
i++;
}

return 0;
}
import java.util.ArrayList;
import java.util.Scanner;

public class NthTermInASeries {

public static void main(String[] args) {
// start!!!
// 1,1,2,3,4,9,8,27,16,81,32,243,….
int i, j, k = 1, m = 1, o = 0;
ArrayList<Integer> odd = new ArrayList<Integer>();
ArrayList<Integer> even = new ArrayList<Integer>();
ArrayList<Integer> result = new ArrayList<Integer>();
System.out.println(“enter the number”);
Scanner in = new Scanner(System.in);
int n = in.nextInt();
odd.add(1);
for (i = 1; i < n; i++) {
k = k * 2;
odd.add(k);

}
even.add(1);
for (j = 1; j < n; j++) {
m = (m * 3);
even.add(m);
}
System.out.println(odd);
System.out.println(even);

int f = 0;
int g = 0;
for (o = 0; o < 2 * n; o++) {
if (o % 2 == 0) {
result.add(odd.get(f));
f++;
} else {
result.add(even.get(g));
g++;
}
}
System.out.println(result);
System.out.println(result.get(n-1));
}

Program 5

Number Series Type 3

Ques. Find the nth term of the series.

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

(TCS Ninja – Sep 2 2018 slot 1)

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

 

or

#include
#include

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

#include <iostream>

using namespace std;

int main()
{ int n;
cout<<“Enter the value for n\n”;
cin>>n;
cout<<“1″<<” “<<“1″<<” “<<“2″<<” “;
if(n==3)
return 100;
int a[100],x;
a[0]=1;a[1]=1;a[2]=2;
int i=3;
while(i<=n){
if((a[i-2])%2!=0){
x=a[i-2]*3;
a[i]=x;
}
else{
x=a[i-2]*2;
a[i]=x;
}
i++;
}i=3;
while(i<=n){
cout<<a[i]<<” “;
i++;
}

return 0;
}
import java.util.ArrayList;
import java.util.Scanner;

public class NthTermInASeries {

public static void main(String[] args) {
// start!!!
// 1,1,2,3,4,9,8,27,16,81,32,243,….
int i, j, k = 1, m = 1, o = 0;
ArrayList<Integer> odd = new ArrayList<Integer>();
ArrayList<Integer> even = new ArrayList<Integer>();
ArrayList<Integer> result = new ArrayList<Integer>();
System.out.println(“enter the number”);
Scanner in = new Scanner(System.in);
int n = in.nextInt();
odd.add(1);
for (i = 1; i < n; i++) {
k = k * 2;
odd.add(k);

}
even.add(1);
for (j = 1; j < n; j++) {
m = (m * 3);
even.add(m);
}
System.out.println(odd);
System.out.println(even);

int f = 0;
int g = 0;
for (o = 0; o < 2 * n; o++) {
if (o % 2 == 0) {
result.add(odd.get(f));
f++;
} else {
result.add(even.get(g));
g++;
}
}
System.out.println(result);
System.out.println(result.get(n-1));
}

}

Program 6

Number Series Type 4

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

(TCS Ninja – Sep 2 2018 slot 2)

#include 
#include

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

or

#include
int main()
{
int i=3,n;
printf(“enter nth term”);
scanf(“%d”,&n);
int a[n+1];
a[1]=0;
a[2]=0;
while(i<=n)
{
if(i%2==0)
a[i]=a[i-2]+1;
else
a[i]=a[i-2]+2;
i++;
}
printf(“%d”,a[n]);
}

Program 7

String based Operation

Question

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

(TCS Ninja – Sep 3 2018 slot 1)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *str1=malloc(sizeof(char)*256);
char *str2=malloc(sizeof(char)*256);
char *str3=malloc(sizeof(char)*256);
printf(“ENter 3 words : “);
scanf(“%s%s%s”,str1,str2,str3);

int p1=strlen(str1);
int p2=strlen(str2);
int p3=strlen(str3);
for(int i=0;i<p1;i++)
{
if(str1[i]==’a’||str1[i]==’e’||str1[i]==’i’||str1[i]==’o’||str1[i]==’u’)
{
str1[i]=’$’;
}
}
for(int i=0;i<p2;i++)
{
if(str2[i]!=’a’ && str2[i]!=’e’ && str2[i]!=’i’ && str2[i]!=’o’ && str2[i]!=’u’)
{
str2[i]=’#’;
}
}
for(int i=0;i<p3;i++)
{
str3[i]=str3[i]-32;
}

printf(“\n%s”,str1);
printf(“\n%s”,str2);
printf(“\n%s”,str3);

return 0;

}

or

#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]==’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;
}
import sys
word1=input(“enter the first word”)
word2=input(“enter the second input”)
word3=input(“enter the third input”)
for ch in word1:
if ch in “aeiouAEIOU”:
word1=word1.replace(ch,”$”)

for ch in word2:
if ch in “aeiouAEIOU”:
word2=word2.replace(ch,”#”)

for ch in word3:
if ch in “abcdefghijklmnopqrstuvwxyz”:
word3=word3.upper()
print(word1,word2,word3)

Program 8

Number Series based Iteration

Consider the below series :

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

#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);
}
}
//C++ Program
#include<stdio.h>
using namespace std;
//main program
int main()
{
//initialising variables
int n;
cout<<"Enter position: ";
//user input
cin>>n;
//logic to find nth term
if(n==1||n==2)
cout<<0;
else if(n%2==0)
cout<<(n-1)/2;
else
cout<<n-1;
//logic ends
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);
System.out.print("Enter the value of n : ");
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(n+" element of the series is = "+b);
}
else
{
for(int i = 1 ; i < (n-2) ; i = i+2)
{
a = a + 2;
b = a / 2;
}
a = a + 2;
System.out.print(n+" element of the series is = "+a);
}
}
}

Program 9

Number Series based Operation

Question 1

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

Solution –

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

CORRECT CODE - 

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

Command Line Programs (Not asked anymore)

Command Line

Question 

Here is the program for gcd of two numbers using command line arguments check other sections for TCS on our website.

#include

int main(int a,char *b[])

{

int num1,num2,min,i,gcd=1;

if(a!=3){

printf("Enter two argument\n");

exit(1);

}

num1=atoi(b[1]);

num2=atoi(b[2]);

min=(no1<no2)?no1:no2;

for(i=1;i<=min;i++) {

if((num1%i)==0 && (num2%i)==0)

gcd=i;

}

printf("GCD of two number %d",gcd);

return 0;

}

Question 3

Binary to Decimal Conversion

#include
#include
int main(int argc, char *argv[])
{
if(argc==1)
{
printf("No Arguments ");
return 0;
}
else
{
int n;

n=atoi(argv[1]);
int binaryN[64];
int i=0;int j;
while(n>0)
{
//storing in binary array remainder of number
binaryN[i]=n%2;
n=n/2;
i++;
}
//printing reverse array
while(i)
{
printf("%d",binaryN[--i]);
}

return 0;
}
}

Question 4

Armstrong Number

#include
#include

int main(int argc,char *argv[])
{
int Given_number= atoi(argv[1]);
int num;
for(num=1; num<=Given_number; num++)
{
int a=num;
int s=0;
int r=0;

while(a>0)
{
s=a%10;
r=r+(s*s*s);
a=a/10;
}
if(r==num)
printf(" %d isarmstrong no \n", num);
}
}

Question 5

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
#include
int main(int argc, char * argv[])
{
 if(argc==1)
 {
 printf("No arguments");
 return 0;
 }
 else
 {
 int radius;
 float pi=3.14;
 float area;
 radius=atoi(argv[1]);
 area=pi*radius*radius;
 printf("%.2f",area);
 return 0;
 }
}

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.

Question 6

Command Line Program to check if a year is Leap Year or Not

#include
void main(int argc,char *argv[])
{
	int n;
	n=atoi(argv[1]);
	if(n%4==0)
	{
		if(n%100==0)
		{
			if(n%400==0)
			
				printf("Leap Year");
				else
				printf("Not Leap Year");
		}
		else
		printf("Leap Year");
   }
    else
    printf("Not Leap Year");
	getch();	
	
}

Question 7

Fibonacci Series

#include
#include

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

{

int n, first = 0, second = 1, next, c;

n = atoi(argv[1]);

printf("These are %d values in Fibonacci series are by PrepInsta:-\n",n);

for ( c = 0 ; c < n ; c++ )

{

if ( c <= 1 )

next = c;

else

{

next = first + second;

first = second;

second = next;

}

printf("%d\n",next);

}

return 0;

}

Question 8

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
#include
int main(int argc, char *argv[])
{
if (argc < 3)// as number of arguments needed are 2 and 1 is default arg.
{
printf(" Please provide values for both base and height \n");
return 0;
}
else
{
int base = atoi(argv[1]);
int height = atoi(argv[2]);
float area = 0.5*base*height;
printf("%.2f",area);
return 0;
}
}

Question 9

Palindrome Number

#include 

int main(int argc, char *argv[])
{
            int num, reverse_num=0,remainder,temp;
            num = atol(argv[1]);
            temp=num;
            while(temp!=0)
   {
            remainder=temp%10;
            reverse_num=reverse_num*10+remainder;
            temp/=10;
   }
   if(reverse_num==num)
            printf("%d is a palindrome number",num);
   else
            printf("%d is not a palindrome number",num);
   return 0;
} 

Question 10

Decimal to Binary

#include
#include
int main(int argc, char *argv[])
{
if(argc==1)
{
printf("No Arguments ");
return 0;
}
else
{
int n;

n=atoi(argv[1]);
int binaryN[64];
int i=0;int j;
while(n>0)
{
//storing in binary array remainder of number
binaryN[i]=n%2;
n=n/2;
i++;
}
//printing reverse array
while(i)
{
printf("%d",binaryN[--i]);
}

return 0;
}
}

Question 11

Binary to Octal

#include

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

{

ong int n,r,c,b=1,s=0;

n=atoi(argv[1]);

c=n;

while(c!=0)

{

r=c%10;

s=s+r*b;

c=c/10;

b=b*2;

}

printf("%lo",s);

getch();

}

Question 12

Decimal to Octal

#include

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

{

int n,s=0,b=1,r;

n=atoi(argv[1]);

int c=n;

while(c>0)

{

r=c%8;

s=s+r*b;

c=c/8;

b=b*10;

}

printf("%d",s);

getch();

}

Question 13

String Palindrome

#include

#include

void isPalindrome(char str[])

{

int l = 0;

int h = strlen(str) - 1;

while (h > l)

{

if (str[l++] != str[h--])

{

printf("%s is Not Palindromen", str);

return;

}

}

printf("%s is palindromen", str);

}

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

{

int i,k;

int strsize = 0;

for (i=1; i<argc; i++) {

strsize += strlen(argv[i]);

if (argc > i+1)

strsize++;

}

char *cmdstring;

cmdstring = malloc(strsize);

cmdstring[0] = '\0';

for (k=1; k<argc; k++) {

strcat(cmdstring, argv[k]);

if (argc > k+1)

strcat(cmdstring, " ");

}

isPalindrome(cmdstring);

}

Question 14

#include

#include

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

{

if(argc==1)

{

printf("No Arguments");

return 0;

}

else

{

int n,reverseNumber,temp,rem;

n=atoi(argv[1]);

temp=n;

reverseNumber=0;

while(temp)

{

rem=temp%10;

reverseNumber=reverseNumber*10+rem;

temp=temp/10;

}

printf("%d",reverseNumber);

return 0;

}

}

Question 15

Square Root without using Math.h

#include

#include

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

{

if(argc==1)

{

printf("No arguments");

return 0;

}

else

{

int n;

n=atoi(argv[1]);

float i=0.00;

while(i*i<=n)

{

i=i+0.001;

}

i=i-0.001;

printf("%.2f",i);

}

}

Question 16

Average of two numbers

#include

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

{

int sum = 0,i = 1,count = 0;

if(argc == 1)

{

printf("Enter the number \n");

exit(1);

}

count = argc - 1;

while (i <= count )

{

sum += atoi (argv[i]) ;

i++;

}

printf("Avg of the numbers.%d\n", sum/count);

}

Question 17

Greatest of two Numbers

#include

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

{

int c[10];

int i,temp,j,greatest;

j = 0;

for(i=1; i<argc; i++)

{

temp = atoi(argv[i]);

c[j] = temp;

j++;

}

greatest = c[0];

for (i = 0; i < 10; i++) {

if (c[i] > greatest) {

greatest = c[i];

}

}

printf("Greatest of ten numbers is %d", greatest);

return 0;

}

Question 18

Write a Program to print whether the given alphabet is vowel or consonant Solution:

#include

int main()

{

// 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 19

Write a program to Check whether a given number is a prime number or not Solution:

#include

#include

int main()

{

int n, i, flag = 0; //

printf("Enter a positive integer: ");

scanf("%d",&n);

for(i=2; i<=sqrt(n); ++i) {

// condition for nonprime 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 20

Write a program to change the case of the given alphabet and print. Solution:

#include 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 21

Given an array and a number (say s), find whether any two elements in the array whose sum is “s”. Solution:

#include 
#include

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. Solution:

#include

#define MAX_SIZE 100

#define MAX_CHARS 26

int main()

{

int i;

//Get a sentence

char str[MAX_SIZE];

scanf("%[^\n]s", str);

// Init Freq stoting array

int freq[MAX_CHARS];

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

{ freq[i]=0; }

//frequency of each character is counted

for(i=0; str[i]= !='\0';i++){

int isalphabet=0 , offset;

if(str[i]>= 'a' && str[i] <= 'z') {

isAlphabet = 1;

offset = str[i] - 'a';

}

else if(str[i] >= 'A' && str[i] <= 'Z')

{

isAlphabet = 1;

offset = str[i] - 'A';

}

if(isAlphabet == 1)

{

freq[offset] += 1;

}

}

// If two characters occurred the same number of time then

// print lowest ASCII value character. int max_index = 0; for(i=0; i<max_chars;i++)

{

if(freq[i] > freq[max_index])

{

max_index = i;

}

}

int max_repeated_char = 'a' + max_index;

printf("%c", max_repeated_char);

return 0;

}
The Words Like “Placement Papers” and “Previous Year Papers” are used here for Google Search Purposes only and may not be. All these questions could be freely available on the internet, we are only charging students for the PrepInsta’s Mock Test experiences and Analytics as well as preparation for the exam. Prepinsta does not guarantee any recurrence of the questions in the exam however we believe that from our practise questions the exam should atleast be similar in pattern as per syllabus or difficulty. These are only practise mock questions. PrepInsta has compiled these from various internet sources and made them as per mock experience for students ease and are offering analytics as per performance
Summary
Review Date
Reviewed Item
TCS Ninja Coding Questions
Author Rating
51star1star1star1star1star

Please Login/Signup to comment

7 comments on “TCS Ninja Coding Questions and Answers”


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