0% found this document useful (0 votes)
335 views255 pages

C Programming Interview Questions Guide

This document contains C programs for various concepts that are commonly asked during coding interviews. It includes programs to check number properties like perfect, Armstrong, prime; mathematical operations like series, factorization; string, matrix and file manipulation; recursion; sorting; searching; and calculating areas and volumes of shapes. The programs cover fundamental C concepts and are intended to help candidates prepare for technical interviews.

Uploaded by

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

C Programming Interview Questions Guide

This document contains C programs for various concepts that are commonly asked during coding interviews. It includes programs to check number properties like perfect, Armstrong, prime; mathematical operations like series, factorization; string, matrix and file manipulation; recursion; sorting; searching; and calculating areas and volumes of shapes. The programs cover fundamental C concepts and are intended to help candidates prepare for technical interviews.

Uploaded by

Pranay Mudhiraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 255

THIS BOOK CONSISTS OF AS MORE AS POSSIBLE C-PROGRAMS

THAT ARE CONTAINING ALL BASICS AND THOSE ARE REQUIRED FOR
INTERVIEW THIS MIGHT BE HELPFUL IN MANY WAYS TO CRACK
CODING TEST OR TECHNICAL ROUND INTERVIEW . ~K V S NAIDU

THIS DOCUMENT CONTAINS AS FOLLOWS

 Frequently asked c programs in interview


1. Write a c program to check given number is perfect number
or not.
2. Write a c program to check given number is Armstrong
number or not.
3. Write a c program to check given number is prime number or
not.
4. Write a c program to check given number is strong number or
not.
5. C program to check a number is odd or even.
6. Write a c program to check given number is palindrome
number or not.
8. Write a c program to check given string is palindrome number
or not.
7. Write a c program to solve quadratic equation.
8. Write a c program to print Fibonacci series of given range.
9. Write a c program to get factorial of given number.
10. Write a c program for Floyd’s triangle.
11. Write a c program to print Pascal triangle.
12. Write a c program to generate multiplication table.
13. Write a c program to print ASCII value of all characters.
14. C program to print hello world without using semicolon
15. Write a c program which produces its own source code as its
output

1 | C-PROGRAMMING BY K V S N
C program with numbers

1. Write a c program to reverse any number.


2. Write a c program to find out sum of digit of given number.
3. Write a c program to find out power of number.
4. Write a c program to add two numbers without using addition
operator.
5. Write a c program to subtract two numbers without using
subtraction operator.
6. Write a c program to find largest among three numbers using
binary minus operator.
7. Write a c program to find largest among three numbers using
conditional operator
8. Write a c program to find out generic root of any number.
9. Write a c program to find out prime factor of given number.
10. Write a c program to find out NCR factor of given number.
11. How to convert string to int without using library functions
in c
12. Program in c to print 1 to 100 without using loop
13. C program for swapping of two numbers
14. Program to find largest of n numbers in c
15. Split number into digits in c programming
16. C program to count number of digits in a number
Recursion

Example of recursion in c programming


L.C.M and H.C.F.
1. Write a c program to find out L.C.M. of two numbers.
2. Write a c program to find out H.C.F. of two numbers.
2 | C-PROGRAMMING BY K V S N
3. Write a c program to find out G.C.D. of two numbers.
Swapping
1. Write a c program to swap two numbers.
2. Write a c program to swap two numbers without using third
variable.
3. Write a c program for swapping of two arrays.
4. Write a c program for swapping of two string.
Conversion ( Number System )
1. Write a c program to convert decimal number to binary
number.
2. Write a c program to convert decimal number to octal
number.
3. Write a c program to convert decimal number
to hexadecimal number.
4. Write a c program to convert octal number to binary number.
5. Write a c program to convert octal number to decimal
number.
6. Write a c program to convert octal number to hexadecimal
number.
7. Write a c program to convert hexadecimal number to binary
number.
8. Write a c program to convert hexadecimal number to octal
number.
9. Write a c program to convert hexadecimal number to decimal
number.
10. Write a c program to convert binary number to octal number.
11. Write a c program to convert binary number to decimal
number.

3 | C-PROGRAMMING BY K V S N
12. Write a c program to convert binary number to hexadecimal
number.
13. C program for addition of binary numbers .
14. C program for multiplication of two binary numbers.
15. C program fractional binary conversion from decimal.
16. C program for fractional decimal to binary fraction
conversion.
17. C program to convert decimal number to roman.
18. C program to convert roman number to decimal number.
19. C program to convert each digits of a number in words
20. C program to convert currency or number in word.

Conversion ( Unit )
1. C program for unit conversion.
String
1. Write a c program to convert the string from upper case to
lower case.
2. Write a c program to convert the string from lower case to
upper case.
3. Write a c program to delete the all consonants from given
string.
4. Write a c program to count the different types of characters in
given string.
5. Write a c program to sort the characters of a string.
6. Write a c program for concatenation two strings without using
string.h header file.
7. Write a c program to find the length of a string using pointer.
8. Write a c program which prints initial of any name.

4 | C-PROGRAMMING BY K V S N
9. Write a c program to print the string from given character.
10. Write a c program to reverse a string
11. Reverse a string using recursion in c
12. String concatenation in c without using strcat
13. How to compare two strings in c without using strcmp
14. String copy without using strcpy in c
15. Convert a string to ASCII in c
Matrix
1. Write a c program for addition of two matrices.
2. Write a c program for subtraction of two matrices
3. Write a c program for multiplication of two matrices.
4. Write a c program to find out sum of diagonal element of a
matrix.
5. Write a c program to find out transport of a matrix.
6. Write a c program for scalar multiplication of matrix.
7. C program to find inverse of a matrix
8. Lower triangular matrix in c
9. Upper triangular matrix in c
10. Strassen's matrix multiplication program in c
11. C program to find determinant of a matrix
File
1. Write a c program to open a file and write some text and close
its.
2. Write a c program to delete a file.
3. Write a c program to copy a file from one location to other
location.
4. Write a c program to copy a data of file to other file.
5. Write a c program which display source code as a output.

5 | C-PROGRAMMING BY K V S N
6. Write a c program which writes string in the file.
7. Write a c program which reads string from file.
8. Write a c program which writes array in the file.
9. Write a c program which concatenate two file and write it
third file.
10. Write a c program to find out size of any file.
11. Write a c program to know type of file.
12. Write a c program to know permission of any file.
13. Write a c program to know last date of modification of any
file.
14. Write a c program to find size and drive of any file.
Complex number

1. Complex numbers program in c


2. Write a c program for addition and subtraction of two
complex numbers.
3. Write a c program for multiplication of two complex
numbers.
4. Write a c program for division two complex numbers.
Series
1. Write a c program to find out the sum of series 1 + 2 + …. +
n.
2. Write a c program to find out the sum of series 1^2 + 2^2 +
…. + n^2.
3. Write a c program to find out the sum of series 1^3 + 2^3 +
…. + n^3.
4. Write a c program to find out the sum of given A.P.
5. Write a c program to find out the sum of given G.P.
6. Write a c program to find out the sum of given H.P.
6 | C-PROGRAMMING BY K V S N
7. Write a c program to find out the sum of series 1 + 2 + 4 + 8
… to infinity.
Array
1. Write a c program to find out largest element of an array.
2. Write a c program to find out second largest element of an
unsorted array.
3. Write a c program to find out second smallest element of an
unsorted array.
4. Write a c program which deletes the duplicate element of an
array.
5. Write a c program for delete an element at desired position in
an array.
6. Write a c program for insert an element at desired position in
an array.
7. C program to find largest and smallest number in an array
Sorting
1. Write a c program for bubble sort.
2. Write a c program for insertion sort.
3. Write a c program for selection sort.
4. Write a c program for quick sort.
5. Write a c program for heap sort.
6. Write a c program for merge sort.
7. Write a c program for shell sort.
Recursion
1. Write a c program to find factorial of a number using
recursion.

7 | C-PROGRAMMING BY K V S N
2. Write a c program to find GCD of a two numbers using
recursion.
3. Write a c program to find out sum digits of a number using
recursion.
4. Write a c program to find power of a number using function
recursion.
5. Write a c program to reverse any number using recursion.
Size of data type
1. Write a c program to find the size of int without using sizeof
operator.
2. Write a c program to find the size of double without using
sizeof operator.
3. Write a c program to find the size of structure without using
sizeof operator.
4. Write a c program to find the size of union without using
sizeof operator.
Using pointer
1. Write a c program for concatenation two string using pointer.
Searching
1. Write a c program for linear search.
2. Write a c program for binary search.
3. Write a c program for binary search using recursion.
Area and volume
1. Write a c program to find the area of circle.

8 | C-PROGRAMMING BY K V S N
2. Write a c program to find the area of any triangle.
3. Write a c program to find the area of equilateral triangle.
4. Write a c program to find the area of right angled triangle.
5. Write a c program to find the area of rectangle.
6. Write a c program to find the area of trapezium.
7. Write a c program to find the area of rhombus.
8. Write a c program to find the area of parallelogram.
9. Write a c program to find the volume and surface area of
cube.
10. Write a c program to find the volume and surface area of
cuboids.
11. Write a c program to find the volume and surface area
of cylinder.
12. Write a c program to find the surface area and volume of a
cone.
13. Write a c program to find the volume and surface area of
sphere.
14. Write a c program to find the perimeter of a circle, rectangle
and triangle.

C program with very large numbers

1. Write a c program to find factorial of 100 or very large


numbers
2. Write a c program to multiply the two very large number
(larger the long int)
3. Write a c program for division of large number (larger than
long int)
4. C code for modular division of large number.
5. C code for division of large number.
6. C code for power of large numbers.
9 | C-PROGRAMMING BY K V S N
Other

1. C program for ATM transaction.


2. Write a c program which passes one dimension array to
function.
3. Write a c program which passes two dimension array to
function.
4. Write a c program which takes password from user.
5. Write a scanf function in c which accept sentence from user.
6. Write a scanf function in c which accept paragraph from user.
7. Write a c program to print the all prime numbers between 1 to
300.
8. Write a c program which passes structure to function.
9. Palindrome in c without using string function
10. How to get the ASCII value of a character in c
11. C program to get last two digits of year
12. C program without main function

10 | C-PROGRAMMING BY K V S N
///////**********************PROGRAMS BY K V SUBBA NAIDU*********************////////////

PERFECT NUMBER

Definition of perfect number or What is perfect number?

Perfect number is a positive number which sum of all


positive divisors excluding that number is equal to that
number. For example 6 is perfect number since divisor
of 6 are 1, 2 and 3. Sum of its divisor is
1 + 2+ 3 =6

Note: 6 is the smallest perfect number.

Next perfect number is 28 since 1+ 2 + 4 + 7 + 14 = 28


Some more perfect numbers: 496, 8128

Code 1:
1. C program to check perfect number

#include<stdio.h>
int main(){
int n,i=1,sum=0;

printf("Enter a number: ");


scanf("%d",&n);

while(i<n){
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
printf("%d is a perfect number",i);
else
printf("%d is not a perfect number",i);

return 0;
}

11 | C-PROGRAMMING BY K V S N
Code 2:

#include<stdio.h>
int main(){
int n,i,sum;
int min,max;

printf("Enter the minimum range: ");


scanf("%d",&min);

printf("Enter the maximum range: ");


scanf("%d",&max);

printf("Perfect numbers in given range is: ");


for(n=min;n<=max;n++){
i=1;
sum = 0;

while(i<n){
if(n%i==0)
sum=sum+i;
i++;
}

if(sum==n)
printf("%d ",n);
}

return 0;
}

12 | C-PROGRAMMING BY K V S N
Code 3:
3. C program to print perfect numbers from 1 to 100

#include<stdio.h>
int main(){
int n,i,sum;

printf("Perfect numbers are: ");


for(n=1;n<=100;n++){
i=1;
sum = 0;

while(i<n){
if(n%i==0)
sum=sum+i;
i++;
}

if(sum==n)
printf("%d ",n);
}

return 0;
}

Output:
Perfect numbers are: 6 28

13 | C-PROGRAMMING BY K V S N
*************************************************************************************
ARMSTRONG NUMBER

Definition of Armstrong number or what is an Armstrong


number:
Definition according to c programming point of view:

THOSE NUMBERS WHICH SUM OF THE CUBE OF ITS DIGITS IS


EQUAL TO THAT NUMBER ARE KNOWN AS ARMSTRONG NUMBERS. FOR
EXAMPLE 153 SINCE 1^3 + 5^3 + 3^3 = 1+ 125 + 9 =153
OTHER ARMSTRONG NUMBERS: 370,371,407 ETC.
IN GENERAL DEFINITION:
THOSE NUMBERS WHICH SUM OF ITS DIGITS TO POWER OF
NUMBER OF ITS DIGITS IS EQUAL TO THAT NUMBER ARE KNOWN
AS ARMSTRONG NUMBERS.
EXAMPLE 1: 153
TOTAL DIGITS IN 153 IS 3
AND 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
Example 2: 1634
Total digits in 1634 is 4
And 1^4 + 6^4 + 3^4 +4^4 = 1 + 1296 + 81 + 64 =1634
Examples of Armstrong numbers: 1, 2, 3, 4, 5, 6, 7, 8,
9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727,
93084, 548834, 1741725

14 | C-PROGRAMMING BY K V S N
Code 1:
#include<stdio.h>
int main(){
int num,r,sum=0,temp;

printf("Enter a number: ");


scanf("%d",&num);

temp=num;
while(num!=0){
r=num%10;
num=num/10;
sum=sum+(r*r*r);
}
if(sum==temp)
printf("%d is an Armstrong number",temp);
else
printf("%d is not an Armstrong number",temp);

return 0;
}

The time complexity of a program that determines


Armstrong number is: O (Number of digits)

15 | C-PROGRAMMING BY K V S N
Code 2:
#include<stdio.h>
int main(){
int num,r,sum,temp;
int min,max;
printf("Enter the minimum range: ");
scanf("%d",&min);

printf("Enter the maximum range: ");


scanf("%d",&max);

printf("Armstrong numbers in given range are: ");


for(num=min;num<=max;num++){
temp=num;
sum = 0;
while(temp!=0){
r=temp%10;
temp=temp/10;
sum=sum+(r*r*r);
}
if(sum==num)
printf("%d ",num);
}

return 0;
}

16 | C-PROGRAMMING BY K V S N
Code 3:

#include<stdio.h>
int main(){
int num,r,sum=0,temp;

printf("Enter a number: ");


scanf("%d",&num);

for(temp=num;num!=0;num=num/10){
r=num%10;
sum=sum+(r*r*r);
}
if(sum==temp)
printf("%d is an Armstrong number",temp);
else
printf("%d is not an Armstrong number",temp);

return 0;
}

17 | C-PROGRAMMING BY K V S N
Code 4:
#include<stdio.h>
int main(){
int num,r,sum,temp;

for(num=1;num<=500;num++){
temp=num;
sum = 0;

while(temp!=0){
r=temp%10;
temp=temp/10;
sum=sum+(r*r*r);
}
if(sum==num)
printf("%d ",num);
}

return 0;
}

18 | C-PROGRAMMING BY K V S N
*************************************************************************************

PRIME NUMBER OR NOT

Definition of prime number:

A natural number greater than one has not any other


divisors except 1 and itself. In other word we can say
which has only two divisors 1 and number itself. For
example: 5

Their divisors are 1 and 5.

Note: 2 is only even prime number.

Logic for prime number in c

We will take a loop and divide number from 2 to number/2.


If the number is not divisible by any of the numbers then
we will print it as prime number.
Example of prime numbers : 2, 3, 5, 7, 11, 13, 17, 19,
23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79,
83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139,
149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,
199 etc.

19 | C-PROGRAMMING BY K V S N
Code 1:

#include<stdio.h>

int main(){

int num,i,count=0;
printf("Enter a number: ");
scanf("%d",&num);
for(i=2;i<=num/2;i++){
if(num%i==0){
count++;
break;
}
}
if(count==0 && num!= 1)
printf("%d is a prime number",num);
else
printf("%d is not a prime number",num);
return 0;
}

Sample output:
Enter a number: 5
5 is a prime number

20 | C-PROGRAMMING BY K V S N
Code 2:
#include<stdio.h>

int main(){
int num,i,count;

for(num = 1;num<=100;num++){
count = 0;

for(i=2;i<=num/2;i++){
if(num%i==0){
count++;
break;
}
}

if(count==0 && num!= 1)


printf("%d ",num);
}

return 0;
}

Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
73 79 83 89 97

21 | C-PROGRAMMING BY K V S N
Code 3:

#include<stdio.h>

int main(){

int num,i,count,n;
printf("Enter max range: ");
scanf("%d",&n);

for(num = 1;num<=n;num++){

count = 0;

for(i=2;i<=num/2;i++){
if(num%i==0){
count++;
break;
}
}

if(count==0 && num!= 1)


printf("%d ",num);
}

return 0;
}

Sample output:
Enter max range: 50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

22 | C-PROGRAMMING BY K V S N
Code 4:

#include<stdio.h>

int main(){

int num,i,count,min,max;

printf("Enter min range: ");


scanf("%d",&min);

printf("Enter max range: ");


scanf("%d",&max);

num = min;
while(num<=max){

count = 0;
i=2;

while(i<=num/2){
if(num%i==0){
count++;
break;
}
i++;
}

if(count==0 && num!= 1)


printf("%d ",num);

num++;
}

return 0;
}

Sample output:
Enter min range: 50
Enter max range: 100
53 59 61 67 71 73 79 83 89 97

23 | C-PROGRAMMING BY K V S N
Code 5:

#include<stdio.h>

int main(){

int num,i,count,min,max;

printf("Enter min range: ");


scanf("%d",&min);

printf("Enter max range: ");


scanf("%d",&max);

for(num = min;num<=max;num++){

count = 0;

for(i=2;i<=num/2;i++){
if(num%i==0){
count++;
break;
}
}

if(count==0 && num!= 1)


printf("%d ",num);
}

return 0;
}

Sample output:
Enter min range: 10
Enter max range: 50
11 13 17 19 23 29 31 37 41 43 47

24 | C-PROGRAMMING BY K V S N
Code 6:

#include<stdio.h>

int main(){

int num,i,count,sum=0;

for(num = 1;num<=100;num++){

count = 0;

for(i=2;i<=num/2;i++){
if(num%i==0){
count++;
break;
}
}

if(count==0 && num!= 1)


sum = sum + num;
}

printf("Sum of prime numbers is: %d ",sum);

return 0;
}

Output:
Sum of prime numbers is: 1060

25 | C-PROGRAMMING BY K V S N
Code 7:

#include<stdio.h>

int main(){

int num,i,count,min,max,sum=0;

printf("Enter min range: ");


scanf("%d",&min);

printf("Enter max range: ");


scanf("%d",&max);

for(num = min;num<=max;num++){

count = 0;

for(i=2;i<=num/2;i++){
if(num%i==0){
count++;
break;
}
}

if(count==0 && num!= 1)


sum = sum + num;
}

printf("Sum of prime numbers is: %d ",sum);

return 0;
}

26 | C-PROGRAMMING BY K V S N
*******************************************************
STRONG NUMBER OR NOT

Definition of strong number:

A number is called strong number if sum of the factorial


of its digit is equal to number itself. For example: 145
since
1! + 4! + 5! = 1 + 24 + 120 = 145

Code 1:
#include<stdio.h>
int main(){
int num,i,f,r,sum=0,temp;

printf("Enter a number: ");


scanf("%d",&num);

temp=num;
while(num){
i=1,f=1;
r=num%10;
while(i<=r){
f=f*i;
i++;
}
sum=sum+f;
num=num/10;
}
if(sum==temp)
printf("%d is a strong number",temp);
else
printf("%d is not a strong number",temp);

return 0;
}
27 | C-PROGRAMMING BY K V S N
Code 2:

#include<stdio.h>
int main(){
int num,i,f,r,sum,temp;
int min,max;

printf("Enter minimum range: ");


scanf("%d",&min);

printf("Enter maximum range: ");


scanf("%d",&max);

printf("Strong numbers in given range are: ");


for(num=min; num <= max; num++){
temp = num;
sum=0;

while(temp){
i=1;
f=1;
r=temp%10;

while(i<=r){
f=f*i;
i++;
}
sum=sum+f;
temp=temp/10;
}

if(sum==num)
printf("%d ",num);
}
return 0;
}

Sample output:
Enter minimum range: 100
Enter maximum range: 100000
Strong numbers in given range are: 145 40585

28 | C-PROGRAMMING BY K V S N
******************************************************************************
EVEN OR ODD NUMBER

Number is called even number if it is divisible by two


otherwise odd.

Example of even numbers: 0,2,4,8,9,10 etc.


Example of odd numbers: 1, 3,5,7,9 etc.

Code 1:

#include<stdio.h>

int main(){

int number;

printf("Enter any integer: ");


scanf("%d",&number);

if(number % 2 ==0)
printf("%d is even number.",number);
else
printf("%d is odd number.",number);

return 0;

Sample output:
Enter any integer: 5
5 is odd number.

29 | C-PROGRAMMING BY K V S N
Code 2:
#include<stdio.h>

int main(){

int number;
int min,max;

printf("Enter the minimum range: ");


scanf("%d",&min);

printf("Enter the maximum range: ");


scanf("%d",&max);

printf("Odd numbers in given range are: ");


for(number = min;number <= max; number++)

if(number % 2 !=0)
printf("%d ",number);

return 0;

Sample output:
Enter the minimum range: 1
Enter the maximum range: 20
Odd numbers in given ranges are: 1 3 5 7 9 11 13 15 17
19

30 | C-PROGRAMMING BY K V S N
Code 3:
#include<stdio.h>

int main(){

int number;
int min,max;

printf("Enter the minimum range: ");


scanf("%d",&min);

printf("Enter the maximum range: ");


scanf("%d",&max);

printf("Odd numbers in given range are: ");


for(number = min;number <= max; number++)

if(number % 2 !=0)
printf("%d ",number);

printf("\nEven numbers in given range are: ");


for(number = min;number <= max; number++)

if(number % 2 ==0)
printf("%d ",number);

return 0;
}

Sample output:
Enter the minimum range: 1
Enter the maximum range: 20
Odd numbers in given ranges are: 1 3 5 7 9 11 13 15 17
19
Even numbers in given ranges are: 2 4 6 8 10 12 14 16
18 20

31 | C-PROGRAMMING BY K V S N
Code 4:

#include<stdio.h>

int main(){

int number;
int min,max;
long sum =0;

printf("Enter the minimum range: ");


scanf("%d",&min);

printf("Enter the maximum range: ");


scanf("%d",&max);

for(number = min;number <= max; number++)


if(number % 2 !=0)
sum = sum + number;

printf("Sum of odd numbers in given range is:


%ld",sum);

return 0;

Sample output:
Enter the minimum range: 1
Enter the maximum range: 100
Sum of odd numbers in given range is: 2500

32 | C-PROGRAMMING BY K V S N
Code 5:

#include<stdio.h>

int main(){

int number;
int min,max;
long odd_sum =0,even_sum = 0;

printf("Enter the minimum range: ");


scanf("%d",&min);

printf("Enter the maximum range: ");


scanf("%d",&max);

for(number = min;number <= max; number++)


if(number % 2 != 0)
odd_sum = odd_sum + number;
else
even_sum = even_sum + number;

printf("Sum of even numbers in given range is:


%ld\n",even_sum);
printf("Sum of odd numbers in given range is:
%ld",odd_sum);

return 0;

Sample output:
Enter the minimum range: 1
Enter the maximum range: 10
Sum of even numbers in given range is: 30
Sum of odd numbers in given range is: 25

33 | C-PROGRAMMING BY K V S N
******************************************************************************
PALINDROME OR NOT (NUMBER)

Definition of Palindrome number or What is palindrome


number?

A number is called palindrome number if it is remain same


when its digits are reversed. For example 121 is
palindrome number. When we will reverse its digit it will
remain same number i.e. 121
Palindrome numbers examples: 0, 1, 2, 3, 4, 5, 6, 7, 8,
9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121,
131, 141, 151, 161, 171, 181, 191 etc.

Code 1:
#include<stdio.h>
int main(){
int num,r,sum=0,temp;

printf("Enter a number: ");


scanf("%d",&num);

temp=num;
while(num){
r=num%10;
num=num/10;
sum=sum*10+r;
}
if(temp==sum)
printf("%d is a palindrome",temp);
else
printf("%d is not a palindrome",temp);

return 0;
}

Sample output:
Enter a number: 131
131 is a palindrome

34 | C-PROGRAMMING BY K V S N
Code 2:

#include<stdio.h>
int main(){
int num,r,sum,temp;
int min,max;

printf("Enter the minimum range: ");


scanf("%d",&min);

printf("Enter the maximum range: ");


scanf("%d",&max);

printf("Palindrome numbers in given range are: ");


for(num=min;num<=max;num++){
temp=num;
sum=0;

while(temp){
r=temp%10;
temp=temp/10;
sum=sum*10+r;
}
if(num==sum)
printf("%d ",num);
}
return 0;
}

Sample output:
Enter the minimum range: 1
Enter the maximum range: 50
Palindrome numbers in given range are: 1 2 3 4 5 6 7 8
9 11 22 33 44

35 | C-PROGRAMMING BY K V S N
Code 3:

#include<stdio.h>
int main(){
int num,r,sum=0,temp;

printf("Enter a number: ");


scanf("%d",&num);

for(temp=num;num!=0;num=num/10){
r=num%10;
sum=sum*10+r;
}
if(temp==sum)
printf("%d is a palindrome",temp);
else
printf("%d is not a palindrome",temp);

return 0;
}

Sample output:
Enter a number: 1221
1221 is a palindrome

36 | C-PROGRAMMING BY K V S N
Code 4:

#include<stdio.h>

int checkPalindrome(int);
int main(){
int num,sum;

printf("Enter a number: ");


scanf("%d",&num);

sum = checkPalindrome(num);

if(num==sum)
printf("%d is a palindrome",num);
else
printf("%d is not a palindrome",num);

return 0;
}

int checkPalindrome(int num){

static int sum=0,r;

if(num!=0){
r=num%10;
sum=sum*10+r;
checkPalindrome(num/10);
}

return sum;
}

Sample output:
Enter a number: 25
25 is not a palindrome

37 | C-PROGRAMMING BY K V S N
******************************************************************************
PALINDROME OR NOT (NUMBER)

Definition of Palindrome string:

A string is called palindrome if it symmetric. In other


word a string is called palindrome if string remains same
if its characters are reversed. For example: asdsa
If we will reverse it will remain same i.e. asdsa

Code 1
#include<string.h>
#include<stdio.h>
int main(){
char *str,*rev;
int i,j;
printf("\nEnter a string:");
scanf("%s",str);
for(i=strlen(str)-1,j=0;i>=0;i--,j++)
rev[j]=str[i];
rev[j]='\0';
if(strcmp(rev,str))
printf("\nThe string is not a palindrome");
else
printf("\nThe string is a palindrome");
return 0;
}

******************************************************************************

ROOTS OF QUADRATIC EQUATION

// TO BE WRITTEN

Code 1
#include<stdio.h>
#include<math.h>

int main(){
float a,b,c;

38 | C-PROGRAMMING BY K V S N
float d,root1,root2;

printf("Enter a, b and c of quadratic equation: ");


scanf("%f%f%f",&a,&b,&c);

d = b * b - 4 * a * c;

if(d < 0){


printf("Roots are complex number.\n");

printf("Roots of quadratic equation are: ");


printf("%.3f%+.3fi",-b/(2*a),sqrt(-d)/(2*a));
printf(", %.3f%+.3fi",-b/(2*a),-sqrt(-d)/(2*a));

return 0;
}
else if(d==0){
printf("Both roots are equal.\n");

root1 = -b /(2* a);


printf("Root of quadratic equation is: %.3f
",root1);

return 0;
}
else{
printf("Roots are real numbers.\n");

root1 = ( -b + sqrt(d)) / (2* a);


root2 = ( -b - sqrt(d)) / (2* a);
printf("Roots of quadratic equation are: %.3f ,
%.3f",root1,root2);
}

return 0;
}

Sample output:
Enter a, b and c of quadratic equation: 2 4 1
Roots are real numbers.
Roots of quadratic equation are: -0.293, -1.707
39 | C-PROGRAMMING BY K V S N
Code 2
#include<stdio.h>
#include<math.h>

int main(){
float a,b,c;
float d,root1,root2;

printf("Enter quadratic equation in the format


ax^2+bx+c: ");
scanf("%fx^2%fx%f",&a,&b,&c);

d = b * b - 4 * a * c;

if(d < 0){


printf("Roots are complex number.\n");

return 0;
}

root1 = ( -b + sqrt(d)) / (2* a);


root2 = ( -b - sqrt(d)) / (2* a);
printf("Roots of quadratic equation are: %.3f ,
%.3f",root1,root2);

return 0;
}

Sample output:
Enter quadratic equation in the format ax^2+bx+c:
2x^2+4x+-1
Roots of quadratic equation are: 0.000, -2.000

40 | C-PROGRAMMING BY K V S N
******************************************************************************
FIBONACCI SERIES

Definition of Fibonacci numbers:

We assume first two Fibonacci are 0 and 1


A series of numbers in which each sequent number is sum
of its two previous numbers is known as Fibonacci series
and each numbers are called Fibonacci numbers. So
Fibonacci numbers is
Algorithm for Fibonacci series

Fn = Fn-2 + Fn-1

Code 1:

#include<stdio.h>
int main(){
int k,r;
long int i=0l,j=1,f;

//Taking maximum numbers form user


printf("Enter the number range:");
scanf("%d",&r);

printf("FIBONACCI SERIES: ");


printf("%ld %ld",i,j); //printing firts two values.

for(k=2;k<r;k++){
f=i+j;
i=j;
j=f;
printf(" %ld",j);
}

return 0;
}

41 | C-PROGRAMMING BY K V S N
Code 2:
1. Fibonacci series using array in c
2. Fibonacci series program in c language
3. Source code of Fibonacci series in c
4. Wap to print Fibonacci series in c

#include<stdio.h>
int main(){

int i,range;
long int arr[40];

printf("Enter the number range: ");


scanf("%d",&range);

arr[0]=0;
arr[1]=1;

for(i=2;i<range;i++){
arr[i] = arr[i-1] + arr[i-2];
}

printf("Fibonacci series is: ");


for(i=0;i<range;i++)
printf("%ld ",arr[i]);

return 0;
}

Sample output:
Enter the number range: 20
Fibonacci series is: 0 1 1 2 3 5 8 13 21 34 55 89 144
233 377 610 987 1597 2584 4181

42 | C-PROGRAMMING BY K V S N
Code 3:

#include<stdio.h>
int main(){
int k=2,r;
long int i=0l,j=1,f;

printf("Enter the number range:");


scanf("%d",&r);

printf("Fibonacci series is: %ld %ld",i,j);

while(k<r){
f=i+j;
i=j;
j=f;
printf(" %ld",j);
k++;
}

return 0;
}

Sample output:
Enter the number range: 10
Fibonacci series is: 0 1 1 2 3 5 8 13 21 34

43 | C-PROGRAMMING BY K V S N
Code 4:

#include<stdio.h>
int main(){
int k,r;
long int i=0,j=1,f;
long int sum = 1;

printf("Enter the number range: ");


scanf("%d",&r);

for(k=2;k<r;k++){
f=i+j;
i=j;
j=f;
sum = sum + j;
}

printf("Sum of Fibonacci series is: %ld",sum);

return 0;
}

Sample output:
Enter the number range: 4
Sum of Fibonacci series is: 4

44 | C-PROGRAMMING BY K V S N
******************************************************************************
FACTORIAL OF A NUMBER

Definition / Algoritham

Factorial of number is defined as:


Factorial (n) = 1*2*3 … * n
For example: Factorial of 5 = 1*2*3*4*5 = 120
Note: Factorial of zero = 1

Code 1:

#include<stdio.h>
int main(){
int i=1,f=1,num;

printf("Enter a number: ");


scanf("%d",&num);

while(i<=num){
f=f*i;
i++;
}

printf("Factorial of %d is: %d",num,f);


return 0;
}

Sample output:
Enter a number: 5
Factorial of 5 is: 120

45 | C-PROGRAMMING BY K V S N
Code 2:

#include<stdio.h>
int main(){
int i,f=1,num;

printf("Enter a number: ");


scanf("%d",&num);

for(i=1;i<=num;i++)
f=f*i;

printf("Factorial of %d is: %d",num,f);


return 0;
}

Code 3:

#include<stdio.h>

void findFactorial(int,int *);


int main(){
int i,factorial,num;

printf("Enter a number: ");


scanf("%d",&num);

findFactorial(num,&factorial);
printf("Factorial of %d is: %d",num,*factorial);

return 0;
}

void findFactorial(int num,int *factorial){


int i;

*factorial =1;

for(i=1;i<=num;i++)
*factorial=*factorial*i;
}

46 | C-PROGRAMMING BY K V S N
Code 4:
1. Factorial program in c using function
2. C program to find factorial of a number

#include<stdio.h>

int findFactorial(int);
int main(){
int i,factorial,num;

printf("Enter a number: ");


scanf("%d",&num);

factorial = findFactorial(num);
printf("Factorial of %d is: %d",num,factorial);

return 0;
}

int findFactorial(int num){


int i,f=1;

for(i=1;i<=num;i++)
f=f*i;

return f;
}
Sample output:
Enter a number: 8
Factorial of 8 is: 40320

47 | C-PROGRAMMING BY K V S N
Code 5:
1. Factorial series in c

#include<stdio.h>
int main(){
long f=1;
int i,num,min,max;

printf("Enter the minimum range: ");


scanf("%d",&min);

printf("Enter the maximum range: ");


scanf("%d",&max);

printf("Factorial series in given range: ");


for(num=min;num<=max;num++){
f=1;

for(i=1;i<=num;i++)
f=f*i;

printf("%ld ",f);
}

return 0;
}

Sample output:
Enter the minimum range: 1
Enter the maximum range: 10
Factorial series in given range: 1 2 6 24 120 720 5040
40320 362880 3628800

48 | C-PROGRAMMING BY K V S N
******************************************************************************
FLOYD’S TRIANGLE

Definition of floyd's triangle:

Floyd's triangle is a right angled-triangle using the


natural numbers. Examples of floyd's triangle:

Example 1:

1
2 3
4 5 6
7 8 9 10

Example 2:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21

49 | C-PROGRAMMING BY K V S N
1. Write a c program to print Floyd’s triangle

2. C program to display Floyd’s triangle

3. How to print Floyd’s triangle in c

#include<stdio.h>

int main(){

int i,j,r,k=1;

printf("Enter the range: ");


scanf("%d",&r);

printf("FLOYD'S TRIANGLE\n\n");
for(i=1;i<=r;i++){
for(j=1;j<=i;j++,k++)
printf(" %d",k);
printf("\n");
}

return 0;
}

Sample output:
Enter the range: 10
FLOYD'S TRIANGLE

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55

50 | C-PROGRAMMING BY K V S N
******************************************************************************
PASCAL’S TRIANGLE

Enter the no. of lines: 8


1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1

51 | C-PROGRAMMING BY K V S N
#include<stdio.h>

long fact(int);
int main(){
int line,i,j;

printf("Enter the no. of lines: ");


scanf("%d",&line);

for(i=0;i<line;i++){
for(j=0;j<line-i-1;j++)
printf(" ");

for(j=0;j<=i;j++)
printf("%ld ",fact(i)/(fact(j)*fact(i-
j)));
printf("\n");
}
return 0;
}

long fact(int num){


long f=1;
int i=1;
while(i<=num){
f=f*i;
i++;
}
return f;
}
Sample output:

Enter the no. of lines: 8


1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1

52 | C-PROGRAMMING BY K V S N
******************************************************************************
MULTIPLICATION TABLE

// WAITLISTED

#include<stdio.h>
int main(){
int r,i,j,k;
printf("Enter the number range: ");
scanf("%d",&r);
for(i=1;i<=r;i++){
for(j=1;j<=10;j++)
printf("%d*%d=%d ",i,j,i*j);
printf("\n");
}
return 0;
}

Sample Output:

Enter the number range: 5

1*1=1 1*2=2 1*3=3 1*4=4 1*5=5 1*6=6 1*7=7 1*8=8 1*9=9 1*10=10

2*1=2 2*2=4 2*3=6 2*4=8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18 2*10=20
3*1=3 3*2=6 3*3=9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27 3*10=30
4*1=4 4*2=8 4*3=12 4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36
4*10=40
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 5*6=30 5*7=35 5*8=40 5*9=45
5*10=50

53 | C-PROGRAMMING BY K V S N
******************************************************************************
PRINTING ASCII VALUES’ USING C-PROGRAM

// PRINT’S ASCII VALUE OF ALL 255 WORD’S OR CHAR OR SPL.SYMBOLS

#include<stdio.h>

int main(){

int i;

for(i=0;i<=255;i++)
printf("ASCII value of character %c:
%d\n",i,i);

return 0;
}

54 | C-PROGRAMMING BY K V S N
******************************************************************************
print hello world without using semicolon
LOGICS TO PRINT HELLO WORLD

#include<stdio.h>
void main(){
if(printf("Hello world")){
}
}

Solution: 2

#include<stdio.h>
void main(){
while(!printf("Hello world")){
}
}

Solution: 3

#include<stdio.h>
void main(){
switch(printf("Hello world")){
}
}

55 | C-PROGRAMMING BY K V S N
******************************************************************************
own source code as its output

#include<stdio.h>

int main(){
FILE *fp;
char c;

fp = fopen(__FILE__,"r");

do{
c= getc(fp);
putchar(c);
}
while(c!=EOF);

fclose(fp);

return 0;
}

Output:
#include<stdio.h>
int main(){
FILE *fp;
char c;

fp = fopen(__FILE__,"r");

do{
c= getc(fp);
putchar(c);
}
while(c!=EOF);

fclose(fp);

return 0;
}
56 | C-PROGRAMMING BY K V S N
******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

57 | C-PROGRAMMING BY K V S N
******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

58 | C-PROGRAMMING BY K V S N
******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

******************************************************************************

59 | C-PROGRAMMING BY K V S N
60 | C-PROGRAMMING BY K V S N
61 | C-PROGRAMMING BY K V S N
Destination Technologies – TCS Ninja Training (Coding Round)

Bangalore 9888738888

Hyderabad 9888748888

Vijayawada 9888758888

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program:
Write a java program to print the following output

class Demo

public static void main(String[] args)

for(int j =1;j<=5;j++)

for(int i=1;i<=5;i++ )

if(j==1 || j==5 || i==1 || i==5)

System.out.print("*");

else

System.out.print(" ");

System.out.println();

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program:
Write a java program to print the following output

class Demo

public static void main(String[] args)

for(int j =1;j<=10;j++)

for(int i=1;i<=10;i++ )

if(j==1 || j==5 || i==1 || i==10)

System.out.print("*");

else

System.out.print(" ");

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

System.out.println();

Program:
Write a java program to print the following output

class Demo

public static void main(String[] args)

for(int j =1;j<=10;j++)

for(int i=1;i<=10;i++ )

if(j==1 && i!=10 || j==5 && i!=10 || j==10 && i!=10 ||


Bangalore Hyderabad Vijayawada
9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

i==1 || i==10 && (j!=1 && j!=5 && j!=10))

System.out.print("*");

else

System.out.print(" ");

System.out.println();

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Bangalore 9888738888

Hyderabad 9888748888

Vijayawada 9888758888

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program 9:
Write a java program to print the following output

class Demo

public static void main(String[] args)

for(int j =1;j<=5;j++)

for(int k =5; k>=j;k--)

System.out.print(" ");

for(int i=1;i<=5;i++ )

System.out.print ("*");

System.out.println();

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program 10:
Write a java program to print the following output

class Demo

public static void main(String[] args)

for(int j =1;j<=5;j++)

for(int k =1; k<=j;k++)

System.out.print(" ");

for(int i=1;i<=5;i++ )

System.out.print ("*");

System.out.println();

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program 11:
Write a java program to print the following output

class Demo

public static void main(String[] args)

for(int j =1;j<=5;j++)

for(int i=1;i<=j;i++ )

System.out.print ("*");

System.out.println();

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program 12:
Write a java program to print the following output

class Demo

public static void main(String[] args)

for(int j =1;j<=5;j++)

for(int i=1;i<=j;i++ )

System.out.print(i);

System.out.println();

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program 13:
Write a java program to print the following output

class Demo

public static void main(String[] args)

for(int j =1;j<=5;j++)

for(int i=1;i<=j;i++ )

System.out.print(j);

System.out.println();

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program 14:
Write a java program to print the following output

class Demo

public static void main(String[] args)

for(int j =1;j<=5;j++)

for(int i=5;i>=j;i-- )

System.out.print(i);

System.out.println();

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program 15:
Write a java program to print the following output

class Demo

public static void main(String[] args)

for(int j =1;j<=5;j++)

for(int i=5;i>=j;i-- )

System.out.print(i);

System.out.println();

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program 16:
Write a java program to print the following output

class Demo

public static void main(String[] args)

for(int j =1;j<=5;j++)

for(int i=5;i>=j;i-- )

System.out.print(j);

System.out.println();

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program 17:
Write a java program to print the following output

class Demo

public static void main(String[] args)

for(int j =1;j<=5;j++)

for(int k=5;k>=j;k-- )

System.out.print(" ");

for(int i=1;i<=j;i++ )

System.out.print("*");

System.out.println();

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program 18:
Write a java program to print the following output

class Demo

public static void main(String[] args)

for(int j =1;j<=5;j++)

for(int k=1;k<=j;k++ )

System.out.print(" ");

for(int i=5;i>=j;i-- )

System.out.print("*");

System.out.println();

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program 1:
Write a java program to print the following output

class Demo

public static void main(String[] args)

System.out.println("*");

Program 2:
Write a java program to print the following output

class Demo

public static void main(String[] args)

System.out.println("*");

System.out.println("*");

System.out.println("*");

System.out.println("*");

System.out.println("*");
Bangalore Hyderabad Vijayawada
9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

}
The above style of writing the code is not suggested as already explained in the lecture.

Program 3:
Write a java program to print the following output using for loop

class Demo

public static void main(String[] args)

for(int i=1;i<=5;i++)

System.out.println("*");

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

Program 4:
Write a java program to print the following output using for loop

class Demo

public static void main(String[] args)

for(int i=1;i<=5;i++ )

System.out.print ("*");

Program 5:
Write a program for the following output without using loops

class Demo

public static void main(String[] args)

for(int i=1;i<=5;i++ )

System.out.print ("*");

for(int i=1;i<=5;i++ )

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

System.out.print ("*");

for(int i=1;i<=5;i++ )

System.out.print ("*");

for(int i=1;i<=5;i++ )

System.out.print ("*");

for(int i=1;i<=5;i++ )

System.out.print ("*");

The above style of writing the code is not suggested as already explained in the lecture.

Program 6:
Write a program for the following output using loops

class Demo

public static void main(String[] args)

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

for(int j =1;j<=5;j++)

for(int i=1;i<=5;i++ )

System.out.print ("*");

Program 7:
Write a program for the following output using loops

class Demo

public static void main(String[] args)

for(int j =1;j<=5;j++)

for(int i=1;i<=5;i++ )

System.out.print ("*");

Bangalore Hyderabad Vijayawada


9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Destination Technologies – TCS Ninja Training (Coding Round)

System.out.println();

Program 8:
Write a program for the following output using loops

class Demo

public static void main(String[] args)

for(int j =1;j<=5;j++)

for(int i=1;i<=3;i++ )

System.out.print ("*");

System.out.println();

}
}
Bangalore Hyderabad Vijayawada
9888738888 9888748888 9888758888
www.destinationtechs.com || [email protected]
Telegram - https://t.me/campusdrive

TCS NQT PREVIOS YEAR CODING QUESTIONS

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 - all 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 is 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 Nth term, no other
characters/strings 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<iostream>
using namespace std;
#define MAX 1000

void fibonacci(int n)
{
int i, t1 = 0, t2 = 1, nextTerm;
for (i = 1; i<=n; i++)
{
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
cout << t1;
}
void prime(int n)
{
int i, j, flag, count =0;
Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

for (i=2; i<=MAX; i++)


{
flag = 0;
for (j=2; j<i; j++)
{
if(i%j == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
if(++count == n)
{
cout << i;
break;
}
}
}
int main()
{
int n;
cin >> n;
if(n%2 == 1)
fibonacci (n/2 + 1);
else
prime(n/2);
return 0;
}

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

2. Given a series whose even term creates a separate geometric series and odd term creates another
geometric series.

Write a program to generate such series.For example,1, 1, 2, 2, 4, 4, 8, 8, 16, 16,......

#include<iostream>
using namespace std;

int main()
{
int n, i, r1, r2;
cout << "nEnter the total number of terms : ";
cin >> n;
cout << "nEnter the common ratio for GP - 1 : ";
cin >> r1;
cout << "nEnter the common ratio for GP - 2 : ";
cin >> r2;
cout << "nThe series isn";
int a = 1, b = 1;
if(n % 2 == 0)
{
for(i = 0; i < n/2; i++)
{
cout << a << " ";
a = a * r1;
cout << b << " ";
b = b * r2;
}
}
else

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

{
for(i = 0; i < n/2; i++)
{
cout << a << " ";
a = a * r1;
cout << b << " ";
b = b * r2;;
}
cout << a << " ";
}
cout << endl;
}

3. Finding area of a circle

Program to find the area of a circle is discussed here. Area of the circle can be found using the
formula, A = πr2 where r is the radius of the circle. When the radius of the circle is known, the area of
the circle can be calculated using the formula mentioned.

#include <iostream>
#include <math.h>
using namespace std;

float area_of_a_circle(float radius)


{
return M_PI * radius * radius;
}

int main()
{

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

float area, radius;


cout << “\nEnter the radius of the circle : “;
cin >> radius;
area = area_of_a_circle(radius);
cout << “\nArea of the circle : ” << area <<endl;
return 0;
}

4.Checking if a given year is leap year or not

#include <iostream>

using namespace std;

int main()

int year;

cout << “Enter a year: “;

cin >> year;

cout << endl;

if(year%4 == 0)

if( year%100 == 0)

if ( year%400 == 0)

cout << year << ” is a leap year” ;

else

cout << year << ” is not a leap year”;

else

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

cout << year << ” is a leap year”;

else

cout << year << ” is not a leap year”;

cout << endl;

return 0;

5. GCD of two numbers | Program to find the GCD or HCF of two numbers

#include<iostream>

using namespace std;

int main()

int a,b,gcd;

cout <<“\nEnter two numbers : “;

cin >> a >> b;

int i;

for(i = 1; i <= a && i <= b; i++)

if((a % i == 0) && (b % i == 0))

gcd = i;

cout << “\nGCD of “<< a << ” and ” << b << ” is ” << gcd;

cout << endl;

return 0;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

6. Check whether a given number is a prime or not

#include<stdio.h>

int main()

int n,i;

printf(“\nEnter the number : “);

scanf(“%d”,&n);

for(i = 2; i <= n/2; i++)

if(n % i ==0)

break;

if(i > n/2)

printf(“\n%d is a Prime Number\n”,n);

else

printf(“\n%d is not a Prime Number\n”, n);

return 0;

7.Find prime numbers in a given range

#include <iostream>

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

using namespace std;

int main()

int a, b, i, flag;

cout << “\nEnter start value : “;

cin >> a;

cout << “\nEnter end value : ” ;

cin >> b;

cout << “\nPrime Numbers between ” << a << ” and ” << b <<” : “;

while (a < b)

flag = 0;

for(i = 2; i <= a/2; ++i)

if(a % i == 0)

flag = 1;

break;

if (flag == 0)

cout << a << ” “;

++a;

cout << endl;

return 0;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

8. Program to check if a given number is a strong number or not

#include<iostream>

using namespace std;

int main()

int n,i;

int fact,rem;

cout << "\nEnter a number : ";

cin >> n;

cout << endl;

int sum = 0;

int temp = n;

while(n)

i = 1,fact = 1;

rem = n % 10;

while(i <= rem)

fact = fact * i;

i++;

sum = sum + fact;

n = n / 10;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

if(sum == temp)

cout << temp << " is a strong number\n";

else

cout << temp << " is not a strong number\n";

return 0;

9. Check whether a number is PALINDROME or Not

#include<iostream>

using namespace std;

int is_Palindrome(int );

int n;

int main()

int palindrome;

cout << “\n\nEnter a number : “;

cin >> n;

cout << endl;

palindrome = is_Palindrome(n);

if(palindrome == 1)

cout << n << ” is a palindrome\n”;

else

cout << n << ” is not a palindrome\n”;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

return 0;

int is_Palindrome(int aj)

static int sum = 0;

if(aj != 0)

sum = sum *10 + aj ;

is_Palindrome(aj/10); // recursive call

else if(sum == n)

return 1;

else

return 0;

10. Check whether the number is armstrong or not

#include<iostream>

#include using namespace std;

int main()

int number, temp, remainder, result = 0, n = 0 ;

cout << “Enter an integer : “;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

cin >> number;

temp = number;

// Finding the number of digits

while (temp != 0)

temp /= 10;

++n;

temp = number;

// Checking if the number is armstrong

while (temp != 0)

remainder = temp ;

result += pow(remainder, n);

temp /= 10;

if(result == number)

cout << number << ” is an Armstrong number\n”;

else

cout << number << ” is not an Armstrong number\n”;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

return 0;

11. Print the Armstrong numbers between two intervals

// C++ program to print the Armstrong numbers between the two intervals

#include <iostream>

#include <math.h>

using namespace std;

int main()

int start, end, i, temp1, temp2, remainder, n = 0, result = 0;

cout << “Enter start value and end value : “;

cin >> start >> end;

cout << “\nArmstrong numbers between ” << start << ” and ” << end << ” are : “;

for(i = start + 1; i < end; ++i)

temp2 = i;

temp1 = i;

while (temp1 != 0)

temp1 /= 10;

++n;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

while (temp2 != 0)

remainder = temp2 % 10;

result += pow(remainder, n);

temp2 /= 10;

if (result == i) {

cout << i << ” “;

n = 0;

result = 0;

cout << endl;

return 0;

12. Fibonacci series upto n value

// C++ program to generate fibonacci series upto n value

#include<iostream>

using namespace std;

int main()

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

int sum = 0, n;

int a = 0;

int b = 1;

cout << "Enter the nth value: ";

cin >> n;

cout << "Fibonacci series: ";

while(sum <= n)

cout << sum << " ";

a = b; // swap elements

b = sum;

sum = a + b; // next term is the sum of the last two terms

return 0;

13. Convert the given Binary Number into Decimal

// C++ program to convert a binary number into decimal number

#include

#include using namespace std;

int binary_to_decimal(long int n)

int decimal = 0, i = 0, remainder;

while (n!=0)

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

remainder = n ;

n /= 10;

decimal += remainder*pow(2,i);

++i;

return decimal;

int main()

long int n;

cout << “Enter a binary number: “;

cin >> n;

cout << “\nDecimal number : ” << binary_to_decimal(n) << endl;

return 0;

Similarly Try the below conversion

14. Decimal to binary conversion

15. Decimal to octal conversion

16. Octal to decimal conversion

17. Binary to octal conversion

18. Octal to binary conversion

19. Find prime numbers in a given range

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

C++ program to find prime numbers in a given range

#include <iostream>

using namespace std;

int main()

int a, b, i, flag;

cout << “\nEnter start value : “;

cin >> a;

cout << “\nEnter end value : ” ;

cin >> b;

cout << “\nPrime Numbers between ” << a << ” and ” << b <<” : “;

while (a < b)

flag = 0;

for(i = 2; i <= a/2; ++i)

if(a % i == 0)

flag = 1;

break;

if (flag == 0)

cout << a << ” “;

++a;

cout << endl;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

return 0;

20. Program to Reverse a Number

// C++ program to reverse a number

#include <iostream>

using namespace std;

int main()

int n, rev = 0, rem;

cout << “\nEnter a number : “;

cin >> n;

cout << “\nReversed Number : “;

while(n != 0)

rem = n ;

rev = rev*10 + rem;

n /= 10;

cout << rev << endl;

return 0;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

21. Program to reverse a string

//program to reverse a string in C++

#include <iostream>

using namespace std;

int main()

char str[1000], rev[1000];

int i, j, count = 0;

cin >> str;

//finding the length of the string by counting

while (str[count] != '')

count++;

j = count - 1;

//reversing the string by swapping

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

rev[i] = str[j];

j--;

cout << rev;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

22. Pyramid pattern using stars or Pyramid star patterns

**

***

****

*****

******

// C++ program to print half pyramid pattern using stars

#include <iostream>

using namespace std;

int main()

int i, j,n;

cin >> n;

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

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

cout << “*”;

cout << endl;

return 0;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

23.Diamond pattern printing using stars

* *

* * *

* * * *

* * * * *

* * * *

* * *

* *

/* C++ program – solid diamond pattern printing using stars */

#include <iostream>

using namespace std;

int main()

int n, c, k, space = 1;

cout << “\nEnter the number of rows : “;

cin >> n;

space = n – 1;

for (k = 1; k <= n; k++)

for (c = 1; c <= space; c++)

cout << ” “;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

space--;

for (c = 1; c <= 2*k-1; c++)

cout << “*”;

cout << endl;

space = 1;

for (k = 1; k <= n – 1; k++)

for (c = 1; c <= space; c++)

cout << ” “;

space++;

for (c = 1 ; c <= 2*(n-k)-1; c++)

cout << “*”;

cout << endl;

return 0;

24. Program to find the second smallest element in an array

#include <bits/stdc++.h>

using namespace std;

int main()

int n,i;

cout << "Enter the number of elements : ";

cin >> n;

int arr[n];

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

cout << "\nInput the array elements : ";

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

cin >> arr[i];

sort(arr, arr+n);

cout << "\nThe second largest element is " << arr[1];

cout << endl;

return 0;

25. Program to remove duplicate elements in an sorted array.

/* C++ program to remove duplicate elements in an array */

#include<iostream>

using namespace std;

int remove_duplicate_elements(int arr[], int n)

if (n==0 || n==1)

return n;

int temp[n];

int j = 0;

int i;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

for (i=0; i<n-1; i++)

if (arr[i] != arr[i+1])

temp[j++] = arr[i];

temp[j++] = arr[n-1];

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

arr[i] = temp[i];

return j;

int main()

int n;

cin >> n;

int arr[n];

int i;

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

cin >> arr[i];

n = remove_duplicate_elements(arr, n);

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

cout << arr[i] << ” “;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

return 0;

Telegram - https://t.me/tcsnqtexam
Swapping 2 numbers

Type 1 :

class Demo

public static void main(String[] args)

int a,b,temp;

a=10;

b=20;

System.out.println("Before swapping the values of a & b are "+a+" "+b);

temp=a;

a=b;

b=temp;

System.out.println("Before swapping the values of a & b are "+a+" "+b);

Type 2:

class Demo

public static void main(String[] args)

int a,b,temp;

a=10;

b=20;

System.out.println("Before swapping the values of a & b are "+a+" "+b);

a=a+b;
b=a-b;

a=a-b;

System.out.println("Before swapping the values of a & b are "+a+" "+b);

Type 3:

class Demo

public static void main(String[] args)

int a,b,temp;

a=10;

b=20;

System.out.println("Before swapping the values of a & b are "+a+" "+b);

a=a*b;

b=a/b;

a=a/b;

System.out.println("Before swapping the values of a & b are "+a+" "+b);

Type 4:

class Demo

public static void main(String[] args)

int a,b,temp;
a=10;

b=20;

System.out.println("Before swapping the values of a & b are "+a+" "+b);

a=a^b;

b=a^b;

a=a-^b;

System.out.println("Before swapping the values of a & b are "+a+" "+b);

}
Coding Question-1
Considerthe peiow 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

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

Please comment the code in other languages as well.

--------------------------------------------------------------------------------------------------------
Coding Question-2
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-
place comparison-based algorithm in which the list is divided into two parts,
the sorted part at the left end and the unsorted part at the right end. Initially,
the sorted part is empty and the unsorted part is the entire list.

The smallest element is selected from the unsorted array and swapped with
the leftmost element, and that element becomes a part of the sorted array.
This process continues moving unsorted array boundary by one element to
the right.

This algorithm is not suitable for large data sets as its average and worst case
complexities are of Ο(n2), where n is the number of items.’

Consider the following depicted array as an example.

For the first position in the sorted list, the whole list is scanned sequentially.
The first position where 14 is stored presently, we search the whole list and
find that 10 is the lowest value.

Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus
leo.

Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus
leo.
Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus
leo.

After two iterations, two least values are positioned at the


beginning in a sorted manner.

The same process is applied to the rest of the items in the array.

Following is a pictorial depiction of the entire sorting process −


// C program for implementation of selection sort
#include <stdio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of unsorted subarray


for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element


swap(&arr[min_idx], &arr[i]);
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

In Python

# Python program for implementation of Selection


# Sort
import sys
A = [64, 25, 12, 22, 11]

# Traverse through all array elements


for i in range(len(A)):

# Find the minimum element in remaining


# unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j

# Swap the found minimum element with


# the first element
A[i], A[min_idx] = A[min_idx], A[i]

# Driver code to test above


print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i]),

In Java

// Java program for implementation of Selection Sort


class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;

// One by one move boundary of unsorted subarray


for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first


// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}

// Prints the array


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

// Driver code to test above


public static void main(String args[])
{
SelectionSort ob = new SelectionSort();
int arr[] = {64,25,12,22,11};
ob.sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}
Coding Question-3

Bubble Sort
Sorting Algorithms are concepts that every competitive programmer must know.
Sorting algorithms can be used for collections of numbers, strings, characters, or a
structure of any of these types.

Bubble sort is based on the idea of repeatedly comparing pairs of adjacent elements
and then swapping their positions if they exist in the wrong order.

Assume that A[] is an unsorted array of n elements. This array needs to be sorted in
ascending order. The pseudo code is as follows:

C/C++

// C program for implementation of Bubble sort


#include <stdio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)

// Last i elements are already in place


for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

Java

// Java program for implementation of Bubble Sort


class BubbleSort
{
void bubbleSort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}

/* Prints the array */


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

// Driver method to test above


public static void main(String args[])
{
BubbleSort ob = new BubbleSort();
int arr[] = {64, 34, 25, 12, 22, 11, 90};
ob.bubbleSort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}

Python

# Python program for implementation of Bubble Sort

def bubbleSort(arr):
n = len(arr)

# Traverse through all array elements


for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):

# traverse the array from 0 to n-i-1


# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]

# Driver code to test above


arr = [64, 34, 25, 12, 22, 11, 90]

bubbleSort(arr)

print ("Sorted array is:")


for i in range(len(arr)):
print ("%d" %arr[i]),

Coding Question-4

Longest Common Subsequence –


We have discussed Overlapping Subproblems and Optimal Substructure properties
in Set 1 and Set 2 respectively. We also discussed one example problem in Set 3. Let
us discuss Longest Common Subsequence (LCS) problem as one more example
problem that can be solved using Dynamic Programming.

LCS Problem Statement: Given two sequences, find the length of longest subsequence
present in both of them. A subsequence is a sequence that appears in the same relative
order, but not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”,
‘”acefg”, .. etc are subsequences of “abcdefg”. So a string of length n has 2^n
different possible subsequences.
It is a classic computer science problem, the basis of diff (a file comparison program
that outputs the differences between two files), and has applications in bioinformatics.

Examples:
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.

C/C++

/* A Naive recursive implementation of LCS problem */


#include<bits/stdc++.h>

int max(int a, int b);

/* Returns length of LCS for X[0..m-1], Y[0..n-1] */


int lcs( char *X, char *Y, int m, int n )
{
if (m == 0 || n == 0)
return 0;
if (X[m-1] == Y[n-1])
return 1 + lcs(X, Y, m-1, n-1);
else
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
}

/* Utility function to get max of 2 integers */


int max(int a, int b)
{
return (a > b)? a : b;
}

/* Driver program to test above function */


int main()
{
char X[] = “AGGTAB”;
char Y[] = “GXTXAYB”;

int m = strlen(X);
int n = strlen(Y);

printf(“Length of LCS is %d”, lcs( X, Y, m, n ) );


return 0;
}

Java

/* A Naive recursive implementation of LCS problem in java*/


public class LongestCommonSubsequence
{

/* Returns length of LCS for X[0..m-1], Y[0..n-1] */


int lcs( char[] X, char[] Y, int m, int n )
{
if (m == 0 || n == 0)
return 0;
if (X[m-1] == Y[n-1])
return 1 + lcs(X, Y, m-1, n-1);
else
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
}

/* Utility function to get max of 2 integers */


int max(int a, int b)
{
return (a > b)? a : b;
}

public static void main(String[] args)


{
LongestCommonSubsequence lcs = new LongestCommonSubsequence();
String s1 = “AGGTAB”;
String s2 = “GXTXAYB”;

char[] X=s1.toCharArray();
char[] Y=s2.toCharArray();
int m = X.length;
int n = Y.length;

System.out.println(“Length of LCS is” + ” ” +


lcs.lcs( X, Y, m, n ) );
}
}

Python

# A Naive recursive Python implementation of LCS problem

def lcs(X, Y, m, n):

if m == 0 or n == 0:
return 0;
elif X[m-1] == Y[n-1]:
return 1 + lcs(X, Y, m-1, n-1);
else:
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));

# Driver program to test the above function


X = “AGGTAB”
Y = “GXTXAYB”
print “Length of LCS is “, lcs(X , Y, len(X), len(Y))

Coding Question-4

SubString Problem in C
Given a string as an input. We need to write a program that will print all non-empty
substrings of that given string.

// C++ program to print all possible


// substrings of a given string

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

// Function to print all sub strings


void subString(char str[], int n)
{
// Pick starting point
for (int len = 1; len <= n; len++)
{
// Pick ending point
for (int i = 0; i <= n – len; i++)
{
// Print characters from current
// starting point to current ending
// point.
int j = i + len – 1;
for (int k = i; k <= j; k++)
cout << str[k];

cout << endl;


}
}
}

// Driver program to test above function


int main()
{
char str[] = “abc”;
subString(str, strlen(str));
return 0;
}

Java

// Java program to print all substrings of a string


public class GFG {

// Function to print all substring


public static void SubString(String str, int n)
{
for (int i = 0; i < n; i++)
for (int j = i+1; j <= n; j++)

// Please refer below article for details


// of substr in Java
// https://www.geeksforgeeks.org/java-lang-string-substring-java/
System.out.println(str.substring(i, j));
}

public static void main(String[] args)


{
String str = “abcd”;
SubString(str, str.length());
}
}

Coding Question-5

Pythrogorous Triplets
A Pythagorean triplet is a set of three integers a, b and c such that a 2 + b2 = c2. Given a
limit, generate all Pythagorean Triples with values smaller than given limit.

Input : limit = 20
Output : 3 4 5
8 6 10
5 12 13
15 8 17
12 16 20

A Simple Solution is to generate these triplets smaller than given limit using three
nested loop. For every triplet, check if Pythagorean condition is true, if true, then print
the triplet. Time complexity of this solution is O(limit 3) where ‘limit’ is given limit.

An Efficient Solution can print all triplets in O(k) time where k is number of triplets
printed. The idea is to use square sum relation of Pythagorean triplet, i.e., addition of
squares of a and b is equal to square of c, we can write these number in terms of m
and n such that,

a = m 2 - n2
b = 2 * m * n
c = m2 + n2
because,
a2 = m4 + n4 – 2 * m2 * n2
b2 = 4 * m 2 * n 2
c2 = m4 + n4 + 2* m2 * n2

We can see that a2 + b2 = c2, so instead of iterating for a, b and c we can iterate for m
and n and can generate these triplets.

Below is the implementation of above idea :


C++
// C++ program to generate pythagorean
// triplets smaller than a given limit
#include <bits/stdc++.h>

// Function to generate pythagorean


// triplets smaller than limit
void pythagoreanTriplets(int limit)
{

// triplet: a^2 + b^2 = c^2


int a, b, c = 0;

// loop from 2 to max_limitit


int m = 2;

// Limiting c would limit


// all a, b and c
while (c < limit) {

// now loop on j from 1 to i-1


for (int n = 1; n < m; ++n) {

// Evaluate and print triplets using


// the relation between a, b and c
a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;

if (c > limit)
break;

printf("%d %d %d\n", a, b, c);


}
m++;
}
}

// Driver Code
int main()
{
int limit = 20;
pythagoreanTriplets(limit);
return 0;
}

Java
// Java program to generate pythagorean
// triplets smaller than a given limit
import java.io.*;
import java.util.*;

class GFG {

// Function to generate pythagorean


// triplets smaller than limit
static void pythagoreanTriplets(int limit)
{

// triplet: a^2 + b^2 = c^2


int a, b, c = 0;

// loop from 2 to max_limitit


int m = 2;

// Limiting c would limit


// all a, b and c
while (c < limit) {

// now loop on j from 1 to i-1


for (int n = 1; n < m; ++n) {
// Evaluate and print
// triplets using
// the relation between
// a, b and c
a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;

if (c > limit)
break;
System.out.println(a + " " + b + " " + c);
}
m++;
}
}

// Driver Code
public static void main(String args[])
{
int limit = 20;
pythagoreanTriplets(limit);
}
}

Python
# Python3 program to generate pythagorean
# triplets smaller than a given limit

# Function to generate pythagorean


# triplets smaller than limit
def pythagoreanTriplets(limits) :
c, m = 0, 2

# Limiting c would limit


# all a, b and c
while c < limits :

# Now loop on n from 1 to m-1


for n in range(1, m) :
a = m * m - n * n
b = 2 * m * n
c = m * m + n * n

# if c is greater than
# limit then break it
if c > limits :
break

print(a, b, c)
m = m + 1

# Driver Code
if __name__ == '__main__' :

limit = 20
pythagoreanTriplets(limit)

Coding Question-6

Armstrong Number
Given a number x, determine whether the given number is Armstrong number or not. A
positive integer of n digits is called an Armstrong number of order n (order is number
of digits) if.

abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....

Example:

Input : 153
Output : Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153

Input : 120
Output : No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9

Input : 1253
Output : No
1253 is not a Armstrong Number
1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723

Input : 1634
Output : Yes
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634
C/C++
// C++ program to determine whether the number is
// Armstrong number or not
#include<bits/stdc++.h>
using namespace std;

/* Function to calculate x raised to the power y */


int power(int x, unsigned int y)
{
if( y == 0)
return 1;
if (y%2 == 0)
return power(x, y/2)*power(x, y/2);
return x*power(x, y/2)*power(x, y/2);
}

/* Function to calculate order of the number */


int order(int x)
{
int n = 0;
while (x)
{
n++;
x = x/10;
}
return n;
}

// Function to check whether the given number is


// Armstrong number or not
bool isArmstrong(int x)
{
// Calling order function
int n = order(x);
int temp = x, sum = 0;
while (temp)
{
int r = temp%10;
sum += power(r, n);
temp = temp/10;
}

// If satisfies Armstrong condition


return (sum == x);
}
// Driver Program
int main()
{
int x = 153;
cout << isArmstrong(x) << endl;
x = 1253;
cout << isArmstrong(x) << endl;
return 0;
}

Java

// Java program to determine whether the number is


// Armstrong number or not
public class Armstrong
{
/* Function to calculate x raised to the
power y */
int power(int x, long y)
{
if( y == 0)
return 1;
if (y%2 == 0)
return power(x, y/2)*power(x, y/2);
return x*power(x, y/2)*power(x, y/2);
}

/* Function to calculate order of the number */


int order(int x)
{
int n = 0;
while (x != 0)
{
n++;
x = x/10;
}
return n;
}

// Function to check whether the given number is


// Armstrong number or not
boolean isArmstrong (int x)
{
// Calling order function
int n = order(x);
int temp=x, sum=0;
while (temp!=0)
{
int r = temp%10;
sum = sum + power(r,n);
temp = temp/10;
}

// If satisfies Armstrong condition


return (sum == x);
}

// Driver Program
public static void main(String[] args)
{
Armstrong ob = new Armstrong();
int x = 153;
System.out.println(ob.isArmstrong(x));
x = 1253;
System.out.println(ob.isArmstrong(x));
}
}

Python

# Python program to determine whether the number is


# Armstrong number or not

# Function to calculate x raised to the power y


def power(x, y):
if y==0:
return 1
if y%2==0:
return power(x, y/2)*power(x, y/2)
return x*power(x, y/2)*power(x, y/2)

# Function to calculate order of the number


def order(x):

# variable to store of the number


n=0
while (x!=0):
n = n+1
x = x/10
return n
# Function to check whether the given number is
# Armstrong number or not
def isArmstrong (x):
n = order(x)
temp = x
sum1 = 0
while (temp!=0):
r = temp%10
sum1 = sum1 + power(r, n)
temp = temp/10

# If condition satisfies
return (sum1 == x)

# Driver Program
x = 153
print(isArmstrong(x))
x = 1253
print(isArmstrong(x))

Coding Question-7
The square root of a Prime number by checking first if it is a prime number?

Write a C program which will check whether a given number N is a Prime or


Not. If the Number N is a Prime, then find it’s square root and print that value
to the STDOUT as floating point number with exactly 2 decimal precision.
If the number is not Prime, then print the value 0.00 to STDOUT.
The given number will be positive non zero integer and it will be passed to the
program as first command line argument.
Other than floating point No other information should be printed to STDOUT.

Also, you can study other Command Line Programming Questions here on
our TCS Dashboard.

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.

lease also write the code in C/++/Java/Python in the comments section below
Please comment your own version of code in the comment section below –

[code language=”cpp”]

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<math.h>
bool isPrime(int n)
{
if(n<2)
return false;
int i;
for(i=2;i*i<=n;i++)
{
if(n%i==0)
return false;
}
return true;
}
int main(int argc, char *argv[])
{
if(argc==1)
{
printf("No arguments");
return 0;
}
else
{
int n;
n=atoi(argv[1]);
float sq=0;
if(isPrime(n))
{
sq=sqrt(n);
printf("%.2f",sq);
}
else
printf("%.2f",sq);
return 0;
}
}

[/code]

Coding Question-8

Basic Program for Decimal to Octal


Given a decimal number as input, we need to write a program to convert the given
decimal number into equivalent octal number. i.e convert the number with base value
10 to base value 8. The base value of a number system determines the number of
digits used to represent a numeric value. For example, the binary number system uses
two digits 0 and 1, octal number system uses 8 digits from 0-7 and decimal number
system uses 10 digits 0-9 to represent any numeric value.

Examples:

Input : 16
Output : 20

Input : 10
Output : 12

Input: 33
Output: 41

Algorithm:

1. Store the remainder when the number is divided by 8 in an array.


2. Divide the number by 8 now
3. Repeat the above two steps until the number is not equal to 0.
4. Print the array in reverse order now.

For Example:
If the given decimal number is 16.
Step 1: Remainder when 16 is divided by 8 is 0. Therefore, arr[0] = 0.
Step 2: Divide 16 by 8. New number is 16/8 = 2.
Step 3: Remainder when 2 is divided by 8 is 2. Therefore, arr[1] = 2.
Step 4: Divide 2 by 8. New number is 2/8 = 0.
Step 5: Since number becomes = 0. Stop repeating steps and print the array in reverse
order. Therefore the equivalent octal number is 20.

C/C++
// C++ program to convert a decimal
// number to octal number

#include <iostream>
using namespace std;

// function to convert decimal to octal


void decToOctal(int n)
{

// array to store octal number


int octalNum[100];

// counter for octal number array


int i = 0;
while (n != 0) {

// storing remainder in octal array


octalNum[i] = n % 8;
n = n / 8;
i++;
}

// printing octal number array in reverse order


for (int j = i - 1; j >= 0; j--)
cout << octalNum[j];
}

// Driver program to test above function


int main()
{
int n = 33;

decToOctal(n);
return 0;
}

Java
// Java program to convert a decimal
// number to octal number
import java.io.*;

class GFG
{
// Function to convert decimal to octal
static void decToOctal(int n)
{
// array to store octal number
int[] octalNum = new int[100];

// counter for octal number array


int i = 0;
while (n != 0)
{
// storing remainder in octal array
octalNum[i] = n % 8;
n = n / 8;
i++;
}

// Printing octal number array in reverse order


for (int j = i - 1; j >= 0; j--)
System.out.print(octalNum[j]);
}

// driver program
public static void main (String[] args)
{
int n = 33;
decToOctal(n);
}
}

Command Line Program to Convert Decimal to Octal


This is very smart short and quick program –

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

Coding Question-9

Basic Program to Binary to Octal


#include <stdio.h>
#include <math.h>

int convertBinarytoOctal(long long binaryNumber);


int main()
{
long long binaryNumber;

printf("Enter a binary number: ");


scanf("%lld", &binaryNumber);

printf("%lld in binary = %d in octal", binaryNumber,


convertBinarytoOctal(binaryNumber));

return 0;
}

int convertBinarytoOctal(long long binaryNumber)


{
int octalNumber = 0, decimalNumber = 0, i = 0;
while(binaryNumber != 0)
{
decimalNumber += (binaryNumber%10) * pow(2,i);
++i;
binaryNumber/=10;
}

i = 1;

while (decimalNumber != 0)
{
octalNumber += (decimalNumber % 8) * i;
decimalNumber /= 8;
i *= 10;
}

return octalNumber;
}

Output

Enter a binary number: 101001


101001 in binary = 51 in octal
import java.util.*;
public class Exercise24 {
public static void main(String[] args)
{
int binnum, binnum1,rem, decnum=0, quot, i=1, j;
int octnum[] = new int[100];
Scanner scan = new Scanner(System.in);
System.out.print("Input a Binary Number : ");
binnum = scan.nextInt();
binnum1=binnum;

while(binnum > 0)
{
rem = binnum % 10;
decnum = decnum + rem*i;
//System.out.println(rem);
i = i*2;
binnum = binnum/10;
}

i=1;
quot = decnum;

while(quot > 0)
{
octnum[i++] = quot % 8;
quot = quot / 8;
}

System.out.print("Equivalent Octal Value of " +binnum1+ " is :");


for(j=i-1; j>0; j--)
{
System.out.print(octnum[j]);
}
System.out.print("\n");

}
}

Sample Output:

Enter Binary Number : 111


Equivalent Octal Value of 111 is :7

Command Line Program to Convert Binary to Octal


This is a very smart program very short and quick method –

#include
void main(int argc,char *argv[])
{
long 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();
}

Coding Question-10

To check if a year is Leap year or not


C/C++
#include <stdio.h>

int main()
{
int year;

printf("Enter a year: ");


scanf("%d",&year);

if(year%4 == 0)
{
if( year%100 == 0)
{
// year is divisible by 400, hence the year is a leap year
if ( year%400 == 0)
printf("%d is a leap year.", year);
else
printf("%d is not a leap year.", year);
}
else
printf("%d is a leap year.", year );
}
else
printf("%d is not a leap year.", year);

return 0;
}

Java
import java.util.Scanner;
public class Check_Leap_Year
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Enter any year:");
int year = s.nextInt();
boolean flag = false;
if(year % 400 == 0)
{
flag = true;
}
else if (year % 100 == 0)
{
flag = false;
}
else if(year % 4 == 0)
{
flag = true;
}
else
{
flag = false;
}
if(flag)
{
System.out.println("Year "+year+" is a Leap Year");
}
else
{
System.out.println("Year "+year+" is not a Leap Year");
}
}
}

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

Coding Question-11

Command Line Program to Check if a Number is Prime or


Not
C/C++
#include <stdio.h>
int main()
{
int n, i, flag = 0;

printf("Enter a positive integer: ");


scanf("%d",&n);

for(i=2; i<=n/2; ++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;
}

Java
public class Prime {

public static void main(String[] args) {

int num = 29;


boolean flag = false;
for(int i = 2; i <= num/2; ++i)
{
// condition for nonprime number
if(num % i == 0)
{
flag = true;
break;
}
}

if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}

Command Line

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

Please comment your own version of code in the comment section below –

#include

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

int n, i, flag = 0;

n = atol(argv[1]);

for(i=2; i<=n/2; ++i)

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;

Coding Question-12

Command Line Program to Reverse a Number


C/c++
#include <stdio.h>
int main()
{
int n, reversedNumber = 0, remainder;

printf("Enter an integer: ");


scanf("%d", &n);

while(n != 0)
{
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
printf("Reversed Number = %d", reversedNumber);

return 0;
}

Java
public class ReverseNumber {

public static void main(String[] args) {

int num = 1234, reversed = 0;

while(num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}

System.out.println("Reversed Number: " + reversed);


}
}

Command Line Programming

Please comment your own version of code in the comment section below –

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

Coding Question-13

Reverse without in built Functions


C/C++
#include <stdio.h>

int main()
{
char s[1000], r[1000];
int begin, end, count = 0;

printf("Input a string\n");
gets(s);

// Calculating string length

while (s[count] != '\0')


count++;

end = count - 1;

for (begin = 0; begin < count; begin++) {


r[begin] = s[end];
end--;
}

r[begin] = '\0';
printf("%s\n", r);

return 0;
}

Coding Question-14

GCD of three numbers


C

Definition of HCF (Highest common factor):

HFC is also called greatest common divisor (gcd). HCF of two numbers is a largest
positive numbers which can divide both numbers without any remainder. For example
HCF of two numbers 4 and 8 is 2 since 2 is the largest positive number which can
dived 4 as well as 8 without a remainder.

Logic for writing program:

It is clear that any number is not divisible by greater than number itself.

☆In case of more than one numbers, a possible maximum number which can divide
all of the numbers must be minimum of all of that numbers.

For example: 10, 20, and 30


Min (10, 20, 30) =10 can divide all there numbers. So we will take one for loop which
will start form min of the numbers and will stop the loop when it became one, since
all numbers are divisible by one. Inside for loop we will write one if conditions which
will check divisibility of both the numbers.

Program :

#include<stdio.h>
int gcd(int , int , int);
int main()
{
int i , j , k , g;
scanf("%d %d %d", &i , &j , &k);

g = gcd(i , j , k);
printf("%d",g);

return 0;
}

int gcd(int i , int j , int k)


{
int least;
least = i;
while(!( (i == j) && (j == k) ) )
{
i = (i == 0 ? least : i);
j = (j == 0 ? least : j);
k = (k == 0 ? least : k);
if(i <= j)
{
if(i <= k)
least = i;
else
least = k;
}
else
{
if(j <= k)
least = j;
else
least = k;
}
i = i % least;
j = j % least;
k = k % least;
}
return least;

}
Java
import java.util.*;

public class HCFOFNumbers {


public static int hcf(int a, int b) {
if (b == 0)
return a;
else
return hcf(b, a % b);
}

public static int hcf(int a, int b, int c) {

return hcf(hcf(a, b), c);

public static void main(String[] args) {


Scanner input = new Scanner(System.in);
System.out.print("Enter Number 1: ");
int num1 = input.nextInt();
System.out.print("Enter Number 2: ");
int num2 = input.nextInt();
System.out.print("Enter Number 3: ");
int num3 = input.nextInt();
int hcfOfNumbers = HCFOFNumbers.hcf(num1, num2,
num3);
System.out.println("HCF of three numbers " + num1
+ "," + num2
+ " and " + num3 + " is: " +
hcfOfNumbers);
}
}

Coding Question-15
Second Largest Number in an Array using Command Line
Programming
#include <stdio.h>
#include <limits.h>

int main()
{
int arr[50], i, Size;
int first, second;

printf("\n Please Enter the Number of elements in an array : ");


scanf("%d", &Size);

printf("\n Please Enter %d elements of an Array \n", Size);


for (i = 0; i < Size; i++)
{
scanf("%d", &arr[i]);
}

first = second = INT_MIN;

Coding Question-16

Sum of odd number in given range using Command Line


Programming
Please comment your own version of code in the comment section below –

[code language=”cpp”]

#include <stdio.h>
#include <stdlib.h>

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


{

if(argc==1 || argc >3){


printf("Please enter only two arguemnts one lower limit and one upper limit");
return 0;
}

else {

int i, n,m, sum=0;


n=atoi(argv[1]);
m = atoi(argv[2]);
for(i=n; i<=m; i++)
{
if(i%2==1)
sum += i;
}

printf("Sum of odd numbers = %d", sum);


}
return 0;
}

Coding Question-17

Addition of 2 numbers and printing the result in binary


Using Command Line Programming
#include<stdlib.h>
#include<stdio.h>

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


{
long n3,i,rem,base=1,decimal,binary=0;

int n1,n2;

n1=atoi(argv[1]);
n2=atoi(argv[2]);

n3=n1+n2;
printf(" The sum of the two numbers are %d",n3);
decimal=n3;
while(n3>0)
{
rem=n3%2;
binary=binary+rem*base;
base=base*10;
n3=n3/2;
}

printf("\n The equivalent binary number is %d",binary);


return 0;
}

Coding Question-18

Write a program that will take a number in string format


and convert it and print it in integer format. For e.g.,
Input String => ”574”
Output Integer => 574

#include <stdio.h>

#include <string.h>

#include <math.h>

#include <ctype.h>

void read_string(char sample[]);

int check_string(char sample[]);

void convert_int(char sample[]);


int main()

int status;

char sample[100];

read_string(sample);

status = check_string(sample);

while ( status == 1 )

printf("\nYou are supposed to enter only digits[0-9]\n");

read_string(sample);

status = check_string(sample);

convert_int(sample);

return 0;

/*This function reads the number entered by the user


and stores it in the character array sample. We are using
fflush to flush the input buffer so that subsequent scans
provide the desired input */

void read_string(char sample[])

printf(“\nEnter the string to be converted to integer(only


numbers) :”);

strcpy(sample, “”);

gets(sample);

fflush(stdin);

/* This function ensures that the string consists of digits


only. If it contains other characters such as punctuation
characters, alphabets etc. then it returns 1 ( Error )

*/

int check_string(char sample[]) {

int i, flag = 0;

for ( i = 0; i<strlen(sample)-1; i++) {

if( isdigit( sample[i] )) {

flag = 1;
}

else {

flag = 0;

break;

if ( flag == 0 ) {

return 1;

else {

return 0;

/* This function does the conversion of the number in


string format to integer format. A character when used in
expressions is treated as an integer and the ASCII value of
the character is used in the expression. For e.g., if the
character is ‘4’ then ASCII value of 4 is 0x34 which is
decimal 52. If we want the integer 4 then we subtract the
48 from the ASCII value of 4 expressed in decimal form,
i.e., 52 – 48 = 4

*/

/* pow function is used to calculate exponent and you


have to include math.h and separately link the math
library as shown ( Unix/Linux )

$ gcc convert.c -lm

*/

void convert_int(char sample[]) {

int i, sum = 0, j = 0;

for ( i=strlen(sample)-1; i>=0; i– ) {

sum = sum + (sample[i] – 48)*pow(10, j);

j++;

printf(“The converted integer = %d\n”, sum);

Coding Question-19

Read from a File


Write a program to print the number of characters and
lines in a file. You should ignore the space, tab and
newline characters for the character count

Create a file called input.txt in the same directory as this


file and enter some lines of text or copy a paragraph of
text. The filename should be input.txt

#include <stdio.h>

#include <stdlib.h>

int main() {

FILE *fp;

int line_count = 0, char_count = 0;

char c;

fp = fopen("input.txt", "r");

if (fp == NULL) {

printf("\nThe file cannot be opened in read mode\n");

exit(1);

c = fgetc(fp);

while ( c != EOF ) {
/* If the character read is a newline or tab or space */

if ( c == '\n' || c == '\t' || c == '\b' ) {

/* If it is a newline character increment the line count */

if ( c == '\n')

line_count++;

/* Read the next character from the file */

c = fgetc(fp);

/* Continue with the next iteration */

continue;

/* Since the character is not a newline, tab or space


increment

the character count

*/

char_count++;

c = fgetc(fp);

/* Since we are done processing the entire file we print the


the charcter count and the word count for the file

*/

printf("\n The number of characters = %d\n",


char_count);

printf("\n The number of lines = %d\n", line_count);

return 0;

Coding Question-20

Here we can take the string and reverse it. Then compare
the original string with the reversed string. If they are the
same then it is a palindrome.

Coding Question-21

Write a program that will take a number in integer


format and convert it and print it in string format. For
e.g.,
Input Integer => 574
Output String => “574”
Solution 1 ( using sprintf )
/* sprint usage is just like printf. Instead of printing the
value on the console we print the value into a string ( char
array ).

printf => Print on Console


fprintf => Print into a file
sprint => Print into a string

*/

#include <stdio.h>

#include <string.h>

int main()

int number, nitems;

char clear[25];

char token[25];

printf(“\nPlease enter a number :”);

fflush(stdin);

nitems = scanf(“%d”, &number);

while ( nitems != 1 ){

/* Clear the Buffer */


gets(clear);

printf(“\nPlease enter a number – digits only :”);

nitems = scanf(“%d”, &number);

printf(“\nThe number of items scanned = %d”, nitems);

sprintf(token, “%d”, number);

printf(“\nThe number %d is converted into string :


%s\n”, number, token);

}
Solution 2 ( using integer manipulation )

#include <stdio.h>

#include <string.h>

int main() {

int number, temp, j = 0, i, rem;

char token[25], snumber[25];

printf(“\nPlease enter a number :”);

scanf(“%d”, &number);

temp = number;
while ( temp ) {

rem = temp%10;

temp = temp/10;

token[j++] = (char)(rem + 48);

token[j] = ‘\0’; /* Token Array has the value “427” */

i = 0;

/* Here we are reversing the array, i.e., 427 to 724 */

for ( j=strlen(token)-1; j>=0; j– ){

snumber[i++] = token[j];

snumber[i] = ‘\0’;

printf(“\nThe number %d is converted into string :


%s\n”, number,

snumber);

Coding Question-22

Write a program to convert a number to its binary


equivalent and print the bit representation of the number
Method 1 ( Using Bit Operators & Masking )

/* In this method we create a mask with the most


significant bit set and And ( &) the mask and the number.
If the result is 0 then we know that the Most Significant Bit
(MSB) of the number is 0. If the result is 1 then the MSB of
the number is 1. Then we right shift the mask by 1 bit and
repeat the process.

*/

#include<stdio.h>

void binary(unsigned int);

void main() {

unsigned int num;

printf(“Enter Decimal Number : “);

scanf(“%u”,&num);

binary(num);

void binary(unsigned int num) {

unsigned int mask=0x80000000;

printf(“\nThe Binary Number is : “);

while(mask > 0){


if((num & mask) == 0 )

printf(“0”);

else

printf(“1”);

mask = mask >> 1;

printf(“\n”);

}
Method 2 ( Consecutive Divide by 2 – The traditional
way in which we convert a number to Binary )

Coding Question-23

Write a program to multiply a number by 8 without using


the * operator
Just left shift by 3 bits. By left shifting a number by 1 bit
we are multiplying by 2.

Left Shift by 1 bit => Multiply by 2


Left Shift by 2 bit => Multiply by 4
Left Shift by 3 bit => Multiply by 8

The number 8 => 00001000


Left Shift by 1 bit => 00010000 ( 16 )
Left Shift by 2 bit => 00100000 ( 32 )
Left Shift by 3 bit => 01000000 ( 34 )
This is a practice question comment down the answer below

#include<stdio.h>
#include<stdlib.h>
int main(int c,char *v[])
{
int n1=atoi(v[1]),n2=8,res=0;
while(n2!=0)
{
res=res+n1;
n2--;
}
printf("%d",res);
}

Coding Question-24

Provide a fast way to multiply a number by 31


Left shift the number by 5 bits and subtract the number
once. For e.g., If the number is 10 left shift by 5 bits gives.

Left Shift by 1 bit is multiplication by 2


Left Shift by 5 bits is multiplication by 32

Since we need to multiply by 31 what we do is multiply


the number by 32 and subtract the number once.
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int n1,n2=31,res=0;

n1=atoi(argv[1]);

while(n2!=0)
{
res=res+n1;
n2--;
}

printf("%d",res);
}

Coding Question-25

Write a program to swap 2 numbers without using the


temporary variable
The idea is to get sum in one of the two given numbers. The numbers can then be
swapped using the sum and subtraction from sum.

C/C++

#include <stdio.h>
int main()
{
int x = 10, y = 5;

// Code to swap ‘x’ and ‘y’


x = x + y; // x now becomes 15
y = x – y; // y becomes 10
x = x – y; // x becomes 5

printf(“After Swapping: x = %d, y = %d”, x, y);

return 0;
}
Java

// Program to swap two numbers without


// using temporary variable
import java.*;

class PrepInsta {

public static void main(String a[])


{
int x = 10;
int y = 5;
x = x + y;
y = x – y;
x = x – y;
System.out.println(“After swaping:”
+ ” x = ” + x + “, y = ” + y);
}
}

Python

x = 10
y=5

# Code to swap ‘x’ and ‘y’

# x now becomes 15
x=x+y

# y becomes 10
y=x–y

# x becomes 5
x=x–y
print(“After Swapping: x =”,x ,” y =”, y);

Coding Question-26
Pushing all 0’s
Given an array of random numbers, Push all the zero’s of a given array to the end of
the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be
changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be
same. Expected time complexity is O(n) and extra space is O(1).

Example:

Input : arr[] = {1, 2, 0, 4, 3, 0, 5, 0};


Output : arr[] = {1, 2, 4, 3, 5, 0, 0};

Input : arr[] = {1, 2, 0, 0, 0, 3, 6};


Output : arr[] = {1, 2, 3, 6, 0, 0, 0};

C/C++
// A C++ program to move all zeroes at the end of array
#include <iostream>
using namespace std;

// Function which pushes all zeros to end of an array.


void pushZerosToEnd(int arr[], int n)
{
int count = 0; // Count of non-zero elements

// Traverse the array. If element encountered is non-


// zero, then replace the element at index 'count'
// with this element
for (int i = 0; i < n; i++)
if (arr[i] != 0)
arr[count++] = arr[i]; // here count is
// incremented

// Now all non-zero elements have been shifted to


// front and 'count' is set as index of first 0.
// Make all elements 0 from count to end.
while (count < n)
arr[count++] = 0;
}

// Driver program to test above function


int main()
{
int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9};
int n = sizeof(arr) / sizeof(arr[0]);
pushZerosToEnd(arr, n);
cout << "Array after pushing all zeros to end of array :n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}

Coding Question-27

Write a function to calculate the length of a string without


using strlen function using Command Line Programming

#include < stdio.h >


#include < conio.h >
void main(int argc,char *argv[])
{
int len;
char *ptr;
clrscr();
if ( argc != 2)
{
printf("\n Invalid arguments ");
exit(0);
}
else
{
ptr=argv[1];
len=0;
while ( *(ptr+len) != '\0')
{
len++;
}
printf("\n Length is %d",len);
}
}

Coding Question-28

Write a function that accepts 2 strings search string and


pattern string and returns TRUE if the pattern string is
found in the search string and FALSE if the pattern string
is not found in the search string
Please also comment the code in other languages below –

#include

#define TRUE 1

#define FALSE 0

int search(char sentence[], char pattern[]);

int main(){

char sentence[1000];

char pattern[25];

int result;

printf(“Please enter a paragraph not exceeding 1000


characters :”);

gets(sentence);
printf(“\n\n”);

printf(“Please enter the search string :”);

gets(pattern);

result = search(sentence, pattern);

int search(char sentence[], char pattern[]){

char *p;

/* The library function strstr searches for the pattern


string in the sentence string. If the pattern is found it
returns a pointer to the index of the pattern in the
sentence. If not it returns NULL

*/

p = strstr(sentence, pattern);

if ( p == NULL ){

printf(“\nThe search string was not found in the


sentence\n\n”);

return FALSE;

else {
printf(“\nThe search string was found in the
sentence\n\n”);

return TRUE;

}
}

Coding Question-29

K’th Smallest/Largest Element in Unsorted Array


Given an array and a number k where k is smaller than size of array, we need to find
the k’th smallest element in the given array. It is given that ll array elements are distinct.

Examples:

Input: arr[] = {7, 10, 4, 3, 20, 15}


k = 3
Output: 7

Input: arr[] = {7, 10, 4, 3, 20, 15}


k = 4
Output: 10

C/C++
// Simple C++ program to find k'th smallest element
#include<iostream>
#include<algorithm>
using namespace std;

// Function to return k'th smallest element in a given array


int kthSmallest(int arr[], int n, int k)
{
// Sort the given array
sort(arr, arr+n);

// Return k'th element in the sorted array


return arr[k-1];
}

// Driver program to test above methods


int main()
{
int arr[] = {12, 3, 5, 7, 19};
int n = sizeof(arr)/sizeof(arr[0]), k = 2;
cout << "K'th smallest element is " << kthSmallest(arr, n, k);
return 0;
}

Java
// Java code for kth smallest element
// in an array
import java.util.Arrays;
import java.util.Collections;

class GFG
{
// Function to return k'th smallest
// element in a given array
public static int kthSmallest(Integer [] arr,
int k)
{
// Sort the given array
Arrays.sort(arr);

// Return k'th element in


// the sorted array
return arr[k-1];
}

// driver program
public static void main(String[] args)
{
Integer arr[] = new Integer[]{12, 3, 5, 7, 19};
int k = 2;
System.out.print( "K'th smallest element is "+
kthSmallest(arr, k) );
}
}

Coding Question-30
GCD Array of Numbers
The GCD of three or more numbers equals the product of the prime factors common
to all the numbers, but it can also be calculated by repeatedly taking the GCDs of
pairs of numbers.

gcd(a, b, c) = gcd(a, gcd(b, c))


= gcd(gcd(a, b), c)
= gcd(gcd(a, c), b)

For an array of elements, we do following.

result = arr[0]
For i = 1 to n-1
result = GCD(result, arr[i])

Below is the implementation of above idea.

C/C++

// C++ program to find GCD of two or


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

// Function to return gcd of a and b


int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}

// Function to find gcd of array of


// numbers
int findGCD(int arr[], int n)
{
int result = arr[0];
for (int i = 1; i < n; i++)
result = gcd(arr[i], result);
return result;
}

// Driven code
int main()
{
int arr[] = { 2, 4, 6, 8, 16 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findGCD(arr, n) << endl;
return 0;
}

Java

// Java program to find GCD of two or


// more numbers

public class GCD {


// Function to return gcd of a and b
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}

// Function to find gcd of array of


// numbers
static int findGCD(int arr[], int n)
{
int result = arr[0];
for (int i = 1; i < n; i++)
result = gcd(arr[i], result);

return result;
}

public static void main(String[] args)


{
int arr[] = { 2, 4, 6, 8, 16 };
int n = arr.length;
System.out.println(findGCD(arr, n));
}
}

// This code is contributed by Saket Kumar

Coding Question-31

Write a function that reads a sentence into a string and


splits the sentence into words without using library
functions

You have to do this without using the strtok function.


Since the delimiters are not specified you assume the
default delimiters such as spaces, comma, tabs and
newlines

You examine character by character and when you


encounter a delimiter you have to terminate the word
with the NULL character(\0)

Coding Question-32

Write a function that reads a sentence into a string and


splits the sentence into words using library functions

#include <stdio.h>

#include <string.h>

int main() {

char sentence[100];
char *p;

printf(“\nPlease enter a sentence :”);

gets(sentence);

p = strtok(sentence, “\t “);

while ( p != NULL ){

printf(“%s\n”, p);

p = strtok(NULL, “\t”);

return 0;
}

Coding Question-33

Write a function that removes all duplicate spaces from a


sentence. Your program should ensure that only one space
exists between words

/* We can remove duplicates by checking each character


and having a space count. But here we are doing it using
the string library function strtok

*/

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

int main(){

char input[100];

char output[100];

char temp[100];

char *p;

printf(“\nPlease enter a sentence :”);

gets(input);

strcpy(temp, input);

strcpy(output,””);

p = strtok(temp, ” “);

while ( p != NULL ){

strcat(output,p);

strcat(output,” “);

printf(“%s\n”, p);

p = strtok(NULL, ” “);

printf(“%s\n”, input);
printf(“%s\n”, output);

printf(“%d\n”, strlen(output));

return 0;

Coding Question-34

Write a function that uses character handling library


functions to determine the number of upper case, lower
case, digits, spaces and punctuation characters in the
specified text

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

int main()

int length, i;

int alpha = 0, punct = 0, digit = 0, lower = 0, upper = 0,

spaces = 0, others = 0;

char buffer[150] = “English Language consists of letters

from A to Z and digits 1 to 9 which are

used to form : words, sentences and


paragraphs!!!”;

length = strlen(buffer);

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

if( isalpha( buffer[i] ))

alpha++;

if ( islower( buffer[i] ))

lower++;

else

upper++;

else if (isdigit(buffer[i] ))

digit++;

}
else if (isspace(buffer[i])){

spaces++;
}

else if (ispunct(buffer[i])){

punct++;

}
else

others++;

printf(“The number of lowercase letters = %d\n”, lower);

printf(“The number of uppercase letters = %d\n”, upper);

printf(“The number of spaces = %d\n”, spaces);

printf(“The number of punctuation characters = %d\n”,


punct);

printf(“The number of alphabets = %d\n”, alpha);

printf(“The number of digits = %d\n”, digit);

Coding Question-35

Write a function that takes an array called scores and 2


pointer parameters min and max and determines the
minimum and maximum values and returns them to the
calling function

Coding Question-36
Write a Program to remove vowels from a string?

Please comment down your answer.

Coding Question-37
Write a Program for Matrix Multiplication(Universal Program)

Please comment down the code, we will add here.


Telegram - https://t.me/campusdrive

TCS NQT PREVIOS YEAR CODING QUESTIONS

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 - all 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 is 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 Nth term, no other
characters/strings 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<iostream>
using namespace std;
#define MAX 1000

void fibonacci(int n)
{
int i, t1 = 0, t2 = 1, nextTerm;
for (i = 1; i<=n; i++)
{
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
cout << t1;
}
void prime(int n)
{
int i, j, flag, count =0;
Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

for (i=2; i<=MAX; i++)


{
flag = 0;
for (j=2; j<i; j++)
{
if(i%j == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
if(++count == n)
{
cout << i;
break;
}
}
}
int main()
{
int n;
cin >> n;
if(n%2 == 1)
fibonacci (n/2 + 1);
else
prime(n/2);
return 0;
}

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

2. Given a series whose even term creates a separate geometric series and odd term creates another
geometric series.

Write a program to generate such series.For example,1, 1, 2, 2, 4, 4, 8, 8, 16, 16,......

#include<iostream>
using namespace std;

int main()
{
int n, i, r1, r2;
cout << "nEnter the total number of terms : ";
cin >> n;
cout << "nEnter the common ratio for GP - 1 : ";
cin >> r1;
cout << "nEnter the common ratio for GP - 2 : ";
cin >> r2;
cout << "nThe series isn";
int a = 1, b = 1;
if(n % 2 == 0)
{
for(i = 0; i < n/2; i++)
{
cout << a << " ";
a = a * r1;
cout << b << " ";
b = b * r2;
}
}
else

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

{
for(i = 0; i < n/2; i++)
{
cout << a << " ";
a = a * r1;
cout << b << " ";
b = b * r2;;
}
cout << a << " ";
}
cout << endl;
}

3. Finding area of a circle

Program to find the area of a circle is discussed here. Area of the circle can be found using the
formula, A = πr2 where r is the radius of the circle. When the radius of the circle is known, the area of
the circle can be calculated using the formula mentioned.

#include <iostream>
#include <math.h>
using namespace std;

float area_of_a_circle(float radius)


{
return M_PI * radius * radius;
}

int main()
{

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

float area, radius;


cout << “\nEnter the radius of the circle : “;
cin >> radius;
area = area_of_a_circle(radius);
cout << “\nArea of the circle : ” << area <<endl;
return 0;
}

4.Checking if a given year is leap year or not

#include <iostream>

using namespace std;

int main()

int year;

cout << “Enter a year: “;

cin >> year;

cout << endl;

if(year%4 == 0)

if( year%100 == 0)

if ( year%400 == 0)

cout << year << ” is a leap year” ;

else

cout << year << ” is not a leap year”;

else

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

cout << year << ” is a leap year”;

else

cout << year << ” is not a leap year”;

cout << endl;

return 0;

5. GCD of two numbers | Program to find the GCD or HCF of two numbers

#include<iostream>

using namespace std;

int main()

int a,b,gcd;

cout <<“\nEnter two numbers : “;

cin >> a >> b;

int i;

for(i = 1; i <= a && i <= b; i++)

if((a % i == 0) && (b % i == 0))

gcd = i;

cout << “\nGCD of “<< a << ” and ” << b << ” is ” << gcd;

cout << endl;

return 0;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

6. Check whether a given number is a prime or not

#include<stdio.h>

int main()

int n,i;

printf(“\nEnter the number : “);

scanf(“%d”,&n);

for(i = 2; i <= n/2; i++)

if(n % i ==0)

break;

if(i > n/2)

printf(“\n%d is a Prime Number\n”,n);

else

printf(“\n%d is not a Prime Number\n”, n);

return 0;

7.Find prime numbers in a given range

#include <iostream>

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

using namespace std;

int main()

int a, b, i, flag;

cout << “\nEnter start value : “;

cin >> a;

cout << “\nEnter end value : ” ;

cin >> b;

cout << “\nPrime Numbers between ” << a << ” and ” << b <<” : “;

while (a < b)

flag = 0;

for(i = 2; i <= a/2; ++i)

if(a % i == 0)

flag = 1;

break;

if (flag == 0)

cout << a << ” “;

++a;

cout << endl;

return 0;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

8. Program to check if a given number is a strong number or not

#include<iostream>

using namespace std;

int main()

int n,i;

int fact,rem;

cout << "\nEnter a number : ";

cin >> n;

cout << endl;

int sum = 0;

int temp = n;

while(n)

i = 1,fact = 1;

rem = n % 10;

while(i <= rem)

fact = fact * i;

i++;

sum = sum + fact;

n = n / 10;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

if(sum == temp)

cout << temp << " is a strong number\n";

else

cout << temp << " is not a strong number\n";

return 0;

9. Check whether a number is PALINDROME or Not

#include<iostream>

using namespace std;

int is_Palindrome(int );

int n;

int main()

int palindrome;

cout << “\n\nEnter a number : “;

cin >> n;

cout << endl;

palindrome = is_Palindrome(n);

if(palindrome == 1)

cout << n << ” is a palindrome\n”;

else

cout << n << ” is not a palindrome\n”;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

return 0;

int is_Palindrome(int aj)

static int sum = 0;

if(aj != 0)

sum = sum *10 + aj ;

is_Palindrome(aj/10); // recursive call

else if(sum == n)

return 1;

else

return 0;

10. Check whether the number is armstrong or not

#include<iostream>

#include using namespace std;

int main()

int number, temp, remainder, result = 0, n = 0 ;

cout << “Enter an integer : “;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

cin >> number;

temp = number;

// Finding the number of digits

while (temp != 0)

temp /= 10;

++n;

temp = number;

// Checking if the number is armstrong

while (temp != 0)

remainder = temp ;

result += pow(remainder, n);

temp /= 10;

if(result == number)

cout << number << ” is an Armstrong number\n”;

else

cout << number << ” is not an Armstrong number\n”;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

return 0;

11. Print the Armstrong numbers between two intervals

// C++ program to print the Armstrong numbers between the two intervals

#include <iostream>

#include <math.h>

using namespace std;

int main()

int start, end, i, temp1, temp2, remainder, n = 0, result = 0;

cout << “Enter start value and end value : “;

cin >> start >> end;

cout << “\nArmstrong numbers between ” << start << ” and ” << end << ” are : “;

for(i = start + 1; i < end; ++i)

temp2 = i;

temp1 = i;

while (temp1 != 0)

temp1 /= 10;

++n;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

while (temp2 != 0)

remainder = temp2 % 10;

result += pow(remainder, n);

temp2 /= 10;

if (result == i) {

cout << i << ” “;

n = 0;

result = 0;

cout << endl;

return 0;

12. Fibonacci series upto n value

// C++ program to generate fibonacci series upto n value

#include<iostream>

using namespace std;

int main()

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

int sum = 0, n;

int a = 0;

int b = 1;

cout << "Enter the nth value: ";

cin >> n;

cout << "Fibonacci series: ";

while(sum <= n)

cout << sum << " ";

a = b; // swap elements

b = sum;

sum = a + b; // next term is the sum of the last two terms

return 0;

13. Convert the given Binary Number into Decimal

// C++ program to convert a binary number into decimal number

#include

#include using namespace std;

int binary_to_decimal(long int n)

int decimal = 0, i = 0, remainder;

while (n!=0)

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

remainder = n ;

n /= 10;

decimal += remainder*pow(2,i);

++i;

return decimal;

int main()

long int n;

cout << “Enter a binary number: “;

cin >> n;

cout << “\nDecimal number : ” << binary_to_decimal(n) << endl;

return 0;

Similarly Try the below conversion

14. Decimal to binary conversion

15. Decimal to octal conversion

16. Octal to decimal conversion

17. Binary to octal conversion

18. Octal to binary conversion

19. Find prime numbers in a given range

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

C++ program to find prime numbers in a given range

#include <iostream>

using namespace std;

int main()

int a, b, i, flag;

cout << “\nEnter start value : “;

cin >> a;

cout << “\nEnter end value : ” ;

cin >> b;

cout << “\nPrime Numbers between ” << a << ” and ” << b <<” : “;

while (a < b)

flag = 0;

for(i = 2; i <= a/2; ++i)

if(a % i == 0)

flag = 1;

break;

if (flag == 0)

cout << a << ” “;

++a;

cout << endl;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

return 0;

20. Program to Reverse a Number

// C++ program to reverse a number

#include <iostream>

using namespace std;

int main()

int n, rev = 0, rem;

cout << “\nEnter a number : “;

cin >> n;

cout << “\nReversed Number : “;

while(n != 0)

rem = n ;

rev = rev*10 + rem;

n /= 10;

cout << rev << endl;

return 0;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

21. Program to reverse a string

//program to reverse a string in C++

#include <iostream>

using namespace std;

int main()

char str[1000], rev[1000];

int i, j, count = 0;

cin >> str;

//finding the length of the string by counting

while (str[count] != '')

count++;

j = count - 1;

//reversing the string by swapping

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

rev[i] = str[j];

j--;

cout << rev;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

22. Pyramid pattern using stars or Pyramid star patterns

**

***

****

*****

******

// C++ program to print half pyramid pattern using stars

#include <iostream>

using namespace std;

int main()

int i, j,n;

cin >> n;

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

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

cout << “*”;

cout << endl;

return 0;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

23.Diamond pattern printing using stars

* *

* * *

* * * *

* * * * *

* * * *

* * *

* *

/* C++ program – solid diamond pattern printing using stars */

#include <iostream>

using namespace std;

int main()

int n, c, k, space = 1;

cout << “\nEnter the number of rows : “;

cin >> n;

space = n – 1;

for (k = 1; k <= n; k++)

for (c = 1; c <= space; c++)

cout << ” “;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

space--;

for (c = 1; c <= 2*k-1; c++)

cout << “*”;

cout << endl;

space = 1;

for (k = 1; k <= n – 1; k++)

for (c = 1; c <= space; c++)

cout << ” “;

space++;

for (c = 1 ; c <= 2*(n-k)-1; c++)

cout << “*”;

cout << endl;

return 0;

24. Program to find the second smallest element in an array

#include <bits/stdc++.h>

using namespace std;

int main()

int n,i;

cout << "Enter the number of elements : ";

cin >> n;

int arr[n];

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

cout << "\nInput the array elements : ";

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

cin >> arr[i];

sort(arr, arr+n);

cout << "\nThe second largest element is " << arr[1];

cout << endl;

return 0;

25. Program to remove duplicate elements in an sorted array.

/* C++ program to remove duplicate elements in an array */

#include<iostream>

using namespace std;

int remove_duplicate_elements(int arr[], int n)

if (n==0 || n==1)

return n;

int temp[n];

int j = 0;

int i;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

for (i=0; i<n-1; i++)

if (arr[i] != arr[i+1])

temp[j++] = arr[i];

temp[j++] = arr[n-1];

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

arr[i] = temp[i];

return j;

int main()

int n;

cin >> n;

int arr[n];

int i;

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

cin >> arr[i];

n = remove_duplicate_elements(arr, n);

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

cout << arr[i] << ” “;

Telegram - https://t.me/tcsnqtexam
Telegram - https://t.me/campusdrive

return 0;

Telegram - https://t.me/tcsnqtexam
1.To find GCD of two numbers
#include <stdio.h>
int main(int argc,char *argv[])
{
int a,b,small,i;
a=atoi(argv[1]);
b=atoi(argv[2]);
if(a>b)
small=b;
else
small=a;
for(i=small;i>=1;i--)
{
if((a%i)==0&&(b%i)==0)
{
printf("%d",i);
break;
}
}
return 0;
}
2. To find the lcm of two numbers

#include <stdio.h>
int main(int argc,char *argv[])
{
int a,b,large;
a=atoi(argv[1]);
b=atoi(argv[2]);
if(a>b)
large=a;
else
large=b;
while(1)
{
if((large%a)==0&&(large%b)==0)
{
printf("%d",large);
break;
}
large++;
}
return 0;
}
3. To find the Factorial of a non negative number
#include <stdio.h>
int main(int argc,char *argv[])
{
int n,fact=1,i;
n=atoi(argv[1]);
for(i=1;i<=n;i++)
{
fact=fact*i;
}
printf("%d",fact);
return 0;
}

4. To find the area of a circle (area=3.14*r*r), when


diameter is given.
#include <stdio.h>
#define PI 3.14
int main(int argc,char *argv[])
{
float dia,radius,area=0;
dia=atoi(argv[1]);
radius=0.5*dia;
area=PI*radius*radius;
printf("%.2f",area);
return 0;
}
5.To check whether the given year is Leap year or not.

#include <stdio.h>

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


{
int year;
year=atoi(argv[1]);
if(year%100==0)
{
if(year%400==0)
printf("Leap year");
else
printf("not leap year");
}
else
if(year%4==0)
printf("leap year");
else
printf("not leap year");
return 0;
}
6.To find the area of triangle when base and height is
given.
#include <stdio.h>
int main(int argc,char *argv[])
{
float height,base,area;
height=atoi(argv[1]);
base=atoi(argv[2]);
area=0.5*base*height;
printf("%.2f",area);
return 0;
}
7. To print the Fibonacci series.
Input=6 Output=1 1 2 3 5 8
#include <stdio.h>
int main(int argc,char *argv[])
{
int n,first=1,sec=1,next,i;
n=atoi(argv[1]);
for (i=0;i<n;i++)
{
if (i<=1)
next=1;
else
{
next=first+sec;
first=sec;
sec=next;
}
printf("%d ",next);
}
return 0;
}
8.To check whether the given number is prime or not.

#include <stdio.h>
int main(int argc,char *argv[])
{
int n,i,count=0;
n=atoi(argv[1]);
for(i=1;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}
if(count==2)
printf("prime number");
else
printf("not prime number ");
return 0;
}
9.To check whether given number is strong number or
not.
#include<stdio.h>
int fact(int);
int main(int argc, char *argv[])
{
int num,d,n,res=0,i,count=0,x;
n=atoi(argv[1]);
num=n;
x=num;
while(n!=0)
{
n=n/10;
count++;
}
for(i=0;i<count;i++){
if(x>0)
{
d=x%10;
res=res+fact(d);
x=x/10;
}
}
if(res==num)
{
printf("strong number");
}
else printf("not strong number");
return 0;
}
int fact(int x)
{
if(x==0)
return 1;
else
return x*fact(x-1);
}
10. To check whether number is palindrome or not.
#include <stdio.h>
int main(int argc,char *argv[])
{
int num,rev=0,digit,orig;
num=atoi(argv[1]);
orig=num;

while(num>0){
digit=num%10;
rev=rev*10+digit;
num=num/10;
}

if(orig==rev)
{
printf("palindrome");
}
else
printf("not palindrome");
return 0;
}
 TCS Ninja programming MCQ’s with answers

 TCS Ninja coding questions and answers

 TCS Ninja Aptitude & English questions – Answers with Explanations

Brought to you by the N. Rajeev Reddy | More n More @ www.matterhere.com | Google+ - Facebook/matterhere

_________________________________________Source: FACE Prep

TCS Ninja Mock test questions – Coding section


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 – all 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 is 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 Nth term, no other characters/strings 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.

Program:

#include<stdio.h>
#define MAX 1000
void fibonacci(int n)
{
int i, t1 = 0, t2 = 1, nextTerm;
for (i = 1; i<=n; i++)
{
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
printf(―%d‖, t1);
}

void prime(int n)
{
int i, j, flag, count =0;
for (i=2; i<=MAX; i++)
{
flag = 0;
for (j=2; j<i; j++)
{
if(i%j == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
count++;
if(count == n)
{
printf(―%d‖, i);
break;
}
}
}
int main( )
{
int n;
scanf(―%d‖, &n);
if(n%2 == 1)
fibonacci (n/2 + 1);
else
prime(n/2);
return 0;
}

TCS Ninja Coding question 1:


Factorial program in c using command line arguments.

Explanation: Factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less
than or equal to n. For example, The value of 5! is 5*4*3*2*1 = 120

Solution:

#include
int main(int a, char *b[]) //command line arguments
{
int x,y,f=1;
x=atoi(b[1]); //atoi function is to convert a character to integer
for(i=1;i<=x;i++)
{
f=f*i;
}
printf(―%d‖,f);
return 0;
}
TCS Ninja Coding question 2:
Write a c program, to find the area of a circle when the diameter is given, using command line arguments. The
input diameter is an integer and the output area should be a floating point variable with 2 point precision.

Solution:

#include
#define PI 3.14
int main(int a, char *b[]) //command line arguments
{
int d; float area =0;
d= atoi(argv[1]);
area =(float) PI*(d/2)*(d/2);
printf(―%0.2f‖, area); //%0.2f is to print the answer with 2 values after decimal point.
return 0;
}

TCS Ninja Coding question 3:


Write a c program, to check whether the given year is a leap year or not using command line arguments. A leap
year is a calendar year containing one additional day (Feb 29th) added to keep the calendar year synchronized
with the astronomical year.

Solution:

#include
int main(int a, char*b[])
{
int year; year=atoi(b[1]);
if(year%100==0)
{
if(year%400==0)
{
printf(―LEAP YEAR‖);
}
else{
printf(―NOT LEAP YEAR‖); } }
else if(year%4==0)
{
printf(―LEAP YEAR‖);
}
else{
printf(―NOT LEAP YEAR‖);
}
return 0; }

Brought to you by the N. Rajeev Reddy | More n More @ www.matterhere.com | Google+ - Facebook/matterhere
TCS Ninja Coding question 4:
Write a c program, to find the GCD of the given 2 numbers, using command line arguments. The input is 2
integer and the output GCD also should be an integer value.

Solution:

#include
int main(int x, char *y[])
{
inta,b,small,i;
a=atoi(y[1]);
b=atoi(y[2]);
small=a>b?b:a;
for(i=small;i>=1;i–)
{
if((a%i==0)&&(b%i==0))
{
printf(―%d‖,i);
break;
}}
return 0;
}

TCS Ninja Coding question 5:


C Program to check whether a given number is a prime number or not. The given number N, a positive integer,
will be passed to the program using the first command line parameter. If it is a prime number the output should
be the square root of the number up to 2 decimal point precision, If it is not a prime number then print 0.00 to
stdout.

Solution:

#include
#include
#include int main(int a, char *b[])
{
int number,i,flag = 1;
number = atoi(b[1]);
for(i=2; i<number; i++)
{
if(number%i == 0)
{
flag = 0;
break;
}
}
if(flag == 1)
printf(―%.2f‖,sqrt(number));
else
printf(―0.00‖);
return 0;
}
TCS Ninja Coding question 6:
C Program to check whether a given number is a strong number or not. The given number N, a positive integer,
will be passed to the program using the first command line parameter. If it is a strong number, the output should
be ―YES‖, If it is not a prime number then output should be ―NO‖ to stdout. Other than YES or NO, no other
extra information should be printed to stdout.

Solution:

#include
#include
int main(int a, char *b[])
{
int number, i, temp, sum = 0, factorial = 1;
number = atoi(b[1]);
temp = number;
while(number != 0)
{
int rem = number%10;
for(i=2; i<=rem; i++)
{
factorial = factorial * i;
}
sum = sum + factorial;
number = number/10;
factorial = 1;
}
if(temp == sum)
printf(―YES‖);
else
printf(―NO‖);
return 0;
}

TCS Ninja Coding question 7:


Write a C program which will convert a given decimal integer number N to its binary equivalent. The given
number N, a positive integer, will be passed to the program using the first command line parameter. Print the
equivalent binary number to stdout. Other than the binary number, no other extra information should be printed
to stdout Example: Given input ―19‖, here N=19, expected output 10011

Solution:

#include
#include
int main(int a, char *argv[])
{
int number, count, i;
int b[32];
number = atoi(argv[1]);
count = 0;
while(number != 0)
{
b[count]=number%2;
number = number/2;
count++;
}
for(i=(count-1); i>=0; i–)
printf(―%d‖, b[i]);
return 0;
}

TCS Ninja Coding question 8:


Write a c program that will find the sum of all prime numbers in a given range. The range will be specified as
command line parameters. The first command line parameter, N1 which is a positive integer, will contain the
lower bound of the range. The second command line parameter N2, which is also a positive integer will contain
the upper bound of the range. The program should consider all the prime numbers within the range, excluding
the upper bound and lower bound. Print the output in integer format to stdout. Other than the integer number,
no other extra information should be printed to stdout. Example Given inputs ―7‖ and ―24‖ here N1= 7 and
N2=24, expected output as 83.

Solution:

#include
int main(int argc, char *argv[])
{
int N1, N2, j, i, count, sum = 0;
N1 =atoi(argv[1]);
N2 =atoi(argv[2]);
for(i=N1+1; i<N2; ++i)
{
count = 0;
for(j=2; j<=(i/2); j++)
{
if(i%j==0)
{
count++;
break;
}
}
if(count==0)
sum = sum + i;
}
printf(―%d‖,sum);
return 0;
}

Brought to you by the N. Rajeev Reddy | More n More @ www.matterhere.com | Google+ - Facebook/matterhere

TCS Ninja Coding question 9:


Write a C program to check whether the given number is a perfect square or not using command line
arguments.
Solution:

#include
#include
int main(int a, char *b[])
{
int n, i;
n= atoi(b[1]);
for(i = 0; i <= n; i++)
{
if(n == i * i)
{
printf(―YES‖);
return 0;
}
}
printf(―NO‖);
return 0;
}

TCS Ninja Coding question 10:


Write a C program to check whether the given number is Palindrome or not using command line arguments.

Solution:

#include
#include
int main(int a,int *b[])
{
int number, rem, sum = 0;
number = atoi(b[1]);
int copy = number;
while(number != 0)
{
rem =number%10;
sum = sum * 10 + rem;
number = number/10;
}
if(copy == sum)
printf(―Palindrome‖);
else
printf(―Not Palindrome‖);
return 0;
}

TCS Ninja Coding question 11:


Write a C program to convert the vowels to an uppercase in a given string using command line arguments.

Example: if the input is tata, then the expected output is tAtA.


Solution:

#include
int main(int argc, char *argv[])
{
char *str = argv[1];
int i;
for(i =0; str[i] !=‘\0′; i++)
{
if(str[i] == ‗a‘ || str[i] == ‗e‘ || str[i] == ‗i‘ || str[i] == ‗o‘ || str[i] == ‗u‘)
{
str[i] = str[i] – 32;
}
}
printf(―%s‖, str);
return 0;
}

TCS Ninja Coding question 12:


Write a C program to find the hypotenuse of a triangle using command line arguments.

Solution:

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


{
float hyp;
int opp=atoi(b[1]);
int adj=atoi(b[2]);
hyp=sqrt((opp*opp)+(adj*adj));
printf(―%0.2f‖,hyp);
return 0;
}

TCS Ninja Coding question 13:


Write a C program to find whether the given number is an Armstrong number or not using command line
arguments.

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the
number itself. For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371.

Solution:

#include
#include
#include int main(int a, char*b[])
{
int n;
n= atoi(b[1]);
int sum=0;
int temp=n;
int cnt=0;
while(n!=0)
{
n=n/10;
cnt++;
}
n=temp;
while(n!=0)
{
int rem=n%10;
sum=sum+pow(rem,cnt);
n=n/10;
}
if(temp==sum)
{
printf(―yes‖);
}
else
{
printf(―no‖);
}
return 0;
}

TCS Ninja Coding question 14:


Write a program to generate Fibonacci Series.

Solution:

#include
#include
int main(int a, char *b[])
{
int i, n, t1 = 0, t2 = 1, nextTerm;
n=atoi(b[1]);
for (i = 1; i <= n; ++i)
{
printf(―%d ―, t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}

Brought to you by the N. Rajeev Reddy | More n More @ www.matterhere.com | Google+ - Facebook/matterhere
TCS Ninja Programming MCQ’s

TCS Ninja mock test – Programming MCQ’s (Standard)

1)

#include
int main(int argc, char ** argv)
{
char **items;
int j = 3, i;
items = argv;
for(i = 1; (i%4); i++)
{
int **p = &items[j];
printf(―%c‖, **p);
j–;
}
return 0;
}

The above code is run with three command line parameters mentioned below:

Paper Ink Pen

What will be the output of the above program?

1. PIP
2. Pen
3. Pap
4. Ink

Answer: a

2) Improper formation of which of the following data-structures can cause un-intentional looping of a program
that uses it.

2. Linked list
3. Array
4. Queue
5. Stack

Answer: Linked list

3) What is the data type that occupies the least storage in ―C‖ language?

Please give the answer in the blank line: __________

Answer: char
4) Which of the following is true?

a. Array is a dynamic data structure whose size can be changed while stacks are static data structures whose
sizes are fixed.
b. Array elements can be accessed and modified(elements can be added or removed) only at the ends of the
array while any elements of the stack can be accessed or modified randomly through their indices.
c. An array can have elements of different data types.
d. Elements of a linked-list can be accessed only sequentially.

Answer: d

5) Which of the following statements is FALSE?


a. The time complexity of binary search is O(log n).
b. A linear search requires a sorted list.
c. A binary search can operate only on a sorted list.
d. The time complexity of linear search is O(n).

Answer: b

6) Eesha wrote a function fact( ) in ―C‖ language to calculate factorial of a given number and saved the file as
fact.c. She forgot to code the main function to call this fact function. Will she be able to compile this fact.c
without the main() function?
a. Yes, she can compile provided the compiler option -nostrict-checking is enabled.
b. No, she can not compile as main function is required to compile any C program file.
c. Yes, she can compile as main( ) is not required at compile time.
d. Yes, she can compile and run as the system will supply default values to fact function.

Answer: b

7) The difference between variable declaration and variable definition is:


a. Declaration and definition are the same. There is no difference.
b. A declaration is used for variables and definitions is used for functions.
c. Declaration associates type to the variable whereas definition associates scope to the variable.
d. Declaration associates type to the variable whereas definition gives the value to the variable.

Answer: d

TCS Ninja Mock test Questions – Programming Concepts (Advanced Section)

1) The inorder and preorder traversal of a binary tree are d b e a f c g and a b d e c f g, respectively. The post-
order traversal of the binary tree is:
a. d e b f g c a
b. d e f g b c a
c. e d b f g c a
d. e d b g f c a

Answer: a
2) Eesha wrote a recursive function that takes the first node in a linked list as an argument, reverses the list,
returning the first Node in the result. The pseudo code for this function is given below. However, she did not
get the correct result. In which line number did she make a mistake?

Please give the answer in the blank line: ____________

public Node reverse(Node first)


{
if (first == null) return null;
if (first.next == null) return first;
Node second = first.next;
Node rest = reverse (second);
second.next = first;
first.next = null;
return rest.next;
}

Answer: return rest

3) The longest common subsequence (LCS) problem is the problem of finding the longest subsequence
common to a set of sequences (often just two sequences). A subsequence is a sequence that can be derived from
another sequence by deleting some or no elements without changing the order of the remaining elements. One
form of implementation of LCS function is given below. The function takes as input sequences X[1…m] and
Y[1…n], computes the length of the Longest common subsequence between X[1..i] and Y[1..j] for all 1<i < m
and 1< j < n, and stores it in C[i,j]. C[m,n] will contain the length of the LCS of X and Y.

function LCSLength(X[1..m], Y[1..n])


C = array(0..m, 0..n)
for i:= 0..m
C[i,0] =0
for j := 0..n
C[0,j] = 0d
for i := 1..m
for j := 1..n
if X[i] = Y[j]
C[i,j] := C[i-1, j-1] + 1
else
C[i,j] := max(C[i, j-1], C[i-1, j])
return C[m, n]

Eesha used the above algorithm to calculate the LCS length between ―kitten‖ and ―string‖. What was the result
she got? Please give the answer in the blank line. ___________

Answer: 2

Brought to you by the N. Rajeev Reddy | More n More @ www.matterhere.com | Google+ - Facebook/matterhere
TCS Ninja Programming MCQ’s (previously asked)
1) How many times the below loop will be executed?

#include
int main()
{
int x, y;
for(x=5;x>=1;x–)
{
for(y=1;y<=x;y++)
printf(―%d\n‖,y);
}}

A. 15
B. 11
C. 10
D. 13

Solution: Option A

2) Where are the local variables stored?

A. Disk
B. Stack
C. Heap
D. Code

Solution: Option B

3) Which datatype has more precision?

A. double
B. float
C. int
D. long int

4) Find the output of the following code?

int main
{
float f = 0.1;
if (f = 0.1)
printf (―yes‖);
else print (―no‖);
}

5) What will happen if in a C program you assign a value to an array element whose subscript exceeds the size
of array?
A. The element will be set to 0.
B. The compiler would report an error.
C. The program may crash if some important data gets overwritten.
D. The array size would appropriately grow.

Solution: Option C

Explanation: If the index of the array size is exceeded, the program will crash. Hence ―option c‖ is the correct
answer. But the modern compilers will take care of this kind of errors.

6) What does the following declaration mean?

int (*ptr)[10];

A.ptr is array of pointers to 10 integers


B.ptr is a pointer to an array of 10 integers
C.ptr is an array of 10 integers
D.ptr is an pointer to array

Solution: Option B

7) In C, if you pass an array as an argument to a function, what actually gets passed?

A.Value of elements in array


B.First element of the array
C.Base address of the array
D.Address of the last element of array

Solution: Option C
Explanation: The statement ‗C‘ is correct. When we pass an array as a function argument, the base address of
the array will be passed.

8) What will be the output of the program ?

#include
int main()
{
int a[5] = {5, 1, 15, 20, 25};
int i, j, m;
i = ++a[1];
j = a[1]++;
m = a[i++];
printf(―%d, %d, %d‖, i, j, m);
return 0;
}

A. 2, 1, 15
B. 1, 2, 5
C. 3, 2, 15
D. 2, 3, 20

Solution: Option C
Explanation:
Step 1: int a[5] = {5, 1, 15, 20, 25}; The variable arr is declared as an integer array with a size of 5 and it is
initiapzed to
a[0] = 5, a[1] = 1, a[2] = 15, a[3] = 20, a[4] = 25 .
Step 2: int i, j, m; The variable i,j,m are declared as an integer type.
Step 3: i = ++a[1]; becomes i = ++1; Hence i = 2 and a[1] = 2
Step 4: j = a[1]++; becomes j = 2++; Hence j = 2 and a[1] = 3.
Step 5: m = a[i++]; becomes m = a[2]; Hence m = 15 and i is incremented by 1(i++ means 2++ so i=3)
Step 6: printf(―%d, %d, %d‖, i, j, m); It prints the value of the variables i, j, m
Hence the output of the program is 3, 2, 15

9) Is there any difference int the following declarations?

int fun(int arr[]);

int fun(int arr[2]);

A.Yes
B.No

Solution: Option B
Explanation: No, both the statements are same. It is the prototype for the function fun() that accepts one
integer array as a parameter and returns an integer value.

10) Are the expressions arr and &arr same for an array of 10 integers?

A.Yes
B.No

Solution: Option B
Explanation: Both mean two different things. arr gives the address of the first int, whereas the &arr gives the
address of array of ints.

11) Which of the fplowing statements should be used to obtain a remainder after dividing 3.14 by 2.1?

A.rem = 3.14 % 2.1;


B.rem = modf(3.14, 2.1);
C.rem = fmod(3.14, 2.1);
D.Remainder cannot be obtain in floating point division.

Solution: Option C
Explanation:
fmod(x,y) – Calculates x modulo y, the remainder of x/y.
This function is the same as the modulus operator. But fmod() performs floating point divisions.

Brought to you by the N. Rajeev Reddy | More n More @ www.matterhere.com | Google+ - Facebook/matterhere
12) What are the types of pnkages?

A.Internal and External


B.External, Internal and None
C.External and None
D.Internal

Solution: Option B

13) Which of the following special symbols are allowed in a variable name?

A.* (asterisk)
B.| (pipepne)
C.-(hyphen)
D._(underscore)

Solution: Option D

Explanation: Variable names in C are made up of letters (upper and lower case) and digits. The underscore
character (―_‖) is also permitted. Names must not begin with a digit.

14) Is there any difference between fplowing declarations?

1 : extern int fun();

2 : int fun();

A. Both are identical


B. No difference, except extern int fun(); is probably in another file
C. int fun(); is overrided with extern int fun();
D. None of these

Answer: Option B

Explanation: extern int fun(); declaration in C is to indicate the existence of a global function and it is defined
externally to the current module or in another file.
int fun(); declaration in C is to indicate the existence of a function inside the current module or in the same file.
TCS Ninja English questions

TCS Ninja Mock test questions and solutions – English section

A greenhouse is a glass-covered structure (1) __________ (uses, using, used) to grow plants. It has transparent
glass that allows sunlight to pass (2) ________ (out, through , inside), but does not allow the heat inside to
escape. The same (3) ________ (effect, affect) occurs on the earth. The (4) ________ (sun‘s, suns, sun)
radiation (5) __________ (passes, passing) through the atmosphere to heat the earth‘s surface. When heated, the
earth‘s surface produces infrared radiation, which has a longer wavelength than that of sunlight. This infrared
radiation rises into the atmosphere where gases, such as carbon dioxide, (6) ____________ (prevents, prevent,
prevented) the infrared radiation from escaping into space. The concentrations of these gases, (7) __________
(that, those, which) are called greenhouse gases, control how much-infrared radiation escapes.

(1) used

(2) through

(3) effect

(4) sun‘s

(5) passes

(6) prevent

(7) which

Brought to you by the N. Rajeev Reddy | More n More @ www.matterhere.com | Google+ - Facebook/matterhere

TCS Ninja English questions (sample questions)


1) Read each sentence to find out whether there is any grammatical error in it. The error, if any will be in one
part of the sentence. The letter of that part is the answer. If there is no error, the answer is ‗D‘. (Ignore the
errors of punctuation, if any).

a. I could not put up in a hotel


b. because the boarding and lodging charges
c. were exorbitant.
d. No error.

Answer: a
‗I could not put up at a hotel‘

2)
a. A lot of travel delay is caused
b. due to the inefficiency and lack of good management
c. on behalf of the railways.
d. No error.

Answer: c
on the part of the railways

3)

a. Having received your letter


b. this morning, we are writing
c. to thank you for the same.
d. No error.

Answer: D

4)

a. Do the roses in your garden smell


b. more sweetly
c. than those in ours?
d. No error.

Answer: B
sweeter

5)

a. The students were


b. awaiting for
c. the arrival of the chief guest.
d. No error.

Answer: b

6) Identify the meaning of the idiom: To catch a tartar

a. To trap wanted criminal with great difficulty


b. To catch a dangerous person
c. To meet with disaster
d. To deal with a person who is more than one‘s match

Answer: b
7) To have an axe to grind

a. A private end to serve


b. To fail to arouse interest
c. To have no result
d. To work for both sides

Answer: a

8) Complete the below sentences: I felt somewhat more relaxed _______

a. but tense as compared to earlier


b. and tense as compared to earlier
c. as there was already no tension at all
d. and tension-free as compared to earlier

Answer: d

9) His appearance is unsmiling but _______

a. his heart is full of compassion for others


b. he looks very serious on most occasions
c. people are afraid of him
d. he is uncompromising on matters of task performance

Answer: a

10) DIVA: OPERA

a. producer:theatre
b. director:drama
c. conductor:bus
d. thespian:play

Answer: d

11) GRAIN:SALT

a. shard:pottery
b. shred:wood
c. blades:grass‘
d. chip:glass
Answer: d
TCS Ninja Aptitude questions
TCS Ninja Mock test questions and solutions – Aptitude (Standard section)

1) A^B means A raised to the power B. If f(x) = ax^4 – bx^2 + x + 5 and f(-3) = 2, then f(3) = ?
a. 3
b. 8
c. -2
d. 1

Answer: b

Explanation:
f(-3) = a(-3)4 – b(-3)2 + (-3) + 5 = 81a – 9b + 2 = 2 So 81a – 9b = 0,
f(3) = a(3)4 – b(3)2 + (3) + 5 = 81a – 9b + 8
Substituting the value of 81a – 9b = 0 in the above we get f(3) = 8

2) 1/4 of the tank contains fuel. When 11 liters of the fuel is poured into the tank, the indicator rests at the 1/2
mark. Find the capacity of the tank in liters.

a. 44
b. 36
c. 6
d. 8

Answer: a

Explanation:
Let the capacity of the tank be x liters.
Given, 1/4 of x + 11 = 1/2 of x
By solving we get the x value as 44 liters.

3) You have been given a physical balance and 7 weights of 47, 46, 43, 48, 49, 42, and 77 kgs. Keeping weights
on one pan and object on the other, what is the maximum you can weigh less than 178 kgs.

a. 172
b. 174
c. 175
d. 177

Answer: b

Explanation:
The maximum weight that can be weighed less than 178 kgs is 174 (48 + 49 + 77 = 174 kgs).

Brought to you by the N. Rajeev Reddy | More n More @ www.matterhere.com | Google+ - Facebook/matterhere
4) How many 6-digit even numbers can be formed from the digits 1, 2, 3, 4, 5, 6 and 7 so that the digits should
not repeat and the second last digit is even?

a. 320
b. 6480
c. 2160
d. 720

Answer: d

Explanation:
To form 6-digit even number, the last digit should be an even number so 3 ways (2, 4, or 6) to fill the last digit
and second last digit also should be even for which it will take 2 ways to fill.
The last two digits are filled in 6 ways( 2 x 3 = 6 ways). The rest of the 4 digits can be filled in 5P4 ways i.e.
120 ways. Hence altogether to fill 6-digit even number = 120 * 6 = 720 ways.

5) Out of a group of swans, 7/2 times the square root of the total number are playing on the shore of the pond.
The remaining 2 are inside the pond. Find the total number of swans.

a. 16
b. 25
c. 4
d. 9

Answer: a

Explanation:
Let the number of swans = x2
x2 = 7x/2 + 2 –> x2 = (7x + 4)/2
2x2 = 7x + 4, —> 2x2 – 7x – 4 = 0
The roots of x are 4, -1/2. Here -1/2 is not possible, so the x value will be 4.
The total number of swans is x2 i.e 16.

6) In a village, every weekend, three-eighth of the men and one-third of the women participate in a social
activity. If the total number of participants is 54, and out of them 18 are men then the total number of men and
women in the village is:

a. 180
b. 156
c. 204
d. 228

Answer: b

Brought to you by the N. Rajeev Reddy | More n More @ www.matterhere.com | Google+ - Facebook/matterhere
Explanation:
3/8th of men and 1/3rd of women participated and given that the total participants are 54.
Out of total participants 54, 18 were men and the rest will be women (54-18 = 36 women). From this, we can
say that –> 3/8 * men = 18, therefore men = 48. And 1/3 of women = 36 –> women = 108.
The total number of men and women in the village is 156.

7) If M is 30% of Q, Q is 20% of P, and N is 50% of P, then M/N = ?

a. 6/5
b. 4/3
c. 3/25
d. 3/250

Answer: c

Explanation:
Q = 20% of P
M = 30% of Q —> 30% of (20% of P) —> 30/ 100 * 20/100 * P –> 6/100 * p
N = 50% of P –> 5/10 * P
M/ N = (6/100 * P) / (5/10 * P) = 6/50 = 3/25

8) There are 20 persons among whom two are sisters. Find the number of ways in which we can arrange them
around a circle so that there is exactly one person between two sisters? Please note that the exact position on the
circle does not matter (no seat numbers are marked on the circle), and only the relative positions of the people
matter.

a. 2! * 19!
b. None of these
c. 2 * 18!
d. 18!

Answer: c

Explanation:
Fix the position of two sisters. Hence there are only 18 people left
So there are 18 ways in which a person can sit between the two sisters. Now if we swap the bothers we get
another 18 ways.
So hence we have a total of = 2 * 18 combinations
Consider the group of three people(two brothers and the person between them) as a single entity.
we have another 17 people left so there are 18 entities to be arranged in total.
Arranging 18 entities around a circle can be done in (18-1)! = 17! ways
Total no of ways = 2 * 18 * 17! = 2 * 18!

Brought to you by the N. Rajeev Reddy | More n More @ www.matterhere.com | Google+ - Facebook/matterhere
9) Find the length of the longest pole that can be placed in an indoor stadium 24m long, 18m wide and 16m
high.

a. 36m
b. 34m
c. 30m
d. 25m

Answer: b

Explanation:

Length of the longestt pole = diagonal of rectangular indoor stadium

= √( l²+b²+h²)
= √(24²+18²+16²)
= √(576+324+256)
= √1156
= 34 m

10) Of a set of 30 numbers, the average of first 10 numbers is equal to the average of last 20 numbers. Then the
sum of the last 20 numbers is:

a. Sum of first ten numbers


b. 2 X sum of the first ten numbers
c. Cannot be determined with the given data
d. 2 x sum of last ten numbers

Answer: b

Explanation:
Average = (sum of n numbers)/(n)
(sum of first 10 numbers)/10 = (sum of last 20 numbers)/20
Hence, (sum of last 20 numbers) = 2*(sum of first 10 numbers)

11) Thomas takes 7 days to paint a house completely whereas Raj would require 9 days to paint the same house
completely. How many days will it take to paint the house if both of them work together (give answers to the
nearest integer)?

a. 4 days
b. 2 days
c. 5 days
d. 3 days

Answer: a

Explanation:
Work done by Thomas in a day = 1/7
Work done by Raj in a day = 1/9
Work done by both in a day = 1/7 +1/9 =16/63
Days required if they both work together = 63/16 = 3.9 = 4 days

12) The University of Vikramasila has enrolled nine Ph.D. candidates: Babu, Chitra, Dheeraj, Eesha, Farooq,
Gowri, Hameed, Iqbal, Jacob.

– Farooq and Iqbal were enrolled on the same day as each other, and no one else was enrolled that day.
– Chitra and Gowri were enrolled on the same day as each other, and no one else was enrolled that day.
– On each of the other days of hiring, exactly one candidate was enrolled.
– Eesha was enrolled before Babu.
– Hameed was enrolled before Dheeraj.
– Dheeraj was enrolled after Iqbal but before Eesha.
– Gowri was enrolled after both Jacob and Babu.
– Babu was enrolled before Jacob.

Who were the last two candidates to be enrolled?

a. Eesha and Jacob


b. Babu and Chitra
c. Gowri and Chitra
d. Babu and Gowri

Answer: c

Explanation:
1. Easha < Babu
2. Hameed < Dheeraj
3. Iqbal < Dheeraj < Easha
4. Jacob/Babu < Gowri
5. Babu < Jacob
from 1 and 5, Easha was before Babu and Jacob so she cannot be in the last two. Option B ruled out
from 4 and 5, babu is before Jacob and Gowri so he cannot be in the last two. Options a, c ruled out.
So option d is correct.

13) In a certain city, 60 percent of the registered voters are Party A supporters and the rest are Party B
supporters. In an assembly election, if 75% of the registered Party A supporters and 20% of the registered Party
B supporters are expected to vote for Candidate A, what percent of the registered voters are expected to vote for
Candidate A?

a. 20
b. 60
c. 75
d. 53

Answer: d

Explanation:
let there be x number of registered voters
60% are Party A supporters = 60% of x
40% are Party B supporters = 40% of x
Out of 60%, 75% voted for party A = 75%(60% of x) = 18x/40
Out of 40% ,20% voted for party B = 20%(40% of x) = 8x/100
=18x/40+8x/100=106x/200
Percentage of registered voters expected to vote for A = 106x/200*100 = 53% of x

14) When 100 is to be successively divided by 6, 3, 4, first divide 100 by 6. Then divide the quotient 16 by 3.
Then divide the quotient 5 by 4.

A number when successively divided by 5, 3, 2 gives the remainder of 0, 2 and 1 respectively in that order.
What will be the remainders when the same number is divided successively by 2, 3 and 5 in that order?

a. 4, 1, 2
b. 1, 0, 4
c. 2, 1, 3
d. 4, 3, 2

Answer: b

15) Professor Nitwit obtains a hash number of a given positive integer > 3 as follows. He subtracts 2 from the
number (to get the new number), and multiplies the new number by 2 to get a term. He repeats this with the
new number (to get newer numbers and terms) until the number becomes 2 or 1. The hash is defined as the sum
of all the terms generated in this process.

For example, with the number 5, he multiplies (5-2 =3) by 2 to get the first term 6. He multiplies (3-2=1) by 2
to get the second term 2. As the number has become 1, he stops. The hash is the sum of the two terms (6+2) or
8.

If professor Nitwit is given 3 numbers 4, 9 and 13, what is the sum of the hash numbers he obtains for the three
numbers?

TCS Ninja Mock test questions and solutions – Aptitude (Advanced section)

1) How many pairs (m,n) of integers satisfy the equation 4^m = n^2 + 15? Please do not add white space
around the answer _____________

Answer: 4

2) Of all the nonempty subsets S of { 1, 2, 3, 4, 5, 6, 7}, how many do not contain the number |S|, where |S|
denotes the number of elements in S? For example, {3, 4} is one such subset, since it does not contain the
number 2. Please do not add white space around the answer ____________

Answer: 63

3) A chord of a circle has length 3n, where n is a positive integer. The segment cut off by the chord has height
n, as shown. What is the smallest value of n for which the radius of the circle ia also a positive integer? Please
do not add white space around the answer ________
Answer: 8

4) A function f satisfies f(0) = 0, f(2n) = f(n), and f(2n + 1) = f(n) + 1 for all positive integers n. What is the
value of f(2018)? Please do not add white space around the answer ___________

5) If n is a positive integer, let s(n) denote the integer obtained by removing the last digit of n and placing it in
front. For example, s(731) = 173. What is the smallest positive integer n ending in 6 satisfying s(n) = 4n?.
Please do not add white space around the answer ____________

Brought to you by the N. Rajeev Reddy | More n More @ www.matterhere.com | Google+ - Facebook/matterhere

TCS Ninja Aptitude questions (previously asked)


1. On a 26 question test, five points were deducted for each wrong answer and eight points were added for each
correct answer. If all the questions were answered, how many were correct, if the score was zero?

a. 10
b. 12
c. 11
d. 13

Ans: a

Explanation:
Let x be the number of questions correct and therefore, (26- x) will be the wrong number of questions,
8x – 5(26-x) = 0 –> 8x – 130 + 5x =0
13x = 130, x =10
Hence 10 questions were correct.

2. Jake can dig a well in 16 days. Paul can dig the same well in 24 days. Jake, Paul and Hari together dig the
well in 8 days. Hari alone can dig the well in

a. 96 days
b. 48 days
c. 32 days
d. 24 days

Ans: b

Explanation:
Let the total work to be done is 48 meters( LCM of 16, 24 and 8). Now Jake can dig (48/16) – 3 meters, Paul
can dig (24/12) – 2 meters a day. Now all of them combined dug in 8 days so per day they dug 48/8 = 6 meters.
So Of these 8 meters, Hari capacity is 1 meter. So he takes 48 /1 = 48 days to complete the digging job.

3. Mark told John ―If you give me half your money I will have Rs.75‖. John said, ―if you give me one-third of
your money, I will have Rs.75/- How much money did John have?
a. 45
b. 60
c. 48
d. 37.5

Ans: b

Explanation:
Let the money with Mark and John are M and J respectively.
Now
M + J/2 = 75
M/3 + J = 75
Solving we get M = 45, and J = 60.

4. The value of a scooter depreciates in such a way that its value of the end of each year is 3/4 of its value of the
beginning of the same year. If the initial value of the scooter is Rs.40,000, what is the value at the end of 3
years?

a. Rs.13435
b. Rs.23125
c. Rs.19000
d. Rs.16875

Ans: d

Explanation:
Every year it depreciates 3/4 th of the previous year. So ( 3/ 4 x (3/4 x (3/4 of 40,000))) = 3*3*3*625 = 16875.
Hence the value after 3 years is Rs. 16875

5. A man has a job, which requires him to work 8 straight days and rest on a ninth day. If he started work on
Monday, find the day of the week on which he gets his 12th rest day.

a. Thursday
b. Wednesday
c. Tuesday
d. Friday

Ans: b

Explanation:
He works for 8 days and takes rest on the 9th day. So On the 12th rest day, there are 9 x 12 = 108 days passed.
Number of odd days = (108 – 1) / 7 = 107 / 7 = 2. So the 12th rest day is Wednesday.

6. George can do a piece of work in 10 days, Paul in 12 days and Hari in 15 days. They all start the work
together, but George leaves after 2 days and Paul leaves 3 days before the work is completed. In how many
days is the work completed?
a. 5
b. 6
c. 9
d. 7

Ans: d

Explanation:
Let the work be 60 units(LCM of 10, 12 and 15). If Paul worked for 3 days, and the remaining days of work are
x days, total days to complete the work be x + 3 days. Now George‘s is 60/10 = 6, Paul is 5, Hari is 4.
(6 + 5 + 4) 2 + (5 + 4) (x – 3) + 5 x 3 = 60. On solving we get x = 4. So total days to complete the work is 7
days.

7. How many arrangements will start and end with a vowel for TOGETHER?

a. 1060
b. 1080
c. 2024
d. 1050

Ans: a

Explanation:
No. of ways to put a vowel on start and end = 3 (i.e O..E, E..O, E..E ). The number of ways to arrange other 6
letters = 6!/2! = 360 (letter T is two times). Total number of arrangements = 3*360 = 1080.

8. In 4 years, Raj‘s father age is twice as raj, Two years ago, Raj‘s mother‘s age twice as raj. If Raj is 32 years old in eight
years from now, what is the age of Raj‘s mother and father?

a. 32,34
b. 51,50
c. 32,36
d. 52,46

Ans: d

Explanation:

Raj present age = 32 – 8 = 24.


After 4 years Raj‘s age is 28. and Raj‘s father‘s age is 28 x 2 = 56, and his present age is 52.
Two years ago, Raj‘s age is 22. and his mother‘s age is 22 x 2 = 44. His mother‘s present age = 46
9. A call center agent has a list of 305 phone numbers of people in alphabetic order of names (but she does not have any
of the names). She needs to quickly contact Deepak Sharma to convey a message to him. If each call takes 2 minutes to
complete, and every call is answered, what is the minimum amount of time in which she can guarantee to deliver the
message to Mr. Sharma?

a. 18 minutes
b. 610 minutes
c. 206 minutes
d. 34 minutes

Ans: a

Explanation:
The call center calls the middle no. i.e. (305/2) = 152.5 say 152 and asks them their name to get an idea of whether to go
to up or downside of 152 no directory and suppose person replies some name. The starting letter of the name will suggest
the call center to decide to weather go up or down the name list.
So the process goes like >305->152–>76–>38–>19–>9–>4–>2–>1, the minimum time = 9*2 = 18 mins.

10. In how many ways a team of 11 must be selected from 5 men and 11 women such that the team must
comprise of not more than 3 men?

a. 1565
b. 2456
c. 1243
d. 2256

Ans: d

Explanation:
The team may consist of 0 men + 11 women, 1 men + 10 women, 2 men + 9 women, or 3 men + 8 women.So
Number of ways are = 11C11+5C1 ×× 11C10+5C2 ×× 11C9+5C3 ××11C8 = 2256 ways.
11. Given that 0 < a < b < c < d, which of the following the largest?

a. (c+d) / (a+b)
b. (b+d) / (a+c)
c. (b+c) / (a+d)
d. (a+d) / (b+c)

Ans: a

Explanation:
Let‘s assume the value of a , b, c and d as 1, 2, 3, 4 (a=1, b=2, c=3, and d=4), by solving we get the answer
as (c+d) / (a+b).
12. Eesha bought 18 sharpeners for Rs.100. She paid 1 rupee more for each white sharpener than for each
brown sharpener. What is the price of a white sharpener and how many white sharpeners did she buy?

a. Rs. 5, 10
b. Rs. 6, 8
c. Rs. 6, 10
d. Rs. 5, 8

Ans: c

Explanation:
Let‘s solve from the options, if she bought 10 white sharpeners at Rs.6 per piece, She has spent Rs.60
already. And with the remaining Rs.40, she bought 8 brown sharpeners at 40/8 = Rs.5 which is Rs.1 less than
the White sharpener. Hence Rs. 6 and 10 white sharpeners.

13. The sum of the digits of a three digit number is 17, and the sum of the squares of its digits is 109. If we
subtract 495 from the number, we shall get a number consisting of the same digits written in the reverse order.
Find the number.

a. 683
b. 863
c. 944
d. 773

Ans: b

Explanation:
Let‘s solve from the options, Sum of the squares should be equal to 109. Only Options a and b satisfying. When
we subtract 495, only 863 becomes 368.

14. Raj goes to the market to buy oranges. If he can bargain and reduce the price per orange by Rs.2, he can buy
30 oranges instead of 20 oranges with the money he has. How much money does he have?

a. Rs. 50
b. Rs. 150
c. Rs. 120
d. Rs. 100

Ans: d

Explanation:
Let the money with Raj is M. So (M/20) – (M/30) = 2. Check options. Option c satisfies.
15. A city in the US has a basketball league with three basketball teams, the Aziecs, the Braves and the
Celtics. A sportswriter notices that the tallest player of the Aziecs is shorter than the shortest player of the
Braves. The shortest of the Celtics is shorter than the shortest of the Aziecs, while the tallest of the Braves is
shorter than the tallest of the Celtics. The tallest of the Braves is taller than the tallest of the Aziecs.
Which of the following can be judged with certainty?

X) Paul, a Brave is taller than David, an Aziec


Y) David, a Celtic, is shorter than Edward, an Aziec

a. Both X and Y
b. X only
c. Y only
d. Neither X nor Y

Ans: B

Explanation:
By assuming the values, let‘s solve it. Be the shortest of Braves is 4 feet, then tallest of Aziecs is less than 4. So
let it be 3 feet. A -> 2 – 3, B -> 4 – 6, C -> 1 – 7. From the above, we can safely conclude X is correct. but Y
cannot be determined.

16. A BB CCC DDDD EEEEE….. What is the 120th letter?

a. L
b. O
c. K
d. N

Ans: b

Explanation:
Number of letters in each term are in AP. 1, 2, 3, … So, n(n+1)/2 <= 120. For n = 15, we get LHS = 120. So
15th letter in the alphabet is O. So 15th term contains 15 Os.

17. There are 120 male and 100 female in a society. Out of 25% male and 20% female are rural. 20% of male
and 25% of female rural people passed in the exam. What % of rural students have passed the exam?

a. 20%
b. 18%
c. 22%
d. 15%

Ans: c
Explanation:
From the given information, Rural male = 25%(120) = 30, Rural female = 20%(100) = 20. Passed students
from rural: male = 20%(30) = 6, female = 25%(20) = 5. Required percentage = 11/50 * 100 = 22%.

18. On the fabled Island of Knights and Knaves, we meet three people, A, B, and C, one of whom is a knight,
one a knave, and one a spy. The knight always tells the truth, the knave always lies, and the spy can either lie or
tell the truth. A says: ―C is a knave.‖B says: ―A is a knight.‖C says: ―I am the spy.‖Who is the knight, who the
knave, and who the spy?

a. A – Knight, B – Knave, C – Spy


b. A – Spy, B – Knight, C – Knave
c. A – Knave, B – Spy, C – Knight
d. A – Knight, B – Spy, C – Knave

Ans: d

Explanation:
Let us say A is Knight and speaks the truth. So C is Knave and B is a spy. So Cs statement is false and Bs
statement is true. This case is possible. If B is Knight, this is not possible as A also becomes Knight as B
speaks the truth.
Suppose C is Knight, this is clearly contradicted by C‘s statement itself.

19. The average temperature of Tuesday, Wednesday and Thursday is 37 C. The average temperature of
Wednesday, Thursday and Friday is 38 C. If the temperature on Friday is 39 C. Find the temperature on
Tuesday.

a. 37.33
b. 38.33
c. 36
d. None of the above

Ans: c

Explanation:
The average temperature of Tuesday, Wednesday and Thursday is (Tue + Wed + Thu) / 3 = 37
Tue + Wed + Thu = 111 —— (A)
The average temperature of Wednesday, Thursday and Friday is (Wed + Thu + Fri) / 3 = 38
Wed + Thu + Fri = 114 ——- (B)
Given Friday‘s temperature as 39, then (B) – (A) –> Fri – Tue = 3. So 39 – Tue = 3 –> Tue = 36.
Hence, the temperature on Tuesday is 36

Brought to you by the N. Rajeev Reddy | More n More @ www.matterhere.com | Google+ - Facebook/matterhere

20. In a certain city, 60% of the registered voters are Congress supporters and the rest are BJP supporters. In an
assembly election, if 75% of the registered congress supporters and 20% of the registered BJP supporters are
expected to vote for candidate A, what percent of the registered voters are expected to vote for candidate A?
a. 20
b. 23
c. 50
d. 53

Ans: d

Explanation:
Let the people in the city be 100, Congress supporters = 60% of 100 = 60 and 40% are BJP=40% of 100 = 40.
Out of 60, 75% voted for congress=75%(60)=45
Out of 40%,20% voted for congress=20%(40)=8
In total = 45 + 8 = 53, Hence the total percentage of registered candidates – 53%

Brought to you by the N. Rajeev Reddy | More n More @ www.matterhere.com | Google+ - Facebook/matterhere

Practice sheet ________________________________________________

You might also like