Codetantra TCS PDF
Codetantra TCS PDF
Codetantra TCS PDF
During execution, the program should print the message on the console as:
Enter a number :
For example, if the user gives the input as 2:
Enter a number : 2
Then the program should print the result as follows:
The square root is : 1.414214
Note - 1:Consider the input and output as double data type.
Note - 2: Use the printf() function with a newline character (\n) at the end.
Q2. GRID GAME:
Julia is playing a game on an infinite two-dimensional grid, where the bottom left cell is referenced as (1,
1) and each cell contains an initial value of 0. The game consists of n steps; during each step:
1. Julia has two integers, r and c.
2. Julia increments the value in every (i, j) cell satisfying 1 ≤ i ≤ r and 1 ≤ j ≤ c by 1.
After performing n such steps, Julia finds the maximum value x, in any cell on the board, and counts the
number of occurrences of x.
Complete the program in the editor below. It has the following:
Name: steps
Type: string array
Description: Each index contains a string of two space-separated integers describing the respective values
of r and c for a step.
The program must return a long integer denoting the total number of occurrences of the greatest
integer x in the grid after n steps.
Input Format:
The first line contains an integer, n, denoting the number of elements in steps.
Each of the n subsequent lines contains a string of two space-separated integers describing an index
in steps.
Constraints
· 1 ≤ n ≤ 100
· 1 ≤ r, c ≤ 106
Output Format:
Return a long integer denoting the total number of occurrences of the greatest integer x in the grid
after n steps.
Sample Input
3
23
Page 2
37
41
Sample Output
2
Explanation
Given steps = ["2 3", "3 7", "4 1"]:
The portion of the infinite grid corresponding to cells (i, j) where 1 ≤ i ≤ 4 and 1 ≤ j ≤ 7.
After performing all n = 3 steps, the maximum x value in any cell is 3. Because there are two such cells with
this maximal value, we return 2 as our answer.
Note: Do use the printf() function with a newline character (\n) at the end.
Q3. PAIR OF TWO NUMBERS IN AN ARRAY:
Complete the program that has - an array of integers a, and an integer k. The program must return an
integer denoting the number of distinct pairs, (ai, aj)where i ≠ j, in a such that ai + aj = k.
Note: Pairs (ai, aj) and (aj, ai) are considered to be the same because they are both composed of the
same 2 elements; however, while i ≠ j, the value of ai may be equal to aj. In addition, two pairs (ai,
aj) and (ak, am) are considered to be the same if (ai ≡ ak and aj ≡ am) or (ai ≡ am and aj ≡ ak), meaning that
both pairs are composed of different elements but the same integer values. See Explanation for more
detail.
Constraints
· 1 ≤ n ≤ 5 × 105
· 0 ≤ a[i] ≤ 109
· 0 ≤ k ≤ 5 × 109
Input Format:
The locked stub code assembles the following inputs from stdin and passes them to your function:
The first line contains an integer, n, denoting the size of a. Each of the n subsequent lines describes an
element in a. The next line contains an integer, k.
Output Format:
Your function must return the number of pairs of unique/distinct pairs in a having a sum equal to k.
Sample Input:
6
1
3
46
1
3
9
47
Sample Output:
1
Explanation:
Page 3
Sample Case 1:
a = [1, 3, 46, 1, 3, 9], k = 47
There are 4 pairs of unique elements where ai + aj = k:
1. (a0 = 1, a2 = 46)
2. (a2 = 46, a0 = 1)
3. (a2 = 46, a3 = 1)
4. (a3 = 1, a2 = 46)
In the list above, pairs 1 and 2 are equivalent, as are pairs 3 and 4 (because they both use the same i and j).
In addition, all four pairs contain the same values. Thus, we only have 1distinct pair, (1, 46), so our function
returns 1.
Sample Case 2:
a = [6, 6, 3, 9, 3, 5, 1], k = 12
There are 5 unique pairs where ai + aj = k:
1. (a0 = 6, a1 = 6)
2. (a1 = 6, a0 = 6)
3. (a2 = 3, a3 = 9)
4. (a3 = 9, a2 = 3)
5. (a3 = 9, a4 = 3)
6. (a4 = 3, a3 = 9)
In the list above, pair 1 ≡ pair 2, pair 3 ≡ pair 4, and pair 5 ≡ pair 6 (because they all use the same i and j). In
addition, pairs 3 through 6 all contain the same values. Thus, we only have 2 distinct pairs, (6, 6) and (3, 9),
so our function returns 2.
Note: Do use the printf() function with a newline character (\n) at the end.
Q4. RAILWAY – SEATING ARRANGEMENT FOR SLEEPER CLASS
Page 4
Write a program to determine the type of berth when the seat / berth number in the train is given.
Input Format:
Input consists of a single integer. Assume that the range of input is between 1 and 72.
Output Format:
Output consists of a single string. [Upper or Middle or Lower or Side Lower or Side Upper]
Sample Input 1:
9
Sample Output 1:
Lower
Sample Input 2:
72
Sample Output 2:
Side Upper
Write a C program that accepts an integer as input and displays the corresponding month in words.
[January, February, March, April, May, June, July, August, September, October, November, December]. Use
Switch statement.
Input Format:
Input consists of a single integer.
Output Format:
Refer sample output for details.
Sample Input 1:
3
Sample Output 1:
March
Sample Input 2:
55
Sample Output 2:
Invalid month
Input Format:
Input consists of 2 integers. The first integer corresponds to the last 2 digits of the birth year. The second
integer corresponds to the last 2 digits of the current year.
Output Format:
Refer sample input and output for further formatting specifications.
Output
Your age is 37
The program will have to determine when a two-digit value such as "62" corresponds to a year in the 20th
century ("1962") or the 21st century. Here is another run of the program, where "00" is taken to mean the
year 2000.
Input
Enter Year of Birth : 62
Enter Current year : 00
Page 6
Output
Your age is 38
Assume that ages are not negative. Another run of the program:
Input
Enter Year of Birth : 27
Enter Current year : 07
Output
Your age is 80
In the following run, the age of the person could be 6 or 106 depending on the assumptions. Assume that
the age will always be less than or equal to 100.
Input
Output
Your age is 6
Input
Enter Year of Birth : 62
Enter Current year : 99
Output
Your age is 37
Input Format:
Input consists of 2 integers. The first integer corresponds to the number of students in college 1 and the
second integer corresponds to the number of students in college 2.
Q8. BLOOD BANK
A team from Rotract Club had planned to conduct a rally to create awarness among the Coimbatore people
to donate blood. They conducted the rally successfully. Many of the coimbatore people realized it and came
forward to donate their blood to near by blood bank. The eligibility criteria for donating blood is people
should be above 18 and his/ her weight should be above 40. There was a huge crowd and staff in blood
bank found it difficult to manage the crowd. So they decided to keep a system and ask the people to enter
their age and weight in system. If a person is eligible he / she will be allowed inside.
Write a program and feed it to the system to find whether a person is eligible or not.
Page 7
Input Format:
Input consists of two integers which corresponds to age and weight of a person respectively.
Output Format:
Display whether the person is eligible or not.
Output
Eligible to donate.
Output
Not Eligible to donate.
Output Format:
Output consists of the string “College 1 is better” or “College 2 is better”. Refer sample input and output for
further formatting specifications.
Output
College 2 is better
Input Format:
Input Consists of Single Integer which Corresponds to Number pressed by the user to the doll.
Output Format:
Display whether the doll will Sing or not. Output consists of the string "Doll will sing" or "Invalid number".
Output
Doll will sing
Input format:
Inputs consists of a single integer which corresponds to number printed on the balloon. Assume that the
input value is between 1 and 50.
Output Format:
Display whether the given Balloon will fly to Miney or Not.
Output
This balloon can fly to miney.
Output
This balloon cannot fly to miney.
Write a program that accepts a character as input and checks whether it is an uppercase letter or lowercase
letter or neither.
Input Format:
Input consists of a single character.
Output Format:
Output consists of a single line. Refer sample output for the format.
Sample Input 1 :
c
Sample Output 1 :
c is lowercase letter
Sample Input 2:
A
Sample Output 2:
A is uppercase letter
Sample Input 3:
5
Sample Output 2:
5 is neither an uppercase or lowercase letter
Input Format:
The first line of the input consists of a character from the set {A, B, C, D}.
The second line of the input consists of an integer which corresponds to the number of regular papers for
which the student is appearing in the examination.
The third line of the input consists of an integer which corresponds to the fee to be paid per regular paper.
The fourth line of the input consists of an integer which corresponds to the number of backlog(arrear)
papers for which the student is appearing in the examination.
The fifth line of the input consists of an integer which corresponds to the fee to be paid per arrear paper.
Output Format:
The output consists of a single line. Refer to Sample output for format details.
Page 10
[ There is a condonation fee or Rs. 5000 for lack of attendance and the hostel students need to pay the last
month mess bill of Rs.1500 along with the examination fee.]
Sample Input 1:
A
5
100
1
200
Sample Output 1:
The fee to be paid is Rs.700
Sample Input 2:
B
5
100
1
200
Sample Output 2:
The fee to be paid is Rs.5700
Sample Input 3:
C
5
100
1
200
Sample Output 3:
The fee to be paid is Rs.2200
Sample Input 4:
D
5
100
1
200
Sample Output 4:
The fee to be paid is Rs.7200
Ms. Sita, the faculty handling programming lab for you is very strict. Your seniors have told you that she will
not allow you to enter the week's lab if you have not completed atleast half the number of problems given
last week. Many of you didn't understand this statement and so they requested the good programmers
from your batch to write a program to find whether a student will be allowed into a week's lab given the
number of problems given last week and the number of problems solved by the student in that week.
Can you help in writing this program?
Input Format:
Input consists of 2 integers.
The first integer corresponds to the number of problems given and the second integer corresponds to the
number of problems solved.
Output Format:
Output consists of the string “IN” or “OUT”. Refer sample input and output for further formatting
specifications.
Output
OUT
Input Format:
Input consists of 3 lines. Each line consists of an integer.
Output Format:
Output consists of a single line. Refer sample output for the format.
Sample Input 1 :
45
45
45
Sample Output 1 :
The grade is F
Page 12
Sample Input 2:
91
95
100
Sample Output 2:
The grade is A
Input Format:
Input consists of 3 integers: X, A and B. X is the number of copies sold, A is the cost per copy and B is the
cost the agency spends per copy.
Output Format:
Refer Sample Input and Output for exact formatting specifications.
Output
The profit obtained is Rs.900
Input Format:
Input consists of an integer corresponding to the 2-digit number.
Output Format:
Output consists of an integer corresponding to the sum of its digits. Refer sample input and output for
formatting specifications.
Page 13
Output
Alice must go in path-5 to find her way to home
Output
Alice must go in path-18 to find her way to home
You are given three integers, a, b, and c. They need not be given in increasing order. If they form a
Pythagorean triple, then print "yes", otherwise, print "no". Please note that the output message is in small
letters.
Sample Input
3
5
4
Sample Output
yes
Test Case 1
Input
3
5
4
Output
yes
Test Case 2
Input
5
8
Page 14
2
Output
no
If the bill exceeds Rs.400 then a surcharge of 15% will be charged and the minimum bill should be of
Rs.100/-
Sample Test Cases
Test Case 1
Input
50
Output
100.00
Test Case 2
Input
300
Output
517.50
Test Case 3
Input
500
Output
1035.00
Test Case 4
Input
700
Output
1610.00
Test Case 2
Input
50 60 80
Output
The triangle is not valid.
Test Case 3
Input
90 35 55
Output
The triangle is valid.
Output
Profit amount : Rs. 700.50
Test Case 2
Input
600.50 520.00
Output
Loss amount : Rs. 80.50
Test Case 3
Input
970 970
Output
No profit No loss
Test Case 2
Input
50 80 80
Output
The candidate is eligible
Test Case 3
Input
50 60 40
Output
The candidate is not eligible
Sample Input:
3
10.50 7.60 1.26 3.49 -1
15.75 6.00 3.98 -1
21.00 5.25 5.75 4.76 3.98 1.50 -1
Sample Output:
$2.84 SHORT
ENOUGH MONEY
$1.94 SHORT
Critical Input:
5
0 5 -1
10 -1
10 0 -1
5 5 -1
0 0 -1
Critical Output:
$5.40 SHORT
ENOUGH MONEY
ENOUGH MONEY
$0.40 SHORT
ENOUGH MONEY
Note - 1: Do use the printf() function with a newline character (\n) at the end.
Note - 2: Let us consider the money as double data type
Note - 3: Each output should be presented after every input value
Q2. PUSH UPS WITH BLAZE:
At UAB football games, Blaze does push ups after each Blazer score. After the first Blazer touchdown (and
point after), Blaze does 7 push ups. After the second touchdown and point after, the score is now 14 and
Blaze does 14 push ups.
Write a program that calculates how many total push ups Blaze does during the whole game. Assume that
only 7 point touchdowns (including the point after) occur. Prompt for the final score and print out how
many push ups Blaze has done.
Example 1:
Input
Enter final score : 21
Output
Push ups : 42
Example 2:
Input
Enter final score : 7
Output
Page 18
Push ups : 7
Note: Do use the printf() function with a newline character (\n) at the end
Q3. MULTIPLICAVERAGE:
General Statement:
For a collection of integers, multiply them together and then divide by the number of integers in the
collection. Round the answer to 3 decimal places.
Input:
The first line in the data set is an integer that represents the number of data collections that follow. There
are an unknown number of integers in each dataset. The integer –1 is used to indicate the end of the
collection of integers.
Output:
Round the answer to 3 decimal places. Trailing zeros to the right of the decimal point are required. The
output is to be formatted exactly like that for the sample output given below.
Assumptions:
The integers are in the range 1 . . . 500. The –1 used to indicate the end of the data collection is not part of
the data for the problem.
Sample Input:
3
6 8 7 2 9 -1
1 2 3 4 5 6 7 -1
11 8 13 -1
Sample Output:
AVERAGE = 1209.600
AVERAGE = 720.000
AVERAGE = 381.333
Note - 1: Do use the printf() function with a newline character (\n) at the end.
Note - 2: Let us consider the AVERAGE as double data type
Note - 3: Each output should be presented after every input value
Page 19
Sample Input:
4 4.296 3 3.8 -2 1.8 2 2.8678 1
Sample Output:
4296.00
0.04
180.00
28.68
Note: Do use the printf() function with a newline character (\n) at the end.
Q5. Write a program to print the given pattern.
Input Format:
Input consists of a single integer.
Output Format:
Refer sample output. There is a trailing space at the end of each line.
Sample Input:
5
Sample Output:
11111
2222
333
44
5
Note: Do use the printf() function with a newline character (\n) at the end.
Q6. Write a program to print the given pattern.
Input Format:
Input consists of a single integer.
Output Format:
Refer sample output. There is a trailing space at the end of each line.
Sample Input:
5
Page 20
Sample Output:
1
22
333
4444
Note: Do use the printf() function with a newline character (\n) at the end.
Q7. Sum of Series:
Write a program in C to find the sum of the series 1 +11 + 111 + 1111 + . . . + n terms (n will be given as
input from the user and sum will be the output)
Sample Test Cases
Test Case 1
Input
4
Output
1234
Test Case 2
Input
6
Output
123456
Note - 1: Do use the printf() function with a newline character (\n) at the end.
Note - 2: Let us consider the sum as long int data type.
Q8. Perfect Number:
Write a C program to check whether a given number is a perfect number or not. (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).
Sample Test Cases
Test Case 1
Input
6
Output
YES
Test Case 2
Input
28
Output
YES
Test Case 3
45
Output
NO
Note: Do use the printf() function with a newline character (\n) at the end.
Q9. Power of 2:
Write a C program to check whether the given number(N) can be expressed as Power of Two (2) or not.
For example, 8 can be expressed as 2^3.
Sample Test Cases
Page 21
Test Case 1
Input
8
Output
8 is a number that can be expressed as power of 2.
Test Case 2
Input
46
Output
46 cannot be expressed as power of 2.
Test Case 3
Input
6572
Output
6572 cannot be expressed as power of 2.
Test Case 4
Input
1024
Output
1024 is a number that can be expressed as power of 2.
Note: Do use the printf() function with a newline character (\n) at the end.
Q10. Write a C program to print the following Pyramid pattern up to Nth row. Where N (number of rows to
be printed) is taken as input.
*****
****
***
**
*
Sample Test Case
Input
5
Output
*****
****
***
**
*
Note: Do use the printf() function with a newline character (\n) at the end.
Q11. Number of Digits:
Write a C program to count total number of digits of an Integer number (N).
Sample Test Cases
Test Case 1
Input
3456
Output
The number 3456 contains 4 digits.
Test Case 2
Page 22
Input
30000
Output
The number 30000 contains 5 digits.
Note: Do use the printf() function with a newline character (\n) at the end.
Q12. Write a C program to find sum of following series where the value of N is taken as input:
1+ 1/2 + 1/3 + 1/4 + 1/5 + ... 1/N
Sample Test Cases
Test Case 1
Input
6
Output
Sum of the series is : 2.45
Test Case 2
Input
50
Output
Sum of the series is : 4.50
Note: Do use the printf() function with a newline character (\n) at the end.
Q13. Write a C program to find LCM of two numbers using GCF.
Sample Test Cases
Test Case 1
Input
4 16
Output
LCM = 16
Test Case 2
Input
25 35
Output
LCM = 175
Test Case 3
Input
25 31
Output
LCM = 775
Note: Do use the printf() function with a newline character (\n) at the end.
Q14. SUM OF 'N' POSITIVE NUMBERS:
Write a C program to that allows the user to enter 'n' numbers and finds the number of non-negative
numbers entered and the sum of all positive numbers entered using a for loop.
Input Format:
Input consists of n+1 integers. The first integer corresponds to n. The next n integers correspond to the
numbers to be added. Consider 0 to be a positive number.
Output Format:
Refer Sample Input and Output for formatting specifications.
[All text in bold corresponds to input and the rest corresponds to output]
Sample Input and Output:
Page 23
Input
Enter the value of n : 4
Enter the number : 5
Enter the number : -2
Enter the number : -1
Enter the number : 6
Output
Number of positive numbers entered is 2 and the sum is 11
Note: Do use the printf() function with a newline character (\n) at the end.
Q15. Geometric Series:
Consider the following series:
1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243, 64, 729, 128, 2187, ...
This series is a mixture of 2 series – all the odd terms in this series form a geometric series and all the even
terms form yet another geometric series.
Write a program to find the Nth term in this series.
The value N in a positive integer that should be read from STDIN.
The Nth term that is calculated by the program should be written to STDOUT.
Other than value of Nth term, no other characters / string or message should be written to STDOUT.
For example, if N=16, the 16th term in the series is 2187. So only the value 2187 should be printed to
STDOUT.
You can assume that N will not exceed 30.
Note: Do use the printf() function with a newline character (\n) at the end.
Q16. Even Number Series:
Consider the below series:
0,0,2,1,4,2,6,3,8,4,10,5,12,6,14,7,16,8
This series is a mixture of 2 series all the odd terms in this series form even numbers in ascending order and
every even terms are derived from the previous term using the formula (x/2)
Write a program to find the nth term in this series.
The value n in a positive integer that should be read from STDIN.
The nth term that is calculated by the program should be written to STDOUT.
Other than the value of the nth term no other characters /strings or message should be written to STDOUT.
For example if n=10, the 10th term in the series is to be derived from the 9th term in the series. The
9th term is 8 so the 10th term is (8/2) = 4. Only the value 4 should be printed to STDOUT.
You can assume that the n will not exceed 20,000.
Note: Do use the printf() function with a newline character (\n) at the end.
Q17. Printing Right Triangles:
You are given a positive integer N. You have to print N rows as follows. The first row consists of one 0, the
second row 2 zeroes, and so on, until the Nth row, which consists of N zeroes.
Sample Test Cases
Test Case 1
Input
2
Output
0
00
Test Case 2
Input
Page 24
6
Output
0
00
000
0000
00000
000000
Note: Do use the printf() function with a newline character (\n) at the end.
Q18. Finding the Second Largest Element:
You are given a sequence of integers as input, terminated by a -1. (That is, the input integers may be
positive, negative or 0. A -1 in the input signals the end of the input.)
-1 is not considered as part of the input.
Find the second largest number in the input. You may not use arrays.
Sample Test Cases
Test Case 1
Input
-840 -288 -261 -337 -335 488 -1
Output
-261
Test Case 2
Input
-840 -335 -1
Output
-840
Test Case 3
Input
471 -288 -366 488 -335 -420 -840 465 -337 413 -261 458 -1
Output
471
Note: Do use the printf() function with a newline character (\n) at the end.
Q19. Write a program to divide an array of 5 elements into two arrays of even and odd elements.
Sample Test Cases
Test Case 1
Input
67
34
69
90
32
Output
Even array: 34 90 32
Odd array: 67 69
Test Case 2
Input
10
Page 25
34
52
5
11
Output
Even array: 10 34 52
Odd array: 5 11
Note: Do use the printf() function with a newline character (\n) at the end.
Q20. Repeated Element:
Write a C program to find the first repeated element in an array of size 5 by filling up required code in the
editable section.
First repeated element means the element occurs atleast twice and has smallest index.
Sample Test Cases
Test Case 1
Input
10
20
30
40
20
Output
20 repeated at index 4
Test Case 2
Input
1
2
3
4
5
Output
There is no repeated element
Note: Do use the printf() function with a newline character (\n) at the end.
SET – 3
Q1. Remove Duplicates:
Write a C Program to delete duplicate elements from an array of integers.
Sample Test Cases
Test Case 1
Input
5
50
60
30
Page 26
20
30
Output
50
60
30
20
Test Case 2
Input
6
40
20
50
30
20
10
Output
40
20
50
30
10
Note: Do use the printf() function with a newline character (\n) at the end.
Q2. Delete Element:
C Program to delete an element from a specified location of an Array starting from array[0] as the 1st
position, array[1] as second position and so on.
Sample Test Cases
Test Case 1
Input
5
10
20
30
40
50
4
Output
10
20
30
50
Test Case 2
Input
6
600
500
Page 27
400
300
300
200
4
Output
600
500
400
300
200
Note: Do use the printf() function with a newline character (\n) at the end.
Q3. Last ant on rod:
There are 'n' ants on a 'n+1' length rod. The ants are numbered from 1 to n and are initially placed at
positions starting from position 1 till position n. They are moving either in left direction (denoted by '-1') or
in the right direction (denoted by '1'). Whenever an ant crosses the boundary of the rod it falls off the rod.
You are given the initial direction of the ants. Now, whenever two ants collide their direction switches, i.e.
the ant going in left direction ('-1) changes it's direction towards right ('1') and the ant going in the right
direction ('1') changes it's direction towards left ('-1'). Find last ant to fall off the rod.
Note: In case two ants are falling simultaneously in the end print the index of the lower indexed ant.
Input Format:
First line contains the integer 'n' denoting the total number of ants s.t. 1 <= n <= 1,000.
Second line contains 'n' space separated numbers (either '1' or '-1') denoting the initial directions of the
ants.
Output Format:
Output a single integer which is the index (lower index in case two ants are falling simultaneously in the
end) of the last ant to fall off the table.
Sample Test Cases
Test Case 1
Input
2
11
Output
1
Test Case 2
Input
3
1 -1 -1
Output
2
Note: Do use the printf() function with a newline character (\n) at the end.
Q4. NUMBER COUNT:
A set of N numbers (separated by one or more spaces) is passed as input (string) to the program. The
program must identify the count of numbers where the number on the left is twice the number on the
right.
Page 28
Input Format:
The first line will contain the N numbers separated by one or more spaces.
Boundary Conditions:
3<=N<=50
The value of the numbers can be from -99999999 to 99999999
Output Format:
The count of numbers where the numbers on the LHS is twice that of the sum of numbers on the RHS.
Example Input / Output 1:
Input:
10 20 5 40 15 -2 30 -1 60
Output:
2
Explanation:
The numbers meeting the criteria are 20, -1
Example Input / Output 2:
Input:
5 90 10 2 5 -4 10 6 5 3
Output:
3
Explanation:
The numbers meeting the criteria are 2, 6, 5
Note: Do use the printf() function with a newline character (\n) at the end.
Q5. CHARACTER PATTERN:
Write a program to print the following output for the given input. You can assume the string is of odd
length
Example-1:
Input:
12345
Output:
1 5
2 4
3
24
1 5
Example-2:
Input:
PROGRAM
Output:
P M
R A
OR
G
O R
R A
P M
Page 29
Note: Do use the printf() function with a newline character (\n) at the end.
Q6. Negative Elements Count
Complete the C code to count the number of negative elements in a two-dimensional matrix.
Sample Test Cases
Test Case 1
Input
3
4
6
-7
8
9
-4
-9
10
11
-7
5
4
-3
Output
No. of Negative Elements = 5
Test Case 2
Input
2
5
10
-30
9
8
-4
10
-20
39
40
-8
Note: Do use the printf() function with a newline character (\n) at the end.
Q7. Diagonal Matrix
Complete the code which reads a square matrix a[n][n] and print only the elements that falls in the
diagonal starting from a[0][0] to a[n][n] and all other elements printed as 0 (zero).
Sample Test Cases
Test Case 1
Input
3
1
Page 30
2
3
4
5
6
7
8
9
Output
100
050
009
Note: Do use the printf() function with a newline character (\n) at the end.
Q8. Lower Triangle
Write a C program to print lower triangle of a square matrix.
For example, the output of a given matrix:
234
567
456
will be
200
560
456
Output
100
120
123
Page 31
Test Case 2
Input
4
1
1
1
1
2
2
2
2
3
3
3
3
4
4
4
4
Output
1000
2200
3330
4444
Note: Do use the printf() function with a newline character (\n) at the end.
Q9. Case Count:
Write a C Program to Count Number of Uppercase and Lowercase Letters in a given string. The string may
be a word or a sentence.
Sample Test Cases
Test Case 1
Input
Online NPTEL Course.
Output
Uppercase Letters : 7
Lowercase Letters : 10
Test Case 2
Input
National Programme on Technology Enhanced Learning is a joint initiative of the IITs and IISc.
Output
Uppercase Letters : 11
Lowercase Letters : 68
Test Case 3
Input
Problem Solving through Programming in C.
Output
Page 32
Uppercase Letters : 4
Lowercase Letters : 31
Test Case 4
Input
AICTE Approved FDP Course
Output
Uppercase Letters : 10
Lowercase Letters : 12
Note: Do use the printf() function with a newline character (\n) at the end.
Q10. Largest and Smallest Word:
Write a C program to print Largest and Smallest Word from a given sentence. If there are two or more
words of same length, then the first one is considered.
Sample Test Cases
Test Case 1
Input
Problem Solving through Programming in C.
Output
Largest word : Programming
Smallest word : C
Test Case 2
Input
NPTEL is a joint initiative of the IITs and IISc.
Output
Largest word : initiative
Smallest word : a
Test Case 3
Input
AICTE Approved FDP Course.
Output
Largest word : Approved
Smallest word : FDP
Note: Do use the printf() function with a newline character (\n) at the end.
Q11. WHERE DOES IT FIT?:
General Statement:
For an input word, determine whether it is alphabetically located before the word EXERCISE, after the word
MUSCLES, or between EXERCISE and MUSCLES.
Input:
The first line of the data set for this problem is an integer that represents the number of words in the list.
Each word is on a separate line.
Output:
The output is to be formatted exactly like that for the sample output given below.
Assumptions:
All letters are upper case.
Sample Input:
4
Page 33
REST
ACHE
STRETCH
GYM
Sample Output:
REST IS AFTER MUSCLES
ACHE IS BEFORE EXERCISE
STRETCH IS AFTER MUSCLES
GYM IS BETWEEN EXERCISE AND MUSCLES
Note: Do use the printf() function with a newline character (\n) at the end.
Q12. LETTERED NUMERATION SYSTEM:
General Statement:
The number equivalents in this numeration system are as follows:
A=1
B = 10
C = 100
D = 1000
E = 10000
F = 100000
G = 1000000
Read the lettered version of the number and convert it to its numerical equivalent.
Input:
The first line in the data set is an integer that represents the number of data collections that follow. There
are an unknown number of letters in each data set. The letter X is used to indicate the end of the collection
of letters.
Output:
Place values to the right of the first digit must all be filled. Use a zero for any missing letters. Do not use
leading zeros.
The output is to be formatted exactly like that for the sample output given below.
Assumptions:
The letters in the data will be in order from highest to lowest and all letters of the same value are grouped
together. The X used to indicate the end of a data collection is not part of the data for the problem.
Sample Input:
3
CCBBBBAX
EEECCCCX
DCCCAAAAAAX
Sample Output:
241
30400
1306
Note: Do use the printf() function with a newline character (\n) at the end.
Q13. Blank Space Count:
Complete the code to find number of blank space in a sentence. (Do not use the strlen() function)
Sample Test Cases
Page 34
Test Case 1
Input
Problem solving through Programming in C.
Output
Number of blank space = 5
Test Case 2
Input
This is Week 7 Programming Assignment Question 8.
Output
Number of blank space = 7
Note: Do use the printf() function with a newline character (\n) at the end.
Q14. String Comparison:
Write a ' C ' code to compare two strings e.g. str1 and str2 and check whether strings are equal and str1 is
greater than str2 or less. Complete the code by filling up required code in editable section without using
standard string library.
Sample Test Cases
Test Case 1
Input
abc
ABC
Output
String-1 is greater than String-2
Test Case 2
Input
ABCD
ABCD
Output
Strings are equal
Test Case 3
Input
ABCD
abcd
Output
String-1 is less than String-2
Test Case 4
Input
123
123
Output
Strings are equal
Note: Do use the printf() function with a newline character (\n) at the end.
Q15. Function to return the quotient:
Write a function called divide that takes two non-negative integers: a and b and returns the quotient of a
divided by b, if b is a factor of a, else it returns -1.
Note: In this assignment the main() function is given to you. The given code for main() cannot be changed
by you and divide() is being called from inside that. You only need to write the divide function.
Page 35
Also note that the #include line is also provided so you do not need to add it while writing the divide()
function.
Sample Test Cases
Test Case 1
Input
4
2
Output
2
Test Case 2
Input
2
4
Output
-1
Test Case 3
Input
0
6
Output
0
Test Case 4
Input
1234
1234
Output
1
6
Test Case 2
Input
2
1
Output
2
Test Case 3
Input
5
2
Output
10
Test Case 4
Input
7
0
Output
1
Test Case 5
Input
10
10
Output
1
134
Output
2
Test Case 3
Input
4
214
Output
3
Test Case 4
Input
5
1453
Output
2
Output
10
Test Case 5
Input
1
4
Output
4
1000
Output
111
SMS language or textese (also known as txt-speak, txtese, chatspeak, txt, txtspk, txtk, txto, texting language,
txt lingo, SMSish, txtslang, or txt talk) is a term for the abbreviations and slang commonly used with mobile
phone text messaging.
Some of the abbreviations used are
· s for yes
· u for you
· 2day for today
· y for why
Many Grandpa's have started sending SMSes to their grand children. But they are not familiar with the SMS
lingo.
Can you help them by writing a program that would convert a given text in proper English to SMS lingo?
Consider only the 4 words listed above.
Input Format:
Input consists of a single string. Assume that the maximum length of the string is 200 and all letters are in
lower-case.
Output Format:
Output consists of a single string.
Sample Input 1:
why is today a working day for you?
Sample Output 1:
y is 2day a working day for u?
Output
The Merit List is :
3 Vivek 900
1 Santanu 700
2 Aparna 550
Test Case 2
Input
4
1
Pradip
900
2
Asutosh
600
3
Santosh
750
4
Sandip
500
Output
The Merit List is :
1 Pradip 900
3 Santosh 750
2 Asutosh 600
4 Sandip 500
Page 43
Note: Do use the printf() function with a newline character (\n) at the end.
Q5. Distance
Write a C program to add two distance given as input in feet and inches.
Sample Test Cases
Test Case 1
Input
40
11
10
11
Output
Sum of distances = 51 feet 10 inches
Test Case 2
Input
10
5
20
5
Output
Sum of distances = 30 feet 10 inches
Test Case 3
Input
5
11
9
1
Output
Sum of distances = 15 feet 0 inches
Note: Do use the printf() function with a newline character (\n) at the end.
Q6. Employee Details
Develop a ‘C’ program to maintain employee details using structures.
Test Case 1
Input
Enter the number of employees : 2
Enter the employee number : 101
Enter the name : Arun
Enter basic pay, allowances & deductions : 5000 1000 250
Enter the employee number : 102
Enter the name : Babu
Enter basic pay, allowances & deductions : 7000 1500 750
Page 44
Output
Emp. No. Name Bpay Allow Ded Npay
101 Arun 5000 1000 250 5750
102 Babu 7000 1500 750 7750
Note: Do use the printf() function with a newline character (\n) at the end.
Q7. Each Sunday, a newspaper agency sells X copies of a certain newspaper for Rs.A per copy. The cost to
the agency of each newspaper is Rs.B.
The agency pays a fixed cost for storage, delivery and soon of Rs.100 per Sunday. The newspaper agency
wants to calculate the profit obtained on Sundays.
Can you please help them by writing a C program to compute the profit given X, A and B.
She gave them an assignment on calculating the distance between the points. In order to prevent copying,
she gave each student a different set of questions.
But she found it very difficult to correct all 100 assignments. She seeks your help. Can you please help her
out?
Given the vertices of a triangle ABC, determine the sides of the triangle AB, BC, and AC. Can you write
a C program to calculate the sides?
At the time of execution, the program should print the following messages one by one on the console as:
Enter the x-coordinate of vertex A :
Enter the y-coordinate of vertex A :
Enter the x-coordinate of vertex B :
Enter the y-coordinate of vertex B :
Enter the x-coordinate of vertex C :
Enter the y-coordinate of vertex C :
For example, if the user gives the input as:
Enter the x-coordinate of vertex A : 2
Enter the y-coordinate of vertex A : 2
Enter the x-coordinate of vertex B : 3
Enter the y-coordinate of vertex B : 3
Enter the x-coordinate of vertex C : 1
Page 45
At the time of execution, the program should print the message on the console as:
Enter a number :
For example, if the user gives the input as:
Enter a number : 10
then the program should print the result as:
The result is : 5
Q10. Emily is a very popular Maths Teacher in School. She retires from her service today. Her 7th class
students like her very much and they wanted to give her a grand farewell at school.
The school HeadMistress is a very strict person and she didn't give permission for them to conduct the
farewell at school premises. The students decided to conduct the farewell at Emily Mam's house itself.
They know the street in which Emily mam lives. The student leader asked Emily Mam to tell her house
number. Emily Mam's last class was on Equation for a straight line.
She said that a straight line can be represented by the equation y = mx + c and you know how to find the x-
intercept and y-intercept of the line and my house number is the sum of the x-intercept and y-intercept of
the line.
The students were puzzled. Can you help the students find the house number of Emily Mam?
Given the values of m and c of the line equation y = mx + c, write a C program to find the sum of x-
intercept and y-intercept.
At the time of execution, the program should print the following messages one by one on the console as:
Enter the value of m :
Enter the value of c :
For example, if the user gives the input as:
Enter the value of m : 5
Enter the value of c : 10
then the program should print the result as:
The line equation is y = 5x + 10
The x intercept : -2
The y intercept : 10
Page 46
In order to help the construction workers to build a straight fence, they planned to place a thick rope
around the ground. They wanted to buy only the exact length of the rope that is needed.
They also wanted to cover the entire ground with a thick carpet during rainy season. They wanted to buy
only the exact quantity of carpet that is needed. They requested your help.
Can you please help them by writing a C program to find the exact length of the rope and the exact quantity
of carper that is required?
At the time of execution, the program should print the following messages on the console as:
Enter length :
Enter width :
For example, if the user gives the input as:
Enter length : 15
Enter width : 36
then the program should print the result as:
Required length : 102m
Required quantity of carpet : 540sqm
Q12. During the Physical Education hour, PD sir Mr. Sundar has decided to conduct some team games. He
wants to split the students in the class into equal sized teams.
In some cases, there may be some students who are left out from teams and he wanted to use the left out
students to assist him in conducting the team games.
For instance, if there are 50 students in the class and if the class has to be divided into 7 equal sized teams,
7 students will be there in each team and 1 student will be left out.
PD sir asks your help to automate this team splitting task. Can you please help him out?
At the time of execution, the program should print the following messages one by one on the console as:
Enter the number of students in the class :
Enter the number of teams :
For example, if the user gives the input as:
Enter the number of students in the class : 30
Enter the number of teams : 7
then the program should print the result as:
The number of students in each team : 4
Page 47
How much sale must he have in the sixth month so that he gets an average sale of Rs. x?
lnput Format:
Input consists of 5 integers and 1 float.
The five integers correspond to s1, s2, s3, s4, and s5.
The float input corresponds to x.
Output Format:
Refer sample input and output for formatting specifications.
The flues are displayed correctly to 2 decimal places
At the time of execution, the program should print the following messages one by one on the console as:
First month sale :
Second month sale :
Third month sale :
Fourth month sale :
Fifth month sale :
Average sales :
For example, if the user gives the input as:
First month sale : 200
Second month sale : 250
Third month sale : 280
Fourth month sale : 240
Fifth month sale : 260
Average sales : 250
then the program should print the result as:
Sixth month sale : Rs.270.00
Q14. Raju lives in a colony. On his 9th birthday, his father gifts him a Pogo Stick, Raju is so excited to play
with the pogo stick.
The pogo stick moves one unit per jump. He wanders around his house jumping with pogo sticks.
He likes to show the pogo stick to his friends and decides to go using the pogo sticks.
Write a program to find the number of jumps needed to reach his friend's house. Assume that Raju's house
is in the location (3, 4).
Q15. The student strength at your college has crossed the 1000 mark now. The small stationary shop
opposite to your college is not able to cater to the growing stationary needs of your college student
Page 48
community.
The students have to always wait in a long queue to purchase stationery items. The shop-keeper is very
weak in Mathematics and he always takes a long time to do even simple addition.
The shopkeeper's poor mathematical skills annoyed your college students as they had to wait for a long
time in the queue.
The current first-year batch of your college have started learning C programming and they decided to help
the shop-keeper by writing a program to add two numbers. So, write a C program for this.
At the time of execution, the program should print the following messages one by one on the console as:
Enter the price of first item :
Enter the price of second item :
For example, if the user gives the input as:
Enter the price of first item : 45.55
Enter the price of second item : 67.75
then the program should print the result as:
The total amount to be paid : Rs.113.300
Q18. Write a program to print the total number of matchstick required to form pyramid of matchsticks of X
floors.
Octagonal numbers can be formed by placing triangular numbers on the four sides of a square. Octagonal
number is calculated by using the formula (3n2 – 2n).
Page 50
Examples:
Input:
a=2b=5
Output:
Number of digits = 2
Explanation:
2^5 = 32
Hence, Number of digits = 2
Input:
a = 2 b = 100
Output:
Number of digits = 31
Explanation:
2^100 = 1.2676506e+30
Hence, Number of digits = 31
Sample Input and Output-1:
Enter two numbers : 2 5
Number of digits = 2
Q2. Write a program given N containers consisting of N copies of number A and N copies of number B.
We need to arrange the numbers in the N containers in such a way that the probability of choosing a
container randomly and drawing one copy of number A is maximum.
Examples:
Input :
N=1
Output :
0.5000
Page 51
Input :
N=2
Output :
0.667
Sample Input and Output-1:
Enter a number : 1
0.5000
Q3. Write a program for the given two numbers, find the floor of their average without using division.
Examples:
Input :
x = 10, y = 12
Output :
11
Input :
x = 10, y = 7
Output :
8
We take floor of sum.
Sample Input and Output-1:
Enter two numbers : 20 10
15
Q4. Write a program given a number, the task is to Toggle all even bit of a number.
Examples:
Input :
10
Output :
0
Explanation :
binary representation 1 0 1 0
after toggle 0 0 0 0
Input :
20
Output :
30
Explanation :
binary representation 1 0 1 0 0
after toggle 1 1 1 1 0
Sample Input and Output-1:
Enter a number : 10
0
Page 52
Q5. Write a program given a number n, the task is to toggle only first and last bits of a number.
Example :
Input :
10
Output :
3
Explanation :
binary representation of 10 is 1 0 1 0
after toggling 0 0 1 1
Sample Input and Output-1:
Enter a number : 15
6
Q6. Write a program given a non-negative integer n, the problem is to reverse the bits of n and print the
number obtained after reversing the bits.
Note that the actual binary representation of the number is being considered for reversing the bits, no
leading 0’s are being considered.
Examples :
Input :
11
Output :
13
Explanation :
(11)10 = (1011)2.
After reversing the bits we get: (1101)2 = (13)10.
Input :
10
Output :
5
Explanation :
(10)10 = (1010)2.
After reversing the bits we get: (0101)2 = (101)2 = (5)10.
Sample Input and Output-1:
Enter a number : 10
5
Q7. Write a program given two integer a and b, find whether their product (a x b) exceed the signed 64 bit
integer or not. If it exceed print Yes else print No.
Examples:
Input :
a = 100, b = 200
Output :
Page 53
No
Input :
a = 10000000000, b = -10000000000
Output :
Yes
Sample Input and Output-1:
Enter two numbers : 100 200
No
Q8. Write a program given the dimension of the matrix R(rows) * C(column), the task is to find which type
of matrix is representing by the given dimension.
Examples:
Input :
R=1C=0
Output :
Row Matrix
Input :
R=4C=5
Output :
Horizontal Matrix
Sample Input and Ouptut-1:
Enter row and column size : 1 0
Row Matrix
Note: Different types of matrices are Column Matrix, Row Matrix, Horizontal Matrix, Vertical
Matrix and Square Matrix.
Q9. Write a program given a positive number N, we need to find number(s) such that sum of digits of those
numbers to themselves is equal to N.
Examples:
Input :
N = 21
Output :
X = 15
Explanation :
X + its digit sum = 15 + 1 + 5 = 21
Input :
N = 100000001
Output :
X = 100000000
X = 99999937
Sample Input and Output-1:
Page 54
Two sequences that differ in the order of their terms define different compositions of their sum.
Examples:
Input :
4
Output :
8
Explanation :
All 8 position composition are 4, 1+3, 3+1, 2+2, 1+1+2, 1+2+1, 2+1+1 and 1+1+1+1
Input :
8
Output :
128
Sample Input and Output-1:
Enter a number : 4
8
Sample Input and Output-2:
Enter a number : 0
Invalid input
Q11. Write a program to calculate factorial without using any loop or recursion.
Yes, this is possible through a well-known approximation algorithm known as Stirling approximation.
Examples:
Input :
n=6
Output :
723
Input :
n=2
Output :
1
Sample input and output-1:
Enter a number : 3
5
Sample input and output-1:
Enter a number : 0
Page 55
Invalid input
Q12. Write a c program compare 2 numbers and find if they are equal without using the ==, > and <
operator.
Invalid input
Q16. A new grossory shop has to be opened. The owner asks the accountant to take a print of price list of
the items to be sold in the store.
The bill should have the details of the item and its cost. The items that the owner decides to sell initially are
A4 sheets, pen, pencil and eraser.
An accountant is an experienced person and he very well knows that number of items will be added to the
list as the business picks up.
The accountant is well versed in programming and he decides to write a C program to generate the price
list.
Input format:
Input consists of 3 floating point values.
Output format:
The output consists of three floating point values with specified number of decimal values.
The first and third line of the output contains one decimal value. The second line of the output must
contain two decimal value.
At the time of execution, the program should print the message on the console as:
Enter 3 floating point values :
For example, if the user gives the input as:
Enter 3 floating point values : 5.3265 4.2564 8.655156
Then the program should print the result as:
The result is:
5.3
Page 57
4.26
8.7
Q18. In Japan, there was a very huge Tsunami. Millions and millions worth buildings and properties were
destroyed. Many people lost their lives. Most of them were injured and few were safe. A news reporter
arrives to the spot to take the current survey regarding the situation of the people alive, dead and injured.
He wanted to publish it in the newspaper and ask the other countries to help the affected people.
Can you please help him in this noble cause by writing a C program to generate the newspaper report?
INPUT FORMAT:
Input consists of three integers corresponding to the number of people dead, injured and those who are
still alive and safe.
OUTPUT FORMAT:
Refer sample input and output for formatting specifications.
At the time of execution, the program should print the message on the console as:
Enter 3 floating point values :
For example, if the user gives the input as:
Enter 3 floating point values : 3.456 23.67 2.4
then the program should print the result as:
The result is : 3.456000 23.670000 2.400000
Q20. Write a program to receive a float variable and print the same with 3 decimal point precision.
At the time of execution, the program should print the message on the console as:
Enter a floating point value :
For example, if the user gives the input as:
Enter a floating point value : 3.478923
Then the program should print the result as:
The given float value is : 3.479
SET – 6
Page 58
Q1. Write a C program to read a character using scanf() and print the entered character using putchar().
At the time of execution, the program should print the message on the console as:
Enter a character :
For example, if the user gives the input as:
Enter a character : A
then the program should print the result as:
A
Q2. Write a program to ask the user to enter an integer and to print the value.
At the time of execution, the program should print the message on the console as:
Enter an integer :
For example, if the user gives the input as:
Enter an integer : 23
then the program should print the result as:
The given integer : 23
Note: Do use the printf() function with a newline character (\n) at the end.
Q3. Write a program to read a number n in a base 10, then find the number of digits in its
base b representation.
Examples:
Input : Number = 48
Base = 4
Output: 3
Explanation : (48)10 = (300)4
Examples:
Input : (x1, y1) = (10, 0)
(x2, y2) = (20, 0)
Output : Yes
The line passing through these points
clearly passes through the origin as
the line is x axis.
Input : n = 5
Output : 2
Explanation : 2 power 5 = 32, which has only 2 digits.
Input : n = 10
Output : 4
Explanation : 2 power 10 = 1024, which has only 4 digits.
Input : 2
Output : 1.46286
Input : side = 4
Output : 490.44
Input : side = 9
Output : 5586.41
Q16. Write a program given a positive number n (n > 1), round-off this number to a given no. of significant
digits, d.
Examples:
Input : n = 139.59
d=4
Output : The number after rounding-off is 139.6.
The number 139.59 has 5 significant figures and for rounding-off
the number to 4 significant figures, 139.59 is converted to 139.6.
Input : n = 1240
d=2
Output : The number after rounding-off is 1200.
At the time of execution, the program should print the following messages one by one on the console as:
Enter first time in format hh:mm:ss :
Enter second time in format hh:mm:ss :
For example, if the user gives the input as:
Enter first time in format hh:mm:ss : 23:10:35
Enter second time in format hh:mm:ss : 03:6:45
then the program should print the result as:
The elapsed time = 20:3:50
Hint: If the user given the input as Hours, Minutes and Seconds beyond the time then print "You entered
wrong time".
Q18. Write a program to accept the DOB of a person and calculate the age in the number of days.
At the time of execution, the program should print the following messages one by one on the console as:
Enter the current date :
Enter the date of birth :
For example, if the user gives the input as:
Enter the current date : 01 05 2018
Enter the date of birth : 18 07 1982
then the program should print the result as:
Current age : 35 years 9 months 13 days
For example, if the inputs are given as:
Page 63
If the average mark is greater than or equal to 90, then print the grade as ‘A'.
If the average mark is 80 and between 80 and 90, then print the grade as 'B’.
If the average mark is 70 and between 70 and 80, then print the grade as ‘C’.
If the average mark is 60 and between 60 and 70, then print the grade as ‘D’.
If the average mark is 50 ond between 50 and 60, then print the grade as 'E'.
If the average mark is less than 50, then print the grade as 'F'.
Sample Input 1:
Enter three subject marks : 34 45 67
Sample Output 1:
The grade is F
Sample Input 2:
Enter three subject marks : 91 95 100
Sample Output 2:
The grade is A
Q20. Write a program to determine whether the input character is a vowel or consonant.
It ran fast, and she followed it, down a rabbit hole. She fell into the hole and found a magical wonderland
with dark trees, beautiful flowers.
She found many ways numbered from 1,2,3,........18. She was confused which is the right way that will lead
her to her home.
She found a cute bird, standing in one of the tree. Alice asked the bird the way to go back to her home.
The bird said a two digit number (say 23) and asked her to find the sum of its digits (2 + 3 = 5) and that
numbered way will lead her to her home. Alice was already confused, so pls help Alice in finding the route
to her home.
Input Format:
Input consists of an integer corresponding to the 2-digit number.
Output Format:
Output consists of an integer corresponding to the sum of its digits. Refer sample input and output for
formatting specifications.
At the time of execution, the program should print the message on the console as:
The bird said :
For example, if the user gives the input as:
The bird said : 23
then the program should print the result as:
Alice must go in path-5 to find her way to home
Note: If the input is 121 then the output should be "Please enter a two digit number".
Q2. Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on
one straight line.
Input Format:
First line of input consists of two integer values that indicates x1, y1 respectively.
Second line of input consists of two integer values that indicates x2, y2 respectively.
Third line of input consists of two integer values that indicates x3, y3 respectively.
Output Format:
Output consists whether all three points fall on the same line or not.
Sample Input - 1:
Page 65
Sample Input - 2:
Enter x1 and y1 values : 2 4
Enter x2 and y2 values : 4 2
Enter x3 and y3 values : 3 7
Sample Output - 2:
Three points don't fall on the same line
Q3. A library charges a fine for every book returned after the due date.
For the first 5 days after the due date, the fine is 50 paise, for 6-10 days after the due date fine is 1 rupee
and for above 10 days after the due date the fine is 5 rupees.
If the book is returned after 30 days beyond the due date the membership will be cancelled.
Write a program to accept the number of days the member is late to return the book and display
the fine and/or the appropriate member cancellation message.
Note: If the book is returned on or before the due date print "No fine"
Sample Input and Output - 1:
Enter how many days late you are : 13
Your fine : Rs.5.00
Sample Input and Output - 2:
Enter how many days late you are : 60
Your membership has been cancelled
Sample Input and Output - 3:
Enter how many days late you are : 0
No fine
Sample Input and Output - 4:
Enter how many days late you are : -2
No fine
Q4. Write a program to check whether a given year is a leap year or not by using nested if.
Q5. Write a program to determine the grade of a student in a particular subject. Refer the data given below
for grade details.
Write a C program to print the denomination of the notes for given user input.
Sample Input - 1:
Enter a number : 21
Sample Output - 1:
21 is divisible by both 7 and 3
Sample Input - 2:
Enter a number : 18
Sample Output - 2:
18 is not divisible by both 7 and 3
Q9. Write a program that accepts as input and checks wheather the given input is an uppercase letter
or lowercase letter or neither.
Sample Input 1:
Enter an input: c
Sample Output 1:
c is a lowercase letter
Sample Input 2:
Enter an input : A
Sample Output2:
A is an uppercase letter
Sample Input 3:
Enter an input : 5
SampleOutput 3:
5 is neither an uppercase or a lowercase letter
Q10. Normally in all engineering colleges, there will be a long vacation after every even semester and a
short vacation after every odd semester.
Write a C program to determine whether he will have a long vacation or short vacation at the end of this
semester.
Page 68
Input format:
Input consists of 1 integer which corresponds to the current semester of the students
i.e., Even semester - "Long vacation", Odd semester - "Short vacation".
Output format:
Output consists of the string "Long vacation " or "Short vacation".
Sample Input and Output - 1:
Enter the current semester : 6
Long vacation
Sample Input and Output - 2:
Enter the current semester : 1
Short vacation
Q11. Write program to relate integers entered by the user as equal to, less than or greater than.
Sample input - 2:
Enter three integer values : 12 56 14
Sample output - 2:
56
Q14. Write a program to print Hi if the given number divisible by 3, print Hello if the number divisible
by 5 or print Hi Hello if number divisible by both 3 & 5.
Q19. Given a number n, write a program to print square and non-square numbers which are smaller than or
equal to n.
Examples:
Input : n = 5
Output :
Square numbers : 2
Non-square numbers : 3
Explanation :
Square numbers are 1 and 4.
Non-square numbers are 2, 3 and 5.
Input : n = 10
Output :
Square numbers : 3
Non-square numbers : 7
Explanation :
Square numbers are 1, 4 and 9.
Non-square numbers are 2, 3, 5, 6, 7, 8 and 10.
Sample Input and Output:
Enter a number : 10
Square numbers : 3
Non-square numbers : 7
Note : If input is not valid please print "Invalid input".
Examples:
--r=5--
---------- ^
| | |
| | |
| | h = 10
| | |
---------- ^
rate_of_flow = 10
No
Set-7
Q1. Alice was bored that day, so she was sitting on the riverbank. Suddenly she notices a talking, White
Rabbit with a pocket watch.
It ran fast, and she followed it, down a rabbit hole. She fell into the hole and found a magical wonderland
with dark trees, beautiful flowers.
She found many ways numbered from 1,2,3,........18. She was confused which is the right way that will lead
her to her home.
She found a cute bird, standing in one of the tree. Alice asked the bird the way to go back to her home.
The bird said a two digit number (say 23) and asked her to find the sum of its digits (2 + 3 = 5) and that
numbered way will lead her to her home. Alice was already confused, so pls help Alice in finding the route
to her home.
Input Format:
Input consists of an integer corresponding to the 2-digit number.
Output Format:
Output consists of an integer corresponding to the sum of its digits. Refer sample input and output for
formatting specifications.
At the time of execution, the program should print the message on the console as:
The bird said :
Q2. Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on
one straight line.
Input Format:
First line of input consists of two integer values that indicates x1, y1 respectively.
Second line of input consists of two integer values that indicates x2, y2 respectively.
Third line of input consists of two integer values that indicates x3, y3 respectively.
Page 74
Output Format:
Output consists whether all three points fall on the same line or not.
Sample Input - 1:
Enter x1 and y1 values : 3 1
Enter x2 and y2 values : 2 1
Enter x3 and y3 values : 1 1
Sample Output - 1:
Three points fall on the same line
Sample Input - 2:
Enter x1 and y1 values : 2 4
Enter x2 and y2 values : 4 2
Enter x3 and y3 values : 3 7
Sample Output - 2:
Three points don't fall on the same line
Q3. A library charges a fine for every book returned after the due date.
For the first 5 days after the due date, the fine is 50 paise, for 6-10 days after the due date fine is 1 rupee
and for above 10 days after the due date the fine is 5 rupees.
If the book is returned after 30 days beyond the due date the membership will be cancelled.
Write a program to accept the number of days the member is late to return the book and display
the fine and/or the appropriate member cancellation message.
Note: If the book is returned on or before the due date print "No fine"
Q4. Write a program to check whether a given year is a leap year or not by using nested if.
Q5. Write a program to determine the grade of a student in a particular subject. Refer the data given below
for grade details.
The interval [a, b) Includes all numbers greater than Or equal to a and less than b.
Q6. A cashier has currency notes of denomination 1, 2, 5, 10, 20, 50, 100, 500, 2000.
Write a C program to print the denomination of the notes for given user input.
Q7. Write a program to find whether a given integer is odd or even number.
46 is an even number
Q8. Write a program to find whether given number is divisible by both 7 and 3.
Sample Input - 1:
Enter a number : 21
Sample Output - 1:
21 is divisible by both 7 and 3
Sample Input - 2:
Enter a number : 18
Sample Output - 2:
18 is not divisible by both 7 and 3
Q9. Write a program that accepts as input and checks wheather the given input is an uppercase letter
or lowercase letter or neither.
Sample Input 1:
Enter an input: c
Sample Output 1:
c is a lowercase letter
Sample Input 2:
Enter an input : A
Sample Output2:
A is an uppercase letter
Sample Input 3:
Enter an input : 5
SampleOutput 3:
5 is neither an uppercase or a lowercase letter
Page 78
Normally in all engineering colleges, there will be a long vacation after every even semester and a short
vacation after every odd semester.
Q10. Write a C program to determine whether he will have a long vacation or short vacation at the end of
this semester.
Input format:
Input consists of 1 integer which corresponds to the current semester of the students
i.e., Even semester - "Long vacation", Odd semester - "Short vacation".
Output format:
Output consists of the string "Long vacation " or "Short vacation".
Sample Input and Output - 1:
Enter the current semester : 6
Long vacation
Sample Input and Output - 2:
Enter the current semester : 1
Short vacation
Q11. Write program to relate integers entered by the user as equal to, less than or greater than.
Q12. There are 3 labs in the CSE department (L1, L2 and L3) with a seating capacity of x, y and z. Find the
lab which has the minimal seating capacity.
Q13. Write a program to print the greatest of 3 numbers received as user input.
Sample input - 2:
Enter three integer values : 12 56 14
Sample output - 2:
56
Q14. Write a program to print Hi if the given number divisible by 3, print Hello if the number divisible
by 5 or print Hi Hello if number divisible by both 3 & 5.
Given the length of the sides of an equilateral triangle. We need to write a program to find the area of
Circumcircle of the given equilateral triangle.
Page 80
Q17. Write a program to remove all the palindromic words from the given sentence.
Example:
Q18. Write a program to check whether the given three sides of a triangle are valid or not.
Q19. Given a number n, write a program to print square and non-square numbers which are smaller than or
equal to n.
Examples:
Input : n = 5
Output :
Square numbers : 2
Non-square numbers : 3
Explanation :
Square numbers are 1 and 4.
Non-square numbers are 2, 3 and 5.
Input : n = 10
Output :
Square numbers : 3
Non-square numbers : 7
Explanation :
Square numbers are 1, 4 and 9.
Non-square numbers are 2, 3, 5, 6, 7, 8 and 10.
Sample Input and Output:
Enter a number : 10
Square numbers : 3
Non-square numbers : 7
Page 82
Q20. Determine whether a rectangle can be formed by giving the four sides. Such that length of its sides are
a, b, c and d (in any order).
Q23. Write a program given a robot which can only move in four directions, UP(U), DOWN(D), LEFT(L),
RIGHT(R). Given a string consisting of instructions to move. Output the co-ordinates of robot after the
executing the instructions. Initial position of robot is at origin(0, 0).
Examples:
Input : move = "UDDLRL"
Output : (-1, -1)
Move U : (0, 0)--(0, 1)
Move D : (0, 1)--(0, 0)
Move D : (0, 0)--(0, -1)
Move L : (0, -1)--(-1, -1)
Move R : (-1, -1)--(0, -1)
Move L : (0, -1)--(-1, -1)
Page 83
Q24. Write a program given n number of spots, and two players. Players need to connect any two spots
without intersecting any of the drawn line, the player who cannot give a move, loses. Determine who will
win player 1 or player 2.
Q25. Write a program pronic number is such a number which can be represented as a product of two
consecutive positive integers.
By multiplying these two consecutive positive integers, there can be formed a rectangle which is
represented by the product or pronic number.
So it is also known as Rectangular Number. The first few Pronic numbers are:
0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462 . . . . . .
Pronic number is a number which is the product of two consecutive integers, that is, a number n is a
product of x and (x+1).
The task is to check if a given number is pronic or not. Mathematical Representation:
If x is a pronic number, then x=n(n+1) ∀ n ∈ N0
Where, N0={0, 1, 2, 3, 4, ....}, (A set of Naturral Numbers)
Examples:
Input : 56
Page 84
Output : YES
Explanation: 56 = 7 * 8 i.e 56 is a product
of two consecutive integers 7 and 8.
Input : 65
Output : NO
Explanation: 65 cannot be represented as a
product of any two consecutive integers.
Q26. Write a program given two numbers w and m, we need to determine whether it is possible to
represent m in terms of powers of w. The powers of number w can be added or subtracted to obtain m and
each powers of w can be used only once .
Examples:
Input : 3 7
Output : Yes
As 7 = 9 - 3 + 1 (3^2 - 3^1 + 3^0 )
so it is possible .
Input : 100 50
Output : No
As 50 is less than 100 so we can never
represent it in the powers of 100 .
Set-8
Page 85
Example:
12(1100)->2
7(111) ->0
Q2. Patrick and Johnny started to play a new game which is played with cards. Johnny decided to play the
card game – I.
In this game, he has to pick one card. The number present in the card will determine whether he will be a
winner or not.
In the game conducted during the past 3 years, the winner card numbers
were 7126, 82417914, 7687 and 6657.
Johnny is an expert in data mining and he could easily infer a pattern in the winner card numbers.
In the entire card numbers listed here, the sum of the odd numbers is equal to the sum of
the even numbers.
Q3. A maths teacher asks her students to give 3 examples for positive odd numbers.
When the student specifies a positive even number, his/her score is decremented by 0.5.
When the student specifies a negative number, he/she will not be given any more chances to correct his or
her mistake and his/her score will be decremented by 1.
So a student's turn comes to an end when he/she has correctly specified 3 positive odd numbers or when
the student has specified a negative number.
Few students didn't know the difference between odd numbers and even numbers and they made many
mistakes and so it was difficult for the teacher to maintain the scores. The teacher asks for your help.
Can you please help her by writing a program to calculate the score?
Q4. Droa normally trains his disciples using a board which consists of concetric circles. When the students
correctly hits the center of the concentric circles, his score is 100.
The score gets reduced depending on where the students hits on the board. When the student hits outside
the board, his score is 0.
Drona will not allow a student to have his food unless his scores 100. Arjuna will always hit the target in his
first attempt and he will leave early.
Can you write a program to determine the number of turns a disciple takes to reach the target score of ‘n’ ?
Q5. Disneyland offers a credit card to all the players playing this card game. This credit card is credited with
points based on this card game - III.
Patrick started to play a card game - III. In this game, he has to pick the cards which are shuffled on the
table until he picks the card with the number -999.
Once he picks the card with number -999, Patrick must handover all the cards picked to Disneyland card
game manager. The sum of all numbers in the card is credited as points to Patrick.
The players can pick any number of cards until the card with number -999 is encountered.
So it is difficult for the Disneyland managers to sum up all card numbers. They approach you and ask for
your help.
Can you please help them with the program to sum all numbers in the card (exclude -999 when calculating
the sum) using for loop?
Sample Input and Output:
Enter a card : 1
Enter a card : 5
Enter a card : 6
Enter a card : -999
The credit points : 12
Q6. A 2-digit number is said to be a special number if the sum of its digits and the products of its digits is
equal to the number itself.
For example, 19 is a special number. The digits in 19 are 1 and 9. The sum of the digits is 10 and the product
of the digits is 9. So, 10 + 9 = 19.
Write a C program to find all special numbers between given two limits m and n (both inclusive).
Enter limits : 12 49
19 29 39 49
Sample Input and Output-2:
Enter limits : 88 110
Invalid number!
Q7. A number is said to be a trendy number if and only if it has 3 digits and the middle digit is divisible by 3.
Q9. Write a C program that allows the user to keep entering numbers as long as the input is valid and also
displays a count of the valid numbers entered using a while loop.
Q11. Write a program to read a 5 digit number and print the number in reverse order.
At the time of execution, the program should print the message on the console as:
Enter a 5 digit number :
Hint: If the user given the input as less than or greater than 5 digits then print "Please enter 5 digit
number".
Q12. Write a C program to print all numbers between a and b (a and b inclusive) using while loop.
Input Format:
Input consists of 2 integers.
The first integer corresponds to a and the second integer corresponds to b. Assume a<=b.
Sample Input and Output:
Enter a and b : 10 16
10
11
12
13
14
15
16
Q13. Write a program given two positive integer n and k. You have to calculate the maximum possible XOR
value of at most k-elements from 1 to n.
Page 90
Note:k > 1
Examples:
Input : n = 7, k = 3
Output : 7
Explanation : You can select 1, 2, 4 for maximum XOR-value
Input : n = 7, k = 2
Output : 7
Explanation : You can select 3 and 4 for maximum value.
Q14. Write a C program to print all numbers between a and b (a and b inclusive) using for loop.
Input Format:
Input consists of 2 integers.
The first integer corresponds to a and the second integer corresponds to b. Assume a<=b.
Sample Input and Output:
Enter a and b : 1 4
1
2
3
4
Q15. Write a C program to print all numbers between a and b (a and b inclusive) using while loops.
Input Format:
Input consists of 2 integers.
The first integer corresponds to a and the second integer corresponds to b.
Page 91
Q16. Write a C program to find the sum of n numbers using a while loop.
Input Format:
Input consists of n+1 integers.
The first integer corresponds to n. The next n integers correspond to the numbers to be added.
Sample Input and Output:
Enter how many values do you want to read : 4
Enter 4 values : 1 5 3 -6
Sum of given values : 3
Q17. Write a C program to print the multiplication table of an integer n up to m rows using a for loop.
Input Format:
Input consists of 2 integers. The first integer corresponds to n. The second integer correspond to m.
Sample Input and Output:
Enter an integer value : 5
Enter how many rows do you want : 6
The multiplication table of 5
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
Q18. Write a C program that allows the user to enter ‘n’ numbers and finds the number of positive numbers
entered and the sum of all positive numbers entered using while loop.
Page 92
Input Format:
Input consists of n+1 integers.
The first integer corresponds to n. The next n integers correspond to the numbers to be added.
Consider 0 to be a positive number.
Sample Input and Output:
Enter how many values do you want to read : 4
Enter 4 values : 5 -2 -4 7
The number of positive numbers : 2
The sum of positive numbers : 12
Q19. Write a C program to that allows the user to enter ‘n’ numbers and finds the number of positive
numbers entered and the number of negative numbers entered using while loop.
Input Format:
Input consists of n+1 integers.
The first integer corresponds to n. The next n integers correspond to the numbers to be added.
Consider 0 to be a positive number.
Sample Input and Output:
Enter how many values do you want to read : 4
Enter 4 values : 9 -8 3 -4
The number of positive numbers : 2
The number of negative numbers : 2
Q20. Rita is planning to handle nested loops topic to students in an efficient way, since once the students
have clear idea of nested loops, they can play with any looping constructs.
She remembered a pattern game which she recently viewed in Disneyland with her daughter.
So she took all the students to Disneyland pattern game. Patrick played a first star pattern game which
prints the square of stars.
So write a program to help Patrick to print the square of stars using for loop.
Sample Input and Output:
Enter number of rows : 4
****
****
Page 93
****
****
Set-9
Given the value of length, print the X pattern in a box using # and " " (space).
Sample Input and Output:
Enter an integer : 10
##########
## ##
## ##
# # # #
# ## #
# ## #
# # # #
## ##
## ##
##########
Q2. Write a program Given two numbers say a and b, mark the multiples of 2 and 5 between a and b using
less than O(|b – a|) space and output each of the multiples.
Note : We have to mark the multiples i.e save (key, value) pairs in memory such that each key either have
value as 1 or 0 representing as multiple of 2 or 5 or not respectively.
Q3. Write a program Given a number n, find the n-th number which is both a square and a cube. First few
such numbers are 1, 64, 729, …
Example with explanation :
Input : 3
Output :729
729 is square of 27 and cube of 3.
Q4. Write a program to find whether the given integer is a circular prime number or not.
A circular prime is a prime number with the property that the number generated at each intermediate step
when cyclically permuting its (base 10) digits will be prime.
Sample Input and Output:
Q5. Given a number n, we need to find the product of all of its unique prime factors.
Prime factors: It is basically a factor of the number that is a prime number itself.
Examples :
Input: num = 10
Output: Product is 10
Explanation:
Here, the input number is 10 having only 2 prime factors and they are 5 and 2.
And hence their product is 10.
Page 95
Input : num = 25
Output: Product is 5
Explanation:
Here, for the input to be 25 we have only one unique prime factor i.e 5.
And hence the required product is 5.
Q6. Write a program given two number n and k. You need to find the n-th number that contains the digit k
or divisible by k (2 <= k <=9 ).
Examples:
Input : n = 15, k = 3
Output : 33
Exploitation : ( 3, 6, 9, 12, 13, 15, 18, 21, 23, 24,
27, 30, 31, 33 ). These are those number who contain
the digit k = 3 or divisible by k and in this nth number
is 33. so output is 33.
Input : n = 10, k = 2
Output : 20
Explanation : ( 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 )
These are those number who contain the digit k = 2 or
divisible by k and in this nth number is 20. so output
is 20.
Page 96
Q7. Write a program given a positive integer n. The problem is to print numbers in the range 1 to n having
first and last bits as the only set bits.
Examples:
Input : n = 10
Output : 1 3 5 9
(1)10 = (1)2.
(3)10 = (11)2.
(5)10 = (101)2.
(9)10 = (1001)2
Examples:
Input : Lower = 50, Upper = 100,
Count of random Number = 5
Output : 50 100 76 94 68
Explanation: lower is the lower limit of the
range and upper is the upper limit of the range.
Output contains 5 random numbers in given range.
Enter a number : 5
The random numbers are : 50 100 76 94 68
Q9. Program to find the sum of a Series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + … + (n*n). find out the sum of
the series till nth term.
Examples :
Input : n = 3
Output : 14
Explanation : 1 + 1/2^2 + 1/3^3
Input : n = 5
Output : 55
Explanation : (1*1) + (2*2) + (3*3) + (4*4) + (5*5)
Q10. Write a program for series: 1 – x^2/2! + x^4/4! -…. upto nth term. This is a mathematical series
program where a user must enter the number of terms up to which the sum of the sumseries is to be
found. Following this, we also need the value of x, which forms the base of the series.
Q11. Write a program which prints number of occurrences of each characters and also it should not print
repeatedly occurrences of duplicate characters as given in the example:
Page 98
Q12. Write a program given a range from low to high and given a number k.You have to find out the
number of count which a number has same digit as k
Examples:
Q13. Write a program given a number n to find first and last digit of a number.
Page 99
Q14. Write a program given the sequence of odd numbers. Find the sum of first n odd numbers.
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, ….
Examples:
Input : n = 2
Output : 4
Sum of first two odd numbers is 1 + 3 = 4.
Input : 5
Output : 25
Sum of first 5 odd numbers is 1 + 3 + 5 +
7 + 9 = 25
Q16. Write a program given two numbers N and K, our task is to subtract a number K from N until
number(N) is greater than zero, once the N becomes negative or zero then we start adding K until that
number becomes the original number(N).
Note : Not allowed to use any loop.
Examples :
Input : N = 15 K = 5
Output : 15 10 5 0 1 5 10 15
Input : N = 20 K = 6
Output : 20 14 8 2 -4 2 8 14 20
Q17. Write a program given a number n, find the number of ways to represent this number as a sum of 2 or
more consecutive natural numbers.
Examples:
Input : n = 15
Page 101
Output : 3
15 can be represented as:
1+2+3+4+5
4+5+6
7+8
Input :10
Output :1
10 can only be represented as:
1+2+3+4
Q18. Write a program to add two numbers.While adding two binary numbers by hand we keep the carry
bits in mind and add it at the same time. But to do same thing in program we need a lot of checks.
Recursive solution can be imagined as addition of carry and a^b (two inputs) until carry becomes 0.
Q19. Write a program given two integer numbers n and d. The task is to find the number between 0 to n
which contains the specific digit d.
Examples:
Input : n = 20
d=5
Output : 5 15
Page 102
Input : n = 50
d=2
Output : 2 12 20 21 22 23 24 25 26 27 28 29 32 42
Q20. Write a program given a number s (1 <= s <= 1000000000). If s is sum of the cubes of the first n natural
numbers then print n, otherwise print -1.
First few Squared triangular numbers are 1, 9, 36, 100, 225, 441, 784, 1296, 2025, 3025, …
Examples :
Input : 9
Output : 2
Explanation : The given number is
sum of cubes of first 2 natural
numbers. 1*1*1 + 2*2*2 = 9
Input : 13
Output : -1
Set-10
Q1. Write a program where a square pyramidal number represents sum of squares of first natural numbers.
First few Square pyramidal numbers are 1, 5, 14, 30, 55, 91, 140, 204, 285, 385, 506, …
Page 103
Geometrically these numbers represents number of spheres to be stacked to form a pyramid with square
base. Please see this Wiki image for more clarity.
Given a number s (1 <= s <= 1000000000). If s is sum of the squares of the first n natural numbers then print
n, otherwise print -1.
Examples :
Input : 14
Output : 3
Explanation : 1*1 + 2*2 + 3*3 = 14
Input : 26
Output : -1
Q2. Write a program given number perfect power that can be expressed as power of another positive
integer.
Given a number n, find count of numbers from 1 to n that are of type xy where x >= 1 and y > 1
Examples:
Input : n = 10
Output : 4
1 4 8 and 9 are the numbers that are
of form x ^ y where x > 0 and y > 1
Input : n = 50
Output : 10
Q3. Given a number N, we need to write a program to find the largest number not greater than N which has
all digits even.
Page 104
Examples:
Input: N = 23
Output: 22
Explanation: 22 is the largest number not
greater then N which has all digits even.
Input: N = 236
Output: 228
Explanation: 228 is the largest number not
greater than N which has all digits even.
4. Write a program given two numbers N and M. Find the number of ways in which factorial N can be
expressed as a sum of two or more consecutive numbers. Print the result modulo M.
Examples:
Input : N = 3, M = 7
Output : 1
Explanation: 3! can be expressed
in one way, i.e. 1 + 2 + 3 = 6.
Hence 1 % 7 = 1
Input : N = 4, M = 7
Output : 1
Explanation: 4! can be expressed
in one way, i.e. 7 + 8 + 9 = 24
Hence 1 % 7 = 1
Page 105
Q5. Write a program given three integers, A, X and n, the task is to print terms of below binomial
expression series.
(A+X)n = nC0AnX0 + nC1An-1X1 + nC2An-2X2 +….+ nCnA0Xn
Q6. Write a program given three integers A, B and N the task is to find N Arithmetic means between A and
B. We basically need to insert N terms in an Arithmetic progression. where A and B are the first and the last
terms.
Examples:
Input : A = 20 B = 32 N = 5
Output : 22 24 26 28 30
The Arithmetic progression series as
20 22 24 26 28 30 32
Q7. Write a program given an integer n, find the power of a given prime number(r) in n!
Examples :
Input : n = 6 r = 3
Page 106
Input : n = 2000 r = 7
Output : 330
Q8. Write a program given an array arr[ ] of size n such that elements of arr[ ] in range [0, 1, ..n-1]. Our task
is to divide the array into maximum number of partitions that can be sorted individually, then concatenated
to make the whole array sorted.
Examples :
Q9. Write a program given three integers A, B and N the task is to find N Geometric means between A and
B. We basically need to insert N terms in a Geometric progression. where A and B are the first and last
terms.
Examples:
Input : A = 2 B = 32 N = 3
Page 107
Output : 4 8 16
the geometric progression series as 2,
4, 8, 16 , 32
Input : A = 3 B = 81 N = 2
Output : 9 27
Q11. Write a program given a decimal number m, convert it into a binary string and apply n iterations, In
each iteration 0 becomes “01” and 1 becomes “10”. Find ith(based indexing) index character in the string
after nth iteration.
Examples :
Input : m = 5, n = 2, i = 3
Output : 1
Input :m = 3, n = 3, i = 7
Output : 0
Q11. Write a program given a large number as string s and an integer k which denotes the number of
breakpoints we must put in the number k <= string length. The task is to find maximum segment value after
putting exactly k breakpoints.
Examples:
Input : s = "8754", k = 2
Output : Maximum number = 87
Explanation : We need to two breakpoints. After
putting the breakpoints, we get following options
8 75 4
87 5 4
Page 108
Input : s = "999", k = 1
Output : Maximum Segment Value = 99
Explanation : We need to one breakpoint. After
putting the breakpoint, we either get 99,9 or
9,99.
Q12. Write a program given N, count the number of ways to express N as sum of 1, 3 and 4.
Examples:
Input : N = 4
Output : 4
Explanation: 1+1+1+1
1+3
3+1
4
Input : N = 5
Output : 6
Explanation: 1 + 1 + 1 + 1 + 1
1+4
4+1
1+1+3
1+3+1
3+1+1
Page 109
Q13. Write to a program to print first n non-square number (non perfect square) .
Q14. Write a program given a number as num, Find whether the given number is palindrome or not using
Bash Scripting.
Q15. Write a program to Find the smallest number such that the sum of its digits is N and it is divisible by
10^N.
Examples:
Input : N = 5
Output : 500000
500000 is the smallest number divisible
Page 110
Q16. Write a program considering a series of numbers composed of only digits 2, 3, 5, 7 (primes). First few
numbers in the series are 2, 3, 5, 7, 22, 23, 25, 27, 32, 33, 35, 37, 52, 53, 55, 57 .. etc. Given a number
constructed by 2, 3, 5, 7 digit only, we need to find position of this number in this series.
Examples:
Input : 22
Output : 5
22 is 5th number in series 2, 3, 5, 7, 22, ...
Input : 777
Output : 84
Q17. Write a program given a series 1 + 1/2^2 + 1/3^3 + …..+ 1/n^n, find out the sum of the series till nth
term.
Examples:
Input : n = 3
Output : 1.28704
Explanation : 1 + 1/2^2 + 1/3^3
Input : n = 5
Output : 1.29126
Explanation : 1 + 1/2^2 + 1/3^3 + 1/4^4 + 1/5^5
Q18. Write a program to Find the sum up to n terms of the series: 1.2.3 + 2.3.4 + … + n(n+1)(n+2).
In this 1.2.3 represent the first term and 2.3.4 represents the second term .
Examples:
Input : 2
Output : 30
1.2.3 + 2.3.4 = 6 + 24 = 30
Input : 3
Output : 90
Q19. Write a program given a number N, Find the number of ways you can draw N chords in a circle with
2*N points such that no 2 chords intersect.
Two ways are different if there exists a chord which is present in one way and not in other.
Examples:
Input : N = 2
Output : 2
Explanation: If points are numbered 1 to 4 in
clockwise direction, then different ways to
draw chords are:
{(1-2), (3-4)} and {(1-4), (2-3)}
Input : N = 1
Output : 1
Explanation: Draw a chord between points 1 and 2.
11 12 13 14 15
7 8 9 10
456
23
1
Sample Input and Output-2:
Enter a number of rows : 10
46 47 48 49 50 51 52 53 54 55
37 38 39 40 41 42 43 44 45
29 30 31 32 33 34 35 36
22 23 24 25 26 27 28
16 17 18 19 20 21
11 12 13 14 15
7 8 9 10
456
23
1
Sample Input and Output-3:
Enter the number of rows : 0
Invalid input
:
Page 113
SET-11
Q1. Write a C Program to calculate the sum of series for Nth terms.
At the time of execution, the program to print the message on the console as,
1+11+111+1111+11111
Sum of the series is : 12345
Q2.
Write a C program to find the Generic Root of any number.
At the time of execution, the program to print the message on the console as follows:
Hint : Generic root means that the sum of digits of a number unit.
Example : Generic root of 456 : 4 + 5 + 6 = 15 since 15 is two digit numbers so 1 + 5 = 6
So, generic root of 456 = 6
Note : Make sure to use \n at the end of the final output.
Q3. Write a C program to find the sum of minimum path in a triangle.
Page 114
Receive a row value from the user, calculate the value based on the user input to form a triangle and
receive the array value from the user based on the calculated value and finally find the sum of minimum
path.
At the time of execution, the program to print the message on the console as,
Enter 6 elements : 2 4 6 5 2 3
(Note : The value 6 calculated based on the row value given by the user)
Q4.
Write a C program to find the Latin square matrix nxn.
At the time of execution, the program to print the message on the console as,
234561
345612
456123
561234
612345
At the time of Execution, the program must print the message on the console as follows:
Enter the row value :
Q7. Write a program to find whether the two arrays are compatible or not using one-dimensional arrays.
Hint: Two arrays are said to be compatible if they are of the same size and if the ith element in the first
array is greater than or equal to the ith element in the second array for all i.
At the time of execution, the program should print the message on the console as:
Enter how many values you want to read :
Next, the program should print the messages one by one on the console as:
Enter the value of a[0] :
Page 116
Note: Use the printf() function with a newline character (\n) at the end.
Q8. Write a C program to find the number of days remaining in a year for the given date and month of
a year.
Sample Input and Output - 1:
Enter valid date with dd/mm/yyyy format : 06/05/2018
The number of days remaining : 239
Page 117
Note: Do use the printf() function with a newline character (\n) at the end.
Q9. Given an array of integers, Write a C program to count the number of duplicate array elements.
Note: Do use the printf() function with a newline character (\n) at the end.
Q10. You are given an array of integers, write a C program to compute the maximum differencebetween
any item and any lower indexed smaller item for all the possible pairs.
i.e., For a given array a, find the maximum value of a[j] - a[i] for all i, j where 0 ≤ i < j < n and a[i] < a[j]. If
there are no lower indexed smaller items for all the items, then return -1.
For example, given an array [ 1, 2, 6, 4], you would first compare 2 to the elements to its left. 1 is smaller, so
calculate the difference 2 - 1 = 1. 6 is bigger than 2 and 1, so calculate the differences 4 and 5. 4 is only
bigger than 2 and 1, and the differences are 2 and 3. The largest difference was 6 - 1 = 5.
Example :
n = 7, a = [2, 3, 10, 2, 4, 8, 1]
Differences are calculated as:
3 - [2] = [1]
10 - [3, 2] = [7, 8]
4 - [2, 3, 2] = [2, 1, 2]
8 - [4, 2, 3, 2] = [4, 6, 5, 6]
Note: Do use the printf() function with a newline character (\n) at the end.
Q11. Given an array of integers, Write a C program to move all 0's to the end of an array.
Note: Do use the printf() function with a newline character (\n) at the end.
Q12. Declare an array of 10 characters, Read one character at a time and place it in the array.
While placing it in the array it should be sorted i.e., the other elements in the array need to be
moved up or down.
For example,
input 1: 'a'
input 2: 'c'
input 3: 'd'
input 4: 'b'
When input 'b' is entered, the program should move 'c' to index 2, and 'd' to index 3 and 'b' should be
stored in index 1.
Sample Input and Output:
Enter number of characters : 5
input 0 : d
After iteration : d
input 1 : a
After iteration : a d
input 2 : c
After iteration : a c d
Page 119
input 3 : b
After iteration : a b c d
input 4 : f
After iteration : a b c d f
Note: Do use the printf() function with a newline character (\n) at the end.
Q13. Write a C program to check whether the array elements are consecutive or not.
Note: Do use the printf() function with a newline character (\n) at the end.
Set-12
Hint : Uniformity matrix is a matrix in which all the elements in the matrix are either completely even or
completely odd.
At the time of execution, the program should print the message on the console as:
Enter the row & column sizes of matrix :
For example, if the user gives the input as:
Enter the row & column sizes of matrix : 2 3
Next, the program should print the message on the console as:
Enter matrix 6 elements :
If the user gives the input as:
Enter matrix 6 elements : 4 0 2 6 8 4
Then the program should print on the console as:
The given matrix is
402
684
If the condition is true, then the program should print the output as :
The given matrix is a uniformity matrix
Page 120
4. Write a C program to find the largest element in each column of the matrix.
At the time of execution, the program should print the message on the console as:
Enter the row & column sizes of matrix :
For example, if the user gives the input as:
Enter the row & column sizes of matrix : 2 3
Next, the program should print the message on the console as:
Enter matrix 6 elements :
f the user gives the input as:
Enter matrix 6 elements : 6 7 4 5 9 1
Then the program should print the result as:
The given matrix is
674
591
Largest of column - 0 elements = 6
Largest of column - 1 elements = 9
Largest of column - 2 elements = 4
Note: Do use the printf() function with a newline character(\n).
5. Write a C program to convert a string into sorted characters.
At the time of execution, the program should print the message on the console as:
Enter a string :
Sorted characters : a a c d e n o r t t
Next, the program should print the messages one by one on the console as:
Note: Do use the printf() function with a newline character (\n) at the end.
Q7. Write a program to find the sum of positive elements of a one-dimensional array.
At the time of execution, the program should print the message on the console as:
Next, the program should print the messages one by one on the console as:
Note: Do use the printf() function with a newline character (\n) at the end.
Q8. Write a program to find the sum of even elements of a one-dimensional array.
At the time of execution, the program should print the message on the console as:
Next, the program should print the messages one by one on the console as:
Note: Do use the printf() function with a newline character (\n) at the end.
Q9.
Write a program to sort an array elements in ascending order of a one-dimensional array.
At the time of execution, the program should print the message on the console as:
Next, the program should print the messages one by one on the console as:
Note: Do use the printf() function with a newline character (\n) at the end.
Q10. Write a C program to find whether two arrays are same using one-dimensional arrays.
At the time of execution, the program should print the message on the console as:
Next, the program should print the messages one by one on the console as:
Note: Do use the printf() function with a newline character (\n) at the end.
Q11. Write a C program to perform matrix addition on two dimensional matrix.
At the time of execution, the program should print the message on the console as:
Next, the program should print the message on the console as:
Next, the program should print the message on the console as:
Next, the program should print the message on the console as:
Next, the program should print the message on the console as:
Next, the program should print the message on the console as:
Next, the program should print the message on the console as:
Next, the program should print the message on the console as:
The 2 x 3 matrix :
785
412
Given an array and limits (lower and upper limits), Check the sum of the sub array in the given limit is prime
or not.
Examples :
Input :
a[] = {1, 2, 3, 5, 5, 4, 7, 8, 9};
lower = 3, upper = 6
Output : Yes
Explanation:- sub array is {3, 5, 5, 4} and sum of sub array 3 + 5 + 5 + 4 = 17 which is prime, so the output is
Yes.
Input :
a[] = {1, 6, 4, 5, 5, 4, 7, 8, 9};
lower = 2, upper = 5
Output : No
Explanation:- sub array is {6, 4, 5, 5} and sum of sub array 6 + 4 + 5 + 5 = 20 which is not prime so the output
is No.
Q15. Write a program square matrix of order n * n, we have to reverse the elements of both diagonals.
Page 130
Example - 1:
Input : {1, 2, 3,
4, 5, 6,
7, 8, 9}
Output :{9, 2, 7,
4, 5, 6,
3, 8, 1}
Explanation:
Major Diagonal Elements before: 1 5 9
After reverse: 9 5 1
Minor Diagonal Elements before: 3 5 7
After reverse: 7 5 3
Sample Input and Output - 1 :
Enter row size : 3
Enter coloum size : 3
Enter 9 elements : 1 2 3 4 5 6 7 8 9
After reversing the diagonals elements :
9 2 7
4 5 6
3 8 1
Sample Input and Output - 2 :
Enter row size : 3
Enter coloum size : 2
Given matrix is not a square
Q17. Given an array arr[ ] of size n where every element is in range from 0 to n-1.
Rearrange the given array so that arr[i] becomes arr[arr[i]]. This should be done with O(1) extra space.
Examples:
Input: arr[ ] = {3, 2, 0, 1} Output: arr[ ] = {1, 0, 3, 2}
Input: arr[ ] = {4, 0, 2, 1, 3} Output: arr[ ] = {3, 4, 2, 0, 1}
Page 131
If the extra space condition is removed, the question becomes very easy. The main part of the question is to
do it without extra space.
Sample Input and Output - 1:
Enter size : 5
Enter 5 elements : 4 0 2 1 3
The result : 3 4 2 0 1
Sample Input and Output - 2:
Enter size : 3
Enter 3 elements : 1 2 3
The result : Invalid input
Q18. Given an array Arr[] of N integers. We need to write a program to find minimum number of elements
needed to be removed from the array, so that sum of remaining elements is even.
Examples:
Input : {1, 2, 3, 4}
Output : 0
Sum is already even
Input : {4, 2, 3, 4}
Output : 1
We need to remove 3 to make
sum even.
Q19. Write a program array arr[] of n integers. The task is to find the sum of product of each element with
each element after it in the array. In other words, find sum of product of each arr[i] with each arr[j] such
that j > i.
Examples :
Input : arr[] = {9, 3, 4, 2}
Output : 107
Sum of product of arr[0] with arr[1],
arr[2], arr[3] is 9*3 + 9*4 + 9*2 = 81
Sum of product of arr[1] with arr[2],
arr[3] is 3*4 + 3*2 = 18
Product of arr[2] with arr[3] is 4*2 = 8
Sum of all these sums is 81 + 18 + 8 = 107
SET-13
Q1. Write a program to Find the first non-repeating element in a given array of integers.
Examples:
Page 133
Input : -1 2 -1 3 2
Output : 3
Explanation : The first number that does not
repeat is : 3
Input : 9 4 9 6 7 4
Output : 6
Q2. Write a program given an array, find the least frequent element in it. If there are multiple elements that
appear least number of times, print any one of them.
Examples :
Q3. Write a program given a matrix, check whether it’s Magic Square or not. A Magic Square is a n x n
matrix of distinct element from 1 to n2 where sum of any row, column or diagonal is always equal to same
number.
Examples:
Q4. Write a program given an integer matrix with odd dimensions. Find the square of the diagonals
elements on both sides.
Examples:
Input : Enter matrix row Size : 3
Enter matrix column Size : 3
123
456
789
Output : Diagonal one: 1 25 81
Diagonal two: 9 25 49
Diagonal two : 9 25 49
Q5. Given a sorted array and an integer k, Write a program to traverse the array and if the element in array
is k, double the value of k and continue traversal. In the end return value of k. Otherwise print "No element
found".
Examples:
Q6. Write a program given an array of size n-1 and the mean of n elements (one element is not given). We
need to find the missing value x in the array.
Examples:
Input : a[] = {2, 4, 20}
Mean = 9
Output : Missing Element = 10
Explanation : Mean of (2, 4, 20, 10) is
(2 + 4 + 20 + 10)/4 = 9
Page 137
Q7. Write a program sorted array with duplicate elements and we have to find the index of last duplicate
element and print index of it and also print the duplicate element. If no such element found print a
message.
Q8. Write a program to Find the sum of number of series after dividing the element of array from previous
element.
Examples:
Input : 3 7 9 10 12 18
Explanation: 3 + 7/3 + 9/7 + 10/9 + 12/10 + 18/12 = 9 (taking only integer part)
Output : 9
Page 138
Q10. Write a program given a square matrix,swap the element of major and minor swap diagonals.
Major Diagonal Elements of a Matrix :
The Major Diagonal Elements are the ones that occur from Top Left of Matrix Down To Bottom Right
Corner. The Major Diagonal is also known as Main Diagonal or Primary Diagonal.
Minor Diagonal Elements of a Matrix :
The Minor Diagonal Elements are the ones that occur from Top Right of Matrix Down To Bottom Left
Corner. Also known as Secondary Diagonal.
Example :
Input : 0 1 2
345
678
Output : 2 1 0
345
876
Q11. Write a program given an array of n distinct elements, count total number of subsets.
Examples:
Input : {1, 2, 3}
Output : 8
Explanation
the array contain total 3 element.its subset
are {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {3, 1}, {1, 2, 3}.
so the output is 8.
Q12. Given a number n, Write a program to print n terms of fibonacci series in reverse order.
Q15. Write a program given an array of n integers, we have to reverse sort the array elements such the
equal keys are stable after sorting.
Enter 5 elements : 4 3 2 3 4
4 4 3 3 2
Sample Input and Output-2:
Enter array size : 0
Invalid array size
Q16. Write a program given heights of consecutive buildings, find the maximum number of consecutive
steps one can put forward such that he gain a increase in altitude while going from roof of one building to
next adjacent one.
Examples :
Q17. Write a program given a 2D array, sort each row of this array and print the result.
Examples:
Input :
77 11 22 3
11 89 1 12
32 11 56 7
11 22 44 33
Output :
3 11 22 77
1 11 12 89
7 11 32 56
11 22 33 44
Page 142
Q18. Write a program given three different types of cups (a[]) and saucers (b[]), and n number of shelves,
Find if neat arrangement of cups and shelves can be made.
Arrangement of the cups and saucers will be neat if it follows the below rules:
No shelf can contain both cups and saucers
There can be no more than 5 cups in any shelf
There can be no more than 10 saucers in any shelf
Examples:
Examples:
Q20. Write a program given two arrays of positive integers. Select two sub-arrays of equal size from each
array and calculate maximum possible OR sum of the two sub-arrays.
Note: Let f(x, l, r) is the OR sum of all the elements in the range [l, r] in array x.
Examples :
Input : A[] = {1, 2, 4, 3, 2}
B[] = {2, 3, 3, 12, 1}
Output : 22
Explanation: Here, one way to get maximum
sum is to select sub-array [l = 2, r = 4]
f(A, 2, 4) = 2|4|3 = 7
f(B, 2, 4) = 3|3|12 = 15
So, f(A, 2, 4) + f(B, 2, 4) = 7 + 15 = 22.
This sum can be achieved in many other ways.
Set 14
Q1. Write a program given an array of n integers(duplicates allowed). Print “Yes” if it is a set of contiguous
integers else print “No”.
Examples:
Input : arr[] = {5, 2, 3, 6, 4, 4, 6, 6}
Output : Yes
The elements form a contiguous set of integers
which is {2, 3, 4, 5, 6}.
Input : 2456
Output : Currency Count
2000 : 1
200 : 2
50 : 1
5:1
1:1
Input : 1, 3, 2, 2, 1
Output : 1 2 3
Input : 1, 1, 1, 2, 2, 3
Output : 1 2 3
Constraints:
1 ≤ number of elements in the set ≤ 1000
INT_MIN ≤ each element in the set ≤ INT_MAX
Examples:
Q15. Write a program given an array that contains both positive and negative integers, Find the product of
the maximum product sub array. Expected Time complexity is O(n) and only O(1) extra space can be used.
The maximum product can be positive, negative or zero.
Examples:
Input : A = [1, 2, 2, 2, 3, 3, 4, 4, 4]
Q=2
L=1R=8
L=0R=4
Output : 5
2
Explanation: We have 5 index i which has
Ai=Ai+1 in range [1, 8). We have
2 indexes i which have Ai=Ai+1
in range [0, 4).
Input :A = [3, 3, 4, 4]
Q=2
L=0R=3
L=2R=3
Output : 2
1
k = 12, m = 4
Output : No
Set-15
Q1:Write a program given an array of 0’s and 1’s, we need to write a program to find the minimum number
of swaps required to group all 1’s present in the array together.
Examples:
Q2:Write a program given an array of n integers in non-decreasing order. Find the number of occurrences
of the most frequent value within a given range.
Examples:
Q3:Write a program given an array A[] of n-elements. There are two players Alice and Bob. A Player can
choose any element from array and remove it. If the bitwise XOR of all remaining elements equals 0 after
removal of selected element, then that player looses. This problem is variation of nim-game.
Note : Each players play game alternately. Find out winner if both of the players play optimally. Alice starts
the game first. In case one-element in array consider its value as the XOR of array.
Examples :
Input : A[] = {3, 3, 2}
Output : Winner = Bob
Explanation : Alice can select 2 and remove it that make XOR of array equals to zero also if Alice choose 3 to
remove than Bob can choose any of 2/3 and finally Alice have to make his steps.
Input : A[] = {3, 3}
Output : Winner = Alice
Explanation : As XOR of array is already zero Alice can’t select any element to remove and hence Alice is
winner.
Q4:Write a program given the Integer n and also in the next line 2*n integers which represents an
Arithmetic Progression series a1, a2, a3…a2n they are in AP. We need to find the sum of a12 – a22 + a32….
+ a2n-12 – a2n2
Examples:
Input : n = 2
a[] = {1 2 3 4}
Output : -10
Explanation : 12 - 22 +
32 42 = -10.
Input : n = 3
a[] = {2 4 6 8 10 12}
Page 156
Output : -84
Q5:Write a program given a sorted array of distinct positive integers, print all triplets that form AP (or
Arithmetic Progression)
Examples :
Input : arr[] = { 2, 6, 9, 12, 17, 22, 31, 32, 35, 42 };
Output :
6 9 12
2 12 22
12 17 22
2 17 32
12 22 32
9 22 35
2 22 42
22 32 42
Input : arr[] = { 3, 5, 6, 7, 8, 10, 12};
Output :
357
567
678
6 8 10
8 10 12
Q6:Write a program given an array of 2n integers, we need to calculate function F(x) = ∑Ai such that x&i==i
for all x. i.e, i is a bitwise subset of x. i will be a bitwise subset of mask x, if x&i==i.
Examples:
Input: A[] = {7, 12, 14, 16} , n = 2
Output: 7, 19, 21, 49
Explanation: There will be 4 values of x: 0,1,2,3
So, we need to calculate F(0),F(1),F(2),F(3).
Now, F(0) = A0 = 7
F(1) = A0 + A1 = 19
F(2) = A0 + A2 = 21
F(3) = A0 + A1 + A2 + A3 = 49
Input: A[] = {7, 11, 13, 16} , n = 2
Output: 7, 18, 20, 47
Explanation: There will be 4 values of x: 0,1,2,3
So, we need to calculate F(0),F(1),F(2),F(3).
Now, F(0) = A0 = 7
F(1) = A0 + A1 = 18
F(2) = A0 + A2 = 20
F(3) = A0 + A1 + A2 + A3 = 47
Enter a number : 2
Enter array size : 4
Enter array 4 elements : 7 12 14 16
7 19 21 49
Q7:Write a program given an array of N numbers, We need to maximise the sum of selected numbers.
At each step you need to select a number Ai, delete one occurrence of Ai-1 (if exists), Ai+1 (if exists) and Ai
each from the array.
Repeat these steps until the array gets empty. The problem is to maximize the sum of selected numbers.
Note: We have to delete Ai+1 and Ai-1 elements if they are present in the array and not Ai+1 and Ai-1.
Examples:
Input : a[] = {1, 2, 3}
Output : 4
Explanation: At first step we select 1, so 1 and
2 are deleted from the sequence leaving us with 3.
Then we select 3 from the sequence and delete it.
So the sum of selected numbers is 1+3 = 4.
Input : a[] = {1, 2, 2, 2, 3, 4}
Output : 10
Explanation : Select one of the 2's from the array, so
2, 2-1, 2+1 will be deleted and we are left with {2, 2, 4},
since 1 and 3 are deleted. Select 2 in next two steps,
and then select 4 in the last step.
We get a sum of 2+2+2+4=10 which is the maximum possible.
Q8:Write a program given an array of size n and a positive integer k, find the maximum number of trailing
zeros in the product of the subsets of size k.
Examples:
Page 159
Q9:Write a C program to remove duplicate element and print unique value in an array.
At the time of execution, the program to print the message on the console as,
Element -
Unique element present in the array :
At the time of execution, the program to print the message on the console as,
Note : If the given array values does not fall under the condition then the program should print the
message The given matrix is not a lower triangular matrix.
Q11:Write a C program to remove the occurrence of the word “the” from the given string.
Page 161
Q13:Write a C program to compute the frequency of each lowercase letter in the string.
Input and Output Format:
Input consists of a string.
Assume that all characters in the string are lowercase letters and the maximum length of the
string is 200.
The letters are displayed sorted in ascending order.
Refer sample input and output for formatting specifications.
Q17:Write a C program to sort the alphabets contained in a given string in descending order.
Input and Output Format:
Input consists of a string.
Assume that the input string consists of only letters and the maximum length of the string is 20.
Refer sample input and output for formatting specifications.
Q18:In these days kids are introduced to computers at a very early age. The kids were taught about
alphabets, digits and blank spaces.
The teacher asked the student to count the vowels, consonants, digits and white spaces in a string.
The teacher found it a bit difficult to evaluate these tests and she knew that the 12th class students are
learning C programming.
So she assigned this task to them to count the vowels, consonants, digits and white spaces in a string. Can
you please help them out?
Write a C program to count the vowels, consonants, digits and white spaces in a string.
Input and Output Format:
Input consists of a string.
Assume the maximum length of the string is 200.
The characters in the string can contain both uppercase and lowercase.
Refer sample input and output for formatting specifications.
Sample Input and Output:
Enter a line of string : This program is very easy 2 complete
Vowels : 10
Consonants : 19
Digits : 1
White spaces : 6
Write a program to remove special characters and numbers in the input string.
Q20:Write a C program using do while loop to print the abbreviation for a given sentence.
Input format:
Get a sentence from the user.
Output Format:
Abbreviate the given sentence. Refer the Sample input and output.
Sample Input and Output:
Enter the sentence : American Standard Code for Information Interchange
The abbreviation : ASCII
Set 16
Q1: After the annual holidays, schools re-opens today. The class teacher wants to prepare attendance sheet
with all student names in alphabetical order.
The teachers found it a bit difficult to prepare attendance list and they requested the school management
to lessen their burden by automating this task.
The 12th class students are learning C programming and they took up the task of automating the
arrangement of names in alphabetical order. Can you please help them out?
Write a C program to arrange the given names in the alphabetical order using arrays.
Sample Input and Output:
Enter the number of names : 5
Enter the names : safiq mani arun sasi kumar
The sorted name list is : arun kumar mani safiq sasi
Q2: A special school is run by an NGO for kids with Dyslexia. As we all know these children will start writing
the letters backwards or in reverse.
Once special care is taken to correct this issue and once they are introduced to words, they will start writing
the words in reverse.
Page 165
The teachers do not want to discourage the children at the start itself and they have decided to mark the
works written in reverse also as correct.
Can you please help the teacher in correcting the answer sheets by writing a C program?
Write a C program to check whether the second word is the reverse of first word. Do not use strrev()
function.
Input Format:
Input consists of 2 strings.
Assume that the maximum length of the string is 50.
Output Format:
Refer sample input and output for formatting specifications.
Sample Input and Output:
Enter the actual word : Excellent
Enter the word the student has typed : tnellecxE
It is correct
Q3: As a young jedi you must learn to converse with Yoda. You have found a simple rule that helps change a
“normal” sentence into “Yoda talk”.
Take the first two words in the sentence and place them at the end.
Write a C program that uses this rule to change normal sentence into “Yoda talk”.
Input Format:
Input consists of a string that you must change into “Yoda talk”.
Assume that the maximum length of the string is 100;
Output Format:
Print the corresponding sentence in Yoda talk.
Sample Input and Output:
Enter a normal sentence : India is very good in culture
The Yoda talk sentence is : very good in culture India is
Note: Write the code in the function yodaTalk() at "YodaTalk1.c"
Q4: Oh my God!!! Someone is trying to break into Anna University's Database and steal sensitive research
information.
It is now up to us to stop this attack. Fortunately our defense mechanisms have traced the attacks to their
source.
The fastest way to stop the attacks is to disable the source. So all we need to do is to teach that guy a
lesson, by planting a virus in his own system.
But before we can do that, we need to break through all the layers of the security he has put around
himself.
Our sources tell us that the first layer is based on ASCII encryption. We must penetrate through this layer as
Page 166
The password to his system is a single character which is the average of the ascii values of his username.
Input Format:
Input consists of a single string which corresponds to the username of the attacker.
The length of the string should be between 2 and 50, both inclusive.
Output Format:
Output consists of a single character.
Sample Input and Output:
Enter the string : IndiA
The password : Z
Q5: Write a program to find whether the two given strings are anagrams or not.
Anagrams are words or phrases made by mixing up the letters of other words or phrases.
Input and Output Format:
Input consists of 2 string.
Assume that all characters in the string are lowercase letters or spaces and the maximum length
of the string is 100.
Refer sample input and output for formatting specifications.
For example, if the input string is “aaabcdeeee”, then the program should print “a3b1c1d1e4".
Page 167
Example:
Input string : abcabcbb
The length of longest substring with no repeating characters is 3 (abc).
Examples:
Input - 1 : hello
Output - 1 : holle
Input - 2 : helloworld
Output - 2: hollowerld
Sample Input and Output:
Enter a string : HelloWorld
The result : HolloWerld
Q15: Write a C program to check if a given string has balanced parentheses.
The teachers found it a bit difficult to prepare attendance list and they requested the school management
to lessen their burden by automating this task.
Page 169
The 12th class students are learning C programming and they took up the task of automating the
arrangement of names in alphabetical order. Can you please help them out?
Write a C program to arrange the given names in the alphabetical order using arrays.
Sample Input and Output:
Enter the number of names : 5
Enter the names :
safiq
mani
arun
sasi
kumar
The sorted name list is :
arun
kumar
mani
safiq
sasi
Q18: Whole India is tweeting about the probable names for Aishwarya Rai's daughter.
Some astrologers are suggesting that she will grow up to be a more famous celebrity than Aishwarya if her
name is a palindrome.
As we all know, a palindrome is a word that can be read the same way in either direction.
Write a C program to determine whether a given word is a palindrome or not. Do not use any string library
functions.
Input Format:
Input consists of a single string.
Assume that the maximum length of the string is 50.
Output Format:
Refer sample input and output for formatting specifications.
Q20: Write a C program to read a company name and year of establishment using sscanf() and print them.
For the given sentence as input, censor a specific word with asterisks ‘*‘.
Example :
Input :
Word : "computer"
text : "CodeTantra is a computer science hands-on programming portal for countries.
People who love computer and computer codes can contribute their valuables/ideas on
computer codes/structures on here."
Output :
CodeTantra is a ******** science hands-on programming portal for countries.
People who love ******** and ******** codes can contribute their valuables/ideas on ********
codes/structures on here.
Sample Input and Output - 1:
Enter a sentence : Ganga is a river
Enter a word : is
Ganga ** a river
Q2:Write a program to find the total number of non-empty substrings of a string with N characters. Here
we use the word properly because we do not consider string itself as part of the output.
Example - 1:
Input : str = "abc"
Output : 6
Proper substrings are "a", "b", "c", "ab", "bc", "abc"
Example - 2:
Input : str = "abcd"
Page 171
Output : 10
Proper substrings are "a", "b", "c", "d", "ab", "bc", "cd", "abc", "bcd" and "abcd"
Sample Input and Output:
Enter the string : abc
6
Q3:Write a program Given two strings, copy one string to other using recursion. We basically need to write
our own recursive version of strcpy in C.
Q4:Write a program Given a string of character the task is to convert each character of a string into the
equivalent binary number.
Q5:problem solving
Q6:Write a program given an expression exp of length n consisting of some brackets. The task is to print the
bracket numbers when the expression is being parsed.
Examples :
Input : (a+(b*c))+(d/e)
Output : 1 2 2 1 3 3
The highlighted brackets in the given expression
(a+(b*c))+(d/e) has been assigned the numbers as:
Page 172
1 2 2 1 3 3.
Q7:Write a program given a string, we have to find the longest word in the input string and then calculate
the number of characters in this word.
Examples:
Input : A computer science portal for codetantra
Output : Longest word's length = 10
Input : I am an intern at code tantra
Output : Longest word's length = 6
Input : x = 'a'
Output : string s = "a"
Q9:Given two strings, Write a program to check if the two strings are equal or not.
Examples:
Input : ABCD, XYZ
Output : ABCD is not equal to XYZ
ABCD is greater than XYZ
Page 173
Input : 1100
Output : YES
Explanation : (1100) is 12 and hence a multiple of 3
Q11:Write a program given a string ‘s’ and an integer k, find other string ‘t’ such that ‘t’ is the largest
subsequence of given string ‘s’ and each character of ‘t’ must occur at least k times in string s.
Page 174
Q12:Write a program find given String have at least one character is different or not.
Input : abccpb
Output : Yes, both halves differ by at least one character
Q13:Write a program given a string S, change the smallest number of letters in S such that all adjacent
characters are different. Print the resultant string.
Examples :
Page 175
Input : S = "aab"
Output: acb
Explanation :
Loop will start for i-th character, which
is second ‘a’. It’s cannot be ‘b’ since it
matches with third char. So output should
be ‘acb’.
Input : S = "aabcc"
Output: acbca
Explanation :
Resultant string, after making minimal
changes. S = "acbca". We made two
changes, which is the optimal solution here.
Q14:Write a program to convert first character uppercase in a sentence and if apart from first character if
any character is in Uppercase then convert in into Lowercase?
Q15:problem solving
Q16:Write a program given a string and the task is to count vowels, consonant, digits and special character
in string. Special character also contains the white space.
Q17:Write a program given two strings str1 and str2, check if str2 can be formed from str1
Example :
Input : str1 = codetantra, str2 = code
Output : Yes
Here, string2 can be formed from string1.
Q18:Write a program given a string str and a character x, find last index of x in str.
Examples :
Q19:Write a program given a string s (containing lowercase letters only), we have to find the minimum cost
to construct the given string. The cost can determined using the following operations:
1. Appending a single character cost 1 unit
2. A sub-string of new string(intermediate string) can be appended without any cost
Note* Intermediate string is the string formed so far.
Examples:
Input : "code"
Output : cost: 4
Explanation:
appending 'c' cost 1, string "c"
appending 'o' cost 1, string "co"
appending 'd' cost 1, string "cod"
appending 'e' cost 1, string "code"
Hence, Total cost to construct "code" is 4
Input : "abab"
Output : cost: 2
Explanation:
Appending 'a' cost 1, string "a"
Appending 'b' cost 1, string "ab"
Page 178
Q20:Write a program given an expression, find and mark matched and unmatched parenthesis in it. We
need to replace all balanced opening parenthesis with 0, balanced closing parenthesis with 1 and all
unbalanced with -1.
Set 18
Q1. Write a program Given a string with brackets. If the start index of the open bracket is given, Find the
index of the closing bracket.
Examples:
Input : abcdef
Output : 6
Explanation: replace 'a', 'b' and
'c' => cost= 1 + 2 + 3 = 6
Input : s1 = "pqrspqrs"
s2 = "pqrspqrspqrspqrs"
Output : 2
The two common base strings are "pqrs"
and "pqrspqrs".
Input: s1 = "bb"
s2 = "bbb"
Output: 2
Q4. Write a program given a string S, we need to find reciprocal of it. The reciprocal of the letter is found by
finding the difference between the position of the letter and the first letter ‘A’. Then move the same
number of steps from letter ‘Z’. The character that we reach after above steps is reciprocal.
Reciprocal of Z is A and vice versa because if you reverse the position of the alphabet A will be in the
position of Z.
Similarly, T is the reciprocal of G, J is the reciprocal of Q.
Sample Input and Output-1:
Enter a string : PRAKHAR
KIZPSZI
Sample Input and Output-2:
Enter a string : VARUN
EZIFM
Q5. Write a program given two strings which are of lengths n and n+1. The second string contains all the
character of the first string, but there is one extra character. Your task to find the extra character in the
second string.
Examples :
Input : X = "CDBABC"
Y = "ADCABD"
Output : Anagram : ADBADC
Number of changes made : 2
Input : X = "PJPOJOVMAK"
Y = "FVACRHLDAP"
Output : Anagram : ACPDFHVLAR
Number of changes made : 7
antraCodeT
Note : Do use '\n' in printf() at the end of displaying the output.
Q15. Write a program to find the next smallest palindrome number of the given number.
For example, if given number is 12345, then the next smallest palindrome is 12421.
Sample Input and Output 1:
Enter number : 567
The next palindrome number : 575
Q16. Write a program to find whether the given two strings are anagrams or not.
Anagrams are words or phrases made by mixing up the letters of other words or phrases.
Input and Output Format:
Input consists of 2 string.
Assume that all characters in the string are lowercase letters or spaces and the maximum length
of the string is 100.
Refer sample input and output for formatting specifications.
Q19. Write a C program to implement a menu driven calculator to work with integers.
Input Format:
Input consists of 3 integers.
The first 2 integers correspond to the operands and the third integer corresponds to the choice of
operation.
Output Format:
Output consists of a single integer or floating point number based on the choice of operation.
All floating point numbers are displayed with respect to 2 decimal places.
SET19
Q1: In the mini project 4th module is to find whether the number is prime or not. Rita allotted this function
to Sonia.
Help Sonia to write a C program to find whether the given number is prime or not.
Function Specification:
int findPrime(int n); - should return 1 if n is prime, else 0.
Input Format:
Input consists of 1 integer.
Output Format:
Output consists of a single integer.
Display 1 if the number is prime and 0 if the number is not prime.
Refer sample input and output for formatting details.
Rita allotted this function to Johnny. Rita gave a hint about leap year conditions to Johnny.
Hint:
In general terms the algorithm for calculating a leap year is as follows.
A year will be a leap year if it is divisible by 4 but not by 100. If a year is divisible by 4 and by 100, it is not a
leap year unless it is also divisible by 400.
Thus years such as 1996, 1992, 1988 and so on are leap years because they are divisible by 4 but not by
100.
For century years, the 400 rule is important. Thus, century years 1900, 1800 and 1700 while all still divisible
by 4 are also exactly divisible by 100. As they are not further divisible by 400, they are not leap years.
Help Johnny to write a program to check whether a given year is a leap year or not?
Function Specification:
int leapyear(int year); - The function returns 1 if it is leap year, else it returns 0.
Input Format:
Input consists of a single integer.
Output Format:
Output consists of a single line.
Refer sample input and output for formatting details.
For example, if given number is 12345, then the next smallest palindrome is 12421.
Sample Input and Output 1:
Enter number : 567
The next palindrome number : 575
Page 188
Q7: Write a C program to find the square root of a number without using inbuilt function.
Function Specifiacation:
float squareroot(int) - this function accepts the number as argument and returns the square root.
Input format :
Input consists of an integer value.
Output Format :
Output consists of a float value.
Q11: Write a C program to implement a menu driven calculator to work with integers.
Input Format:
Input consists of 3 integers.
The first 2 integers correspond to the operands and the third integer corresponds to the choice of
operation.
Output Format:
Output consists of a single integer or floating point number based on the choice of operation.
All floating point numbers are displayed with respect to 2 decimal places.
Anagrams are words or phrases made by mixing up the letters of other words or phrases.
Input and Output Format:
Input consists of 2 string.
Assume that all characters in the string are lowercase letters or spaces and the maximum length
of the string is 100.
Refer sample input and output for formatting specifications.
Q13: Write a program find Fibonacci Cube Graph You are given input as an order of graph n (highest
number of edges connected to a node), you have to find the number of vertices in a Fibonacci cube graph
of order n. (Using functions)
Examples with explanation :
Input : n = 3
Output : 5
Explanation :
Fib(n + 2) = Fib(5) = 5
Input : n = 2
Output : 3
Sample Input and output-1:
Enter the order of the graph : 3
5
Sample Input and output-2:
Enter the order of the graph : 0
Invalid input
Q14: Write a program given an array A[] consisting 0s, 1s and 2s, write a function that sorts A[]. The
functions should put all 0s first, then all 1s and all 2s in last.
Sample Input and Output-1:
Enter array size : 6
Enter 6 elements : 1 0 2 2 0 1
0 0 1 1 2 2
Sample Input and Ouput-2:
Enter array size : 7
Enter 7 elements : 1 2 0 0 2 1 1
0 0 1 1 1 2 2
Sample Input and Ouput-3:
Enter array size : 0
Invalid input
Q15: Write a program given 3 arrays (A, B, C) which are sorted in ascending order, we are required to
merge them together in ascending order and output the array D. (Using functions)
Examples:
Input : A = [1, 2, 3, 4, 5]
B = [2, 3, 4]
C = [4, 5, 6, 7]
Output : D = [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7]
Input : A = [1, 2, 3, 5]
B = [6, 7, 8, 9 ]
C = [10, 11, 12]
Output: D = [1, 2, 3, 5, 6, 7, 8, 9. 10, 11, 12]
Q16: Write a program Given a number n, print n-th number in Newman-Conway Sequence. Newman-
Conway Sequence is the one which generates the following integer sequence.
Page 191
Input : 3
Output : 6
Explanation : 1 + 2 + 3 = 6
Input : 5
Output : 15
Explanation : 1 + 2 + 3 + 4 + 5 = 15
Input : N = 5 and M = 7
Output : YES
Explanation : as numbers from 1 to 5 can be divided into two sets {1, 2, 3, 5} and {4} such that absolute
difference between the sum of both sets is 11 – 4 = 7 which is equal to M and also GCD(11, 4) = 1.
Page 192
Input : N = 6 and M = 3
Output : NO
Determine if N is a multiple of 3.
Constraints:
2 ≤K ≤1012
1 ≤d0 ≤9
0 ≤d1 ≤9
Sample Input and Output-1:
Enter number of digites : 13
Enter values for d0 and d1 : 8 1
Yes
Sample Input and Output-2:
Enter number of digites : 5
Enter values for d0 and d1 : 3 4
No
Set-20
Q1:Write a program given an algebraic expression of the form (x1 + x2 + x3 + . . . + xn) * (y1 + y2 + . . . + ym)
and
(n + m) integers. Find the maximum and minimum value of the expression using the given integers.
Consstraint :
n <= 50
m <= 50
-50 <= x1, x2, .. xn <= 50
Examples:
Input : n = 2, m = 2
arr[] = {1, 2, 3, 4}
Page 193
Output : Maximum : 25
Minimum : 21
The expression is (x1 + x2) * (y1 + y2) and
the given integers are 1, 2, 3 and 4. Then
maximum value is (1 + 4) * (2 + 3) = 25
whereas minimum value is (4 + 3) * (2 + 1)
= 21.
Input : n = 3, m = 1
arr[] = {1, 2, 3, 4}
Output : Maximum : 24
Minimum : 9
Q2:Write a program given an algebraic expression of the form (x1 + x2 + x3 + . . . + xn) * (y1 + y2 + . . . + ym)
and
(n + m) integers. Find the maximum and minimum value of the expression using the given integers.
Consstraint :
n <= 50
m <= 50
-50 <= x1, x2, .. xn <= 50
Examples:
Input : n = 2, m = 2
arr[] = {1, 2, 3, 4}
Output : Maximum : 25
Minimum : 21
The expression is (x1 + x2) * (y1 + y2) and
the given integers are 1, 2, 3 and 4. Then
maximum value is (1 + 4) * (2 + 3) = 25
whereas minimum value is (4 + 3) * (2 + 1)
= 21.
Page 194
Input : n = 3, m = 1
arr[] = {1, 2, 3, 4}
Output : Maximum : 24
Minimum : 9
Q3:Write a program given an array of positive numbers and a number k, find the number of subarrays
having product exactly equal to k. We may assume that there is no overflow.
Examples:
Q4:Write a program given two numbers, n >= 0 and 0 <= k <= n, count the number of derangements with k
fixed points.
Examples:
Input : n = 3, k = 0
Output : 2
Since k = 0, no point needs to be on its
original position. So derangements
are {3, 1, 2} and {2, 3, 1}
Input : n = 3, k = 1
Output : 3
Since k = 1, one point needs to be on its
original position. So partial derangements
are {1, 3, 2}, {3, 2, 1} and {2, 1, 3}
Input : n = 7, k = 2
Output : 924
Q5:Write a program given a list of strings, find the largest string among all. Largest string is the string with
largest number of unique characters
Example :
Q6:Write a program given a number N. our task is to find the closest Palindrome number whose absolute
difference with given number is minimum and absolute difference must be greater than 0.
Examples:
Input : N = 121
Output : 131 or 111
Both having equal absolute difference
with the given number.
Q7:Write a program given a string s, count special sub-strings in it. A Sub-string of S is said to be special if
either of the following properties is satisfied.
It starts with a vowel and ends with a consonant.
It starts with a consonant and ends with a vowel.
Examples:
Input : S = "aba"
Output : 2
Substrings of S are : a, ab, aba, b, ba, a
Out of these only 'ab' and 'ba' satisfy the
condition for special Substring. So the
answer is 2.
Page 197
Q8:Write a program given n cities and there are roads in between some of the cities. Somehow all the
roads are damaged simultaneously. We have to repair the roads to connect the cities again. There is a fixed
cost to repair a particular road. Find out the minimum cost to connect all the cities by repairing roads. Input
is in matrix(city) form, if city[i][j] = 0 then there is not any road between city i and city j, if city[i][j] = a > 0
then the cost to rebuild the path between city i and city j is a. Print out the minimum cost to connect all the
cities.
It is sure that all the cities were connected before the roads were damaged.
Examples:
Input : 0 3 1 6 0 0
305030
150564
605002
036006
004260
Output : 13
13
Q9:Write a program given a range [L, R], and a prime number P. We are required to find the sum of the
highest power of P in all numbers from L to R.
Examples:
Input : L = 1, R = 10, P = 2
Output : 8
There are 10 integers in the range, and:
In 1 the highest power of 2 is 0
In 2 the highest power of 2 is 1
In 3 the highest power of 2 is 0
Similarly the highest powers of 2 in 4,
5, 6, 7, 8, 9, 10 are 2, 0, 1, 0, 3,
0, 1 respectively.
Q10:Write a program to print all distinct permutations of a given string in sorted order. Note that the input
string may contain duplicate characters.
In mathematics, the notion of permutation relates to the act of arranging all the members of a set into
some sequence or order, or if the set is already ordered, rearranging (reordering) its elements, a process
called permuting.
Source – Wikipedia
Examples:
Input : BAC
Output : ABC ACB BAC BCA CAB CBA
Input : AAB
Output : AAB ABA BAA
Input : DBCA
Output: ABCD ABDC ACBD ACDB ADBC ADCB BACD BADC BCAD BCDA BDAC BDCA CABD CADB CBAD CBDA
CDAB CDBA DABC DACB DBAC DBCA
DCAB DCBA
Q11:Write a program given a number as string s, find the sum of all the elements present in all possible
subsequences of s.
Examples :
Input : s = "123"
Output : 24
Explanation : all possible sub-sequences are
1, 2, 3, {1, 2}, {2, 3}, {1, 3}, {1, 2, 3}
Page 200
which add up to 24
Input : s = "453"
Output : 48
Q12:Write a program given a number, check if it is squarefree or not. A number is said to be square free if
no prime factor divides it more than once, i.e.,the largest power of a prime factor that divides n is one. First
few squarefree numbers are 1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30, 31, 33, 34, 35,
37, 38, 39, …
Examples:
Input : n = 10
Output : Yes
10 can be factorized as 2*5. Since
no prime factor appears more than
once, it is a square free number.
Input : n = 20
Output : No
20 can be factorized as 2 * 2 * 5.
Since prime factor appears more than
once, it is not a square free number.
Q13:Write a program given an array of n integers sorted in ascending order, write a function that returns a
Fixed Point in the array, if there is any Fixed Point present in the array, else returns -1. Fixed Point in an
array is an index i such that arr[i] is equal to i. Note that integers in an array can be negative.
Examples:
Q14:Write a program to print all Sophie Germain number less than n. A prime number p is called a Sophie
prime number if 2p+1 is also a prime number. The number 2p+1 is called a safe prime. For example, 11 is a
prime number and 11*2 + 1 = 23 is also a prime number so, 11 is Sophie Germain prime number. The first
few Sophie German prime numbers are 2, 3, 5, 11, 23, 29, 41, 53, 83, 89, 113, 131, 173, 179 ..
Q15:Write a program given the value of n(n < 10), i.e, the number of lines, print the Fibonacci triangle.
13 21 34 55
89 144 233 377 610
Sample Input and Output-2:
Enter a number : 7
1
12
358
13 21 34 55
89 144 233 377 610
987 1597 2584 4181 6765 10946
17711 28657 46368 75025 121393 196418 317811
Q16:Write a program find maximum power of a number that divides a factorial given two numbers, fact
and n, find the largest power of n that divides fact! (Factorial of fact).
Examples:
Input : fact = 5, n = 2
Output : 3
Value of 5! is 120.
The largest power of 2 that divides 120 is 8 (or 2^3).
Q17:Write a program given an Array of Positive and Negative Integers, find out the Maximum Subarray Sum
in that Array.
Examples:
Page 203
Q18:Write a program given a number, the task is to toggle bits of a number except first and last bit.
Examples:
Input : 10
Output : 12
Binary representation : 1 0 1 0
After toggling first and last : 1 1 0 0
Input : 9
Output : 15
Binary representation : 1 0 0 1
After toggling first and last : 1 1 1 1
Q19:Write a program given a sequence, find the length of the longest palindromic sub-sequence in it.
Q20:Write a program given an array of positive integers of length n. Our task is to find minimum number of
operations to convert an array so that arr[i] % 4 is zero for each i. In each operation, we can take any two
elements from the array, remove both of them and put back their sum in the array.
Examples:
Input : arr = {2 , 2 , 2 , 3 , 3}
Page 204
Output : 3
Explanation: In 1st operation, we pick 2 and 2 and put their sum back to the array. In 2nd operation, we
pick 3 and 3 and do same for that.
Now in 3rd operation, we pick 6 and 2 so overall 3 operation are required.
Set-21
Q1:Write a program on Prime Triplet. Prime Triplet is a set of three prime numbers of the form (p, p+2, p+6)
or (p, p+4, p+6). This is the closest possible grouping of three prime numbers, since one of every three
sequential odd numbers is a multiple of three, and hence not prime (except for 3 itself) except (2, 3, 5) and
(3, 5, 7) .
Q2:Write a program given an Array of Integers and an Integer value k, find out k non-overlapping sub-arrays
which have k maximum sums.
Examples:
Input : arr1[] = {4, 1, 1, -1, -3, -5, 6, 2, -6, -2},
k = 3.
Output : Maximum non-overlapping sub-array sum1: 8,
starting index: 6, ending index: 7.
Q3:Write a program given a number N, task is to Check whether it is a permutable prime number or not.
Page 206
A Permutable prime number is that number which after switching the position of digits through any
permutation is also prime. Some of the permutable prime numbers are 2, 3, 5, 7, 11, etc.
Note : input most be 1 to 99. Otherwise invalid input
Examples :
Input : 31
Output : Yes
Explanation :
Both 13 and 31 are prime.
Input : 19
Output : No
Explanation :
19 is prime but 91 is not
Q4:Write a program for ‘n’ points in a plane out of which ‘m points are collinear. How many different
straight lines can form?
Examples:
Input : n = 3, m = 3
Output : 1
We can form only 1 distinct straight line
using 3 collinear points
Q5:Write a program given an array A positive integers, sort the array in ascending order such that element
in given subarray (start and end indexes are input) in unsorted array stay unmoved and all other elements
are sorted.
Examples:
Q6:Write a program We have an array of the form {a0, a1, a2….., an, b0, b1, b2, …..bn} and our task is to
rearrange the same in theform given below by using O(1) space-
{a0, b0, a1, b1, a2, b2………..an, bn}
Examples:
Q7:Write a program given an array of n integers, slope of a line i. e., m and the intercept of the line i.e c,
Count the number of ordered pairs(i, j) of points where i ≠ j, such that point (Ai, Aj) satisfies the line formed
with given slope and intercept.
Note : The equation of the line is y = mx + c, where m is the slope of the line and c is the intercept.
Examples :
Input : m = 1, c = 1, arr[] = [ 1, 2, 3, 4, 2 ]
Output : 5 ordered points
Explanation : The equation of the line with given slope and intercept is : y = x + 1.
The Number of pairs (i, j), for which (arri, arrj) satisfies the above equation of the line are : (1, 2), (1, 5), (2,
3), (3, 4), (5, 3).
Input : m = 2, c = 1, arr[] = [ 1, 2, 3, 4, 2, 5 ]
Output : 3 ordered points
Q8:Write a program given an array of N numbers. Find out the number of pairs i and j such that i < j and Ai
and Aj have atleast one digit common (For e.g. (11, 19) have 1 digit common but (36, 48) have no digit
common)
Examples:
Input : A[] = { 10, 12, 24 }
Output : 2
Page 209
Explanation: Two valid pairs are (10, 12) and (12, 24) which have atleast one digit common
Q9:Write a program given three arrays A, B and C, the task is to find sum of values of all special triplets. A
special triplet is defined as a triplet (X, Y, Z) where the condition :
X ≤ Y and Z ≤ Y always holds true. The value of each triplet (X, Y, Z) is given by:
f(X, Y, Z) = (X + Y) * (Y + Z)
Note: If a triplet is not ‘special’,
f(x, y, z) = 0 for that particular triplet.
Examples:
Input : A = {1, 4, 5}, B = {2, 3}, C = {2, 1, 3}
Output : 81
Explanation
The special triplets and their values are given below
Triplet f(x, y, z) = (x + y) * (y + z)
(1, 2, 2) (1 + 2) * (2 + 2) = 12
(1, 2, 1) (1 + 2) * (2 + 1) = 9
(1, 3, 2) (1 + 3) * (3 + 2) = 20
(1, 3, 1) (1 + 3) * (3 + 1) = 16
(1, 3, 3) (1 + 3) * (3 + 3) = 24
-------------------------------------
Sum = 81
Q10:Given an array of N integers, count number of even-odd subarrays. An even – odd subarray is a
subarray that contains the same number of even as well as odd integers.
Examples :
Input : arr[] = {2, 5, 7, 8}
Output : 3
Explanation : There are total 3 even-odd subarrays.
1) {2, 5}
2) {7, 8}
3) {2, 5, 7, 8}
Input : arr[] = {3, 4, 6, 8, 1, 10}
Output : 3
Explanation : In this case, 3 even-odd subarrays are:
1) {3, 4}
2) {8, 1}
3) {1, 10}
Q11:Write a program given pair of strings when concatenated is said to be a ‘Pan-digital Concatenation’ if
their concatenation consists of all digits from (0 – 9) in any order at least once.The task is, given N strings,
compute the number of pairs resulting in a ‘Pan-digital Concatenation’.
Examples:
Input : num[] = {"123567", "098234", "14765", "19804"}
Output : 3
The pairs, 1st and 2nd giving
(123567098234),1st and 4rd giving(12356719804) and
2nd and 3rd giving (09823414765),
on concatenation result in Pandigital Concatenations.
Page 211
Q12:Write a program given matrix is said to be singular if the determinant of the matrix is 0 otherwise it is
non-singular .
Examples:
Input : 0 0 0
456
123
Output : Yes
Determinant value of the matrix is
0 (Note first row is 0)
Input : 1 0 0
456
123
Output : No
Determinant value of the matrix is 3
(which is non-zero).
Q13:Write a program given N, we have to find the sum of products of all combination taken 1 to N at a
time. In simple words, we have to find the sum of products of all combination taken 1 at time, then 2 at a
time, then 3 at a time till N at a time.
If you think closely about the problem, a large value of N could result in producing a large number of
combinations.
Examples:
Input : N = 3
Output : f(1) = 6
f(2) = 11
f(3) = 6
Explanation: f(x) is sum of products of all
combination taken x at a time
1+2+3=6
f(2) = (1*2) + (1*3) + (2*3) = 11
f(3) = (1*2*3)
Input : N = 4
Output : f(1) = 10
f(2) = 35
f(3) = 50
f(4) = 24
Explanation: f(1) = 1 + 2 + 3 + 4 = 10
f(2) = (1*2) + (1*3) + (1*4) +
(2*3) + (2*4) + (3*4)
= 35
f(3) = (1*2*3) + (1*2*4) +(1*3*4) +
(2*3*4)
= 50
f(4) = (1*2*3*4) = 24
f(1) = 6
f(2) = 11
f(3) = 6
Q14:Write a program given a string, convert the string to palindrome without any modifications like adding
a character, removing a character, replacing a character etc.
Examples:
Input : "mdaam"
Output : "madam" or "amdma"
Input : "abb"
Output : "bab"
Input : "codetantra"
Output : "No Palindrome"
Q15:Write a program given any date according to the Gregorian Calendar, the task is to return the
day(Monday, Tuesday…etc) on that particular day.
Examples:
Input : Date: 13 7 2017
Output : 4 i.e Thursday
Input : Date: 15 8 2012
Output : 3 i.e Wednesday
Input : Date: 24 12 2456
Output : 0 i.e Sunday
Page 214
Note: Assume that the date given is always valid. So date validation need not be performed.
Q16:Write a program We have given a large number now we can easily find out the factorial of this large
number. programmers who need more precision than 64 bits.
Examples:
Input : 100
Output : 933262154439441526816992388562667004-
907159682643816214685929638952175999-
932299156089414639761565182862536979-
208272237582511852109168640000000000-
00000000000000
Input :50
Output : 3041409320171337804361260816606476884-
4377641568960512000000000000
Q17:Write a program given an integer n and an array of positions ‘position[]’ (1 <= position[i] <= 2n), find
the number of ways of proper bracket expressions that can be formed of length 2n such that given
positions have opening bracket. Examples :
[[[]]]
[[][]]
Q18:Write a program give a positive integer n, find modular multiplicative inverse of all integer from 1 to n
with respect to a big prime number, say, ‘prime’.
The modular multiplicative inverse of a is an integer ‘x’ such that.
a x ≡ 1 (mod prime)
Examples :
Input : n = 10, prime = 17
Output : 1 9 6 13 7 3 5 15 2 12
Explanation :
For 1, modular inverse is 1 as (1 * 1)%17 is 1
For 2, modular inverse is 9 as (2 * 9)%17 is 1
For 3, modular inverse is 6 as (3 * 6)%17 is 1
.......
Input : n = 5, prime = 7
Output : 1 4 5 2 3
Q19:Write a program given two numbers, the task is to use alternative bits within two numbers to create
result. We take first bits of second number, then second bit of the first number, third bit of second number
and take the fourth bit of a first number and so on and generate a number with it.
Examples :
Input : n = 10, m = 11
Output : 11
Start from right of second number
Binary representation of n = 1 0 1 0
^ ^
Binary representation of m = 1 0 1 1
^ ^
Output is =1011
Input : n = 20, m = 7
Output : 5
Start from right of second number
binary representation of n = 1 0 1 0 0
^ ^
binary representation of m = 0 0 1 1 1
^ ^ ^
Output is =00101
Q20:Write a program given the upper limit limit, print factorials of all Fibonacci Numbers smaller than limit.
Examples :
Input : limit = 20
Page 217
SET-22
Q1: Write a program given an array, write a program to reverse it using pointers .
Input : array = 2, 4, -6, 5, 8, -1
Output : reverse_array = -1, 8, 5, -6, 4, 2
No subsequence is divisible by 8.
Input : 3144
Output : No
The subsequence 344 is divisible by 8.
Input : n = 9, m = 5
Output : 20
Explanation:
Factorial of n = 1 * 2 * 3 *4 * 5 * 6 * 7 * 8
* 9 = 362880
Factorial of m = 1 * 2 * 3 * 4 * 5 = 120
GCD(362880, 120) = 120
Enter a number : 10
Enter the array size : 4
Enter array 4 elements : 1 2 3 4
11
Q7: Write a program given an array of N non-negative integers, task is to find the maximum size of a
subarray such that the pairwise sum of the elements of this subarray is not divisible by a given integer, K.
Also, print this subarray as well. If there are two or more subarrays which follow the above stated
condition, then print the first one from the left.
Examples :
Input : N = 5, M = 3
C1 = 1 3, C2 = 4 5, C3 = 1 4
Output : Resultant array = {0, 0, 0, 0, 1}
Page 221
Explanation :
Initial array : {0, 0, 0, 0, 0}
After first toggle : {1, 1, 1, 0, 0}
After second toggle : {1, 1, 1, 1, 1}
After third toggle : {0, 0, 0, 0, 1}
Input : N = 5, M = 5
C1 = 1 5, C2 = 1 5, C3 = 1 5,
C4 = 1 5, C5 = 1 5
Output : Resultant array = {1, 1, 1, 1, 1}
Input : 56
Output : 56 is lychrel : false
Explanation : 56 becomes palindromic after one iteration :
56 + 65 = 121
Input : 196
Output : 196 is lychrel : true
Explanation : 196 becomes palindromic after 19 iterations :
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
....
16403234045 + 54043230461
70446464506 + 60546464407
If such a match for n characters is not found, the function should return the original str.
For example:
removePrefixAndSuffix("sysABCsys", 3) should return "ABC"
Q13: Fill in the missing code in the function char* removePrefix(char* str, int n), such that if the
String str has the same n characters as prefix and suffix, then return a string with characters of strafter
removing the prefix.
If such a match for n characters is not found, the function should return the original str.
For example:
removePrefix("sysABCsys", 3) should return "ABCsys"
If such a match for n characters is not found, the function should return the original str.
For example:
removeMiddle("sysABCsys", 3) should return "syssys"
Any multiple of 4 is a leap year, as long as it is not divisible by 100. But when it is divisible by 100, it
becomes a leap year only if it is also divisible by 400. All years which are not leap years are called common
years. Function int common(int year) accepts any positive integer value for year and returns 0 if it is leap
and 1 if it is common.
For example:
common(2001) should return 1
A research experiment conducted recently tried to predict the quality of friendship between any two
people based on their year of birth. Function int friendshipQuality(int year1, int year2) takes two positive
integers as parameters and returns an integer value for friendship quality as follows:
1. If year1 and year2 are both leap years, then the friendship quality is equal to the bigger of the two
numbers divided by 4.
Page 224
2. If the two passed years are both common, then the friendship quality is the absolute value of the
difference between the two, multiplied by 100.
3. If one of them is leap and the other is common, then the friendship quality is the smaller of the two
numbers.
For example:
friendshipQuality(2000, 2004) should return 501
Any multiple of 4 is a leap year, as long as it is not divisible by 100. But when it is divisible by 100, it
becomes a leap year only if it is also divisible by 400. All years which are not leap years are called common
years. Function int common(int year) accepts any positive integer value for year and returns 0 if it is leap
and 1 if it is common.
For example:
common(2001) should return 1
A research experiment conducted recently tried to predict the quality of friendship between any two
people based on their year of birth. Function int friendshipQuality(int year1, int year2) takes two positive
integers as parameters and returns an integer value for friendship quality as follows:
1. If year1 and year2 are both leap years, then the friendship quality is equal to the bigger of the two
numbers divided by 4.
2. If the two passed years are both common, then the friendship quality is the absolute value of the
difference between the two, multiplied by 100.
3. If one of them is leap and the other is common, then the friendship quality is the smaller of the two
numbers.
For example:
friendshipQuality(2000, 2004) should return 501
Page 225
Write a program to find the smallest number that is missing from the array.
Examples:
Input: {0, 1, 2, 6, 9}
Output: 3
Input: {4, 5, 10, 11}
Output: 0
Input: {0, 1, 2, 3}
Output: 4
Input: {0, 1, 2, 3, 4, 5, 6, 7, 10}
Output: 8
Input and Output Format:
The first line of the input consists of an integer, n that corresponds to the number of elements in
the input array.
The next 'n' lines in the input corresponding to the elements in the array.
Output is an integer.
Sample Input and Output:
Enter size : 5
Enter 5 elements : 0 1 3 4 5
2Problem Solving
Q17: In cricket tournament, the winner of a match is awarded 3 points and the loser 0 points.
In case of a tie, both teams are awarded 1 point each.
You had been given the number of wins for each team in the tournament, and the number of ties for each
team in the tournament.
Your job is to calculate the maximum points a team in the tournament has.
Example:
There are 6 teams in a tournament and
no. of wins of 1st team= 12
no. of wins of 2nd team= 45
no. of wins of 3rd team= 20
no. of wins of 4th team= 17
no. of wins of 5th team= 48
Page 226
For example, if we have two sets A = {1,2,3,4,5} and B = {3,4,5,6,7,8}, then the symmetric difference of A
and B is the set {1,2,6,7,8}.
Given two sets of positive integers, Write a program to display their symmetric difference.
Input Format:
Both sets will be input from a single line.
A zero (0) marks the end of each set.
There will be no more than 20 numbers in each set, and no number within a set will be repeated.
Each number in a set is a positive integer less than 65535.
Output Format:
The set of integers making up the symmetric difference of the two sets.
The numbers within a set may appear in the same order as in the input. (set 1 first and then set 2)
Sample Input and Output - 1:
Enter size : 8
Enter elements
12302460
The symmetric difference is : 1 3 4 6
Sample Input and Output - 2:
Enter size : 10
Enter elements
1357024351
Invalid set of input
Page 227
Write a program to find the row with the minimum number of 1's.
Input Format:
The first line of the input consists of an integer, r that corresponds to the number of rows in the
matrix.
The next line of the input consists of an integer, c that corresponds to the number of columns in
the matrix.
The next 'm*n' lines in the input corresponds to the elements in the matrix.
Output Format:
Output is an integer.
Refer sample input and output for formatting details.
Sample Input and Output:
Enter the number of rows and columns : 3 4
Enter matrix elements : 1 0 0 0 1 1 0 0 1 1 1 0
The given matrix is
1000
1100
1110
Row with min count of 1's : 0
Set 23
Q1. Mahirl had gone for a magic show last evening along with Sam, her uncle and she was quite thrilled to
see the various magic tricks.
After she came home, she was pestering her uncle to do some magic trick. Her uncle decided to show her –
“Finding the Rose” trick.
In this magic game, there are 'N' identical cups placed upside down.
The cups are numbered 1 to N. A red rose is initially kept under the Kth cup.
He would then swap pairs of cups and challenges Mahirl to find where the rose has gone.
Due to his high hand speed, no one is able to guess correctly which cup the rose is under.
However, using a high-speed camera you have managed to capture each of his cup-swaps.
Given the number of cups, the initial position of the rose and the list of swaps, write a program to
determine the final position of the rose.
Page 228
Write a C program to determine whether the given matrix is row dominant or not.
Function Specification:
int ** readMatrix(int rows, int cols)
void displayMatrix(int ** a, int rows, int cols)
int findRowDominantMatrix(int ** a, int rows, int cols)
findRowDominantMatrix - should return 1 if "Row Dominant", else return 0;
Input Format:
Input consists of (m*n)+2 integers.
The first integer corresponds to m, the number of rows in the matrix.
The second integer corresponds to n, the number of columns in the matrix.
The next 'n' integers correspond to the elements in the first row of the matrix.
The next 'n' integers correspond to the elements in the second row of the matrix and so on.
Output Format:
Refer Sample Output for formatting details.
Page 229
Write a program to find the row with the maximum number of 1's.
Input Format:
The first line of the input consists of an integer, r that corresponds to the number of rows in the
matrix.
The next line of the input consists of an integer, c that corresponds to the number of columns in
the matrix.
The next 'm*n' lines in the input corresponds to the elements in the matrix.
Output Format:
Output is an integer.
Refer sample input and output for formatting details.
Sample Input and Output:
Enter the number of rows and columns : 3 3
Enter matrix elements : 1 0 0 1 1 0 1 1 1
The given matrix is
100
110
111
Row with max count of 1's : 2
Q4. Write a C program to find the type of square matrix using functions:
a) Fn. findSymmetric which returns 1 if the matrix is symmetric and 0 if the matrix is not symmetric.
b) Fn. findIdentity which returns 1 if the matrix is an identity matrix and 0 if the matrix is not an identity
matrix.
c) Fn. findMagic which returns 1 if the matrix is a magic square and 0 if the matrix is not a magic square.
Page 230
A Magic Square is a square matrix in which the sum of the elements in each row and column is the
same.
d) Fn. findUpperTriangular which returns 1 if the matrix is an upper diagonal matrix and 0 if it is not.
An upper triangular matrix is one in which all the elements below the diagonal are equal to 0.
e) Fn. findLowerTriangular which returns 1 if the matrix is a lower diagonal matrix and 0 if it is not.
A lower triangular matrix is one in which all the elements above the diagonal are equal to 0.
f) Fn. findEvenTrace which returns 1 if the sum of the diagonal (L->R) elements of the matrix is even and 0
otherwise.
g) Fn. findNonzero which returns 1 if the all the elements in the matrix are nonzero and 0 otherwise.
h) Fn. findSpecial which returns 1 if the integer n (n corresponds to the number of rows / columns of the
matrix) is present in the matrix and 0 otherwise.
i) Fn. findSpecialTrace which returns 1 if the sum of the L-> R diagonal elements of the matrix is the same as
the sum of the R->L diagonal elements of the matrix and 0 otherwise.
j) Fn. findLucky which returns 1 if all the elements in the matrix are divisible by the number of
rows/columns in the matrix and 0 otherwise.
Use dynamic allocation of memory. (i.e use malloc()). Use functions for reading and displaying a matrix.
Input Format:
Input consists of (n*n)+1 integers.
The first integer corresponds to n, the number of rows/columns in the matrix.
The next 'n' integers correspond to the elements in the first row of the matrix.
The next 'n' integers correspond to the elements in the second row of the matrix and so on.
Output Format:
Refer Sample Output for formatting details.
Q5. Given a sorted array of n integers where each integer is in the range from 0 to n - 1.
Write a program to find the smallest number that is missing from the array.
Examples:
Input: {0, 1, 2, 6, 9}
Output: 3
Input: {4, 5, 10, 11}
Output: 0
Input: {0, 1, 2, 3}
Output: 4
Input: {0, 1, 2, 3, 4, 5, 6, 7, 10}
Output: 8
Input and Output Format:
The first line of the input consists of an integer, n that corresponds to the number of elements in
the input array.
The next 'n' lines in the input corresponding to the elements in the array.
Output is an integer.
Sample Input and Output:
Enter size : 5
Enter 5 elements : 0 1 3 4 5
2
Q6. Given an array arr[ ] of n integers, Write a program to construct a product array prod[ ] of same size
such that prod[i] is equal to the product of all the elements of arr[ ] except arr[i].
Example:
arr[ ] = {10, 3, 5, 6, 2}
prod[ ] = {180, 600, 360, 300, 900}
Input and Output Format:
The first line of the input consists of an integer, n that corresponds to the number of elements in
the input array arr[ ].
The next 'n' lines in the input correspond to the elements in the array.
Output is an array of integers.
Sample Input and Output - 1:
Enter size : 3
Enter 3 elements : 2 4 6
24 12 8
Sample Input and Output - 2:
Enter size : 1
Enter 1 elements : 15
-1
Q7. Write a C program to reverse a string without using library functions and using pointers.
Sample Input and Output:
Enter a string : Hindustan
Reverse of the string : natsudniH
Page 232
Write a program to find the row with the minimum number of 1's.
Input Format:
The first line of the input consists of an integer, r that corresponds to the number of rows in the
matrix.
The next line of the input consists of an integer, c that corresponds to the number of columns in
the matrix.
The next 'm*n' lines in the input corresponds to the elements in the matrix.
Output Format:
Output is an integer.
Refer sample input and output for formatting details.
Sample Input and Output:
Enter the number of rows and columns : 3 4
Enter matrix elements : 1 0 0 0 1 1 0 0 1 1 1 0
The given matrix is
1000
1100
1110
Row with min count of 1's : 0
Q9. Mahirl's uncle Sam was teaching her addition.
Sam wanted to test Mahirl's addition skills. Instead of giving her boring notebook exercises, he designed an
activity.
1. Sam gave Mahirl 'n' hats and asked her to arrange them into a line.
2. Then Sam gave a red marker to Mahirl and asked her to write a positive integer onto each hat.
3. Then Sam gave her a blue marker and asked her to write another positive integer onto each hat.
For each hat, the blue number is either the prefix sum or the suffix sum of all red numbers up to and
including that hat.
After Mahirl has completed the 3 steps described above, Sam wanted to check whether she has done the
task correctly.
Can you please help Sam?
Input Format:
The first line of the input consists of an integer, n that corresponds to the number of hats.
The integers in the next 'n' lines of the input correspond to the numbers written in n hats in red
color in order.
The integers in the next 'n' lines of the input correspond to the numbers written in n hats in blue
color in order.
Output Format:
Print “Correct” if Mahirl has completed the task correctly.
Print “Incorrect” if Mahirl has not done the task completely.
If Mahirl has done the task correctly, print a string of length n in the second line of the output to
indicate whether Mahirl has done a suffix operation or prefix operation on each hat.
The character 'S' in the string corresponds to Suffix operation and the character 'P' corresponds to
Prefix operation and the character 'E' corresponds to either prefix or suffix operation.
Output format:
Output should display the same input using pointer.
Sample Input and Output:
Enter an integer value : 99
Value pointed by ptr = 99
Q12. Dynamic memory allocation is the process of allocating memory during runtime of a program.
Here write a program to find the minimum and maximum elements in an array of 'n' elements which is
created dynamically.
Get the value of 'n' from the user and store the following n values in the array after allocating memory.
Use the following functions to find maximum and minimum elements in the array.
int min(int *, int ) -- where the arguments are the array and number of elements respectively and return
the minimum element.
int max(int *a, int n) -- where the arguments are the array and number of elements respectively and return
the maximum element.
Sample Input and Output:
Enter size : 6
Enter elements : 1 5 3 6 8 5
Minimum value : 1
Maximum value : 8
Q13. Problem Solving
Write a C program define a float variable f, a pointer to f as pf1 and a pointer to pf1 as pf2 (two level
pointer).
SET 24
Q1 Problem Solving
Write a program to find which car gives the highest mileage.
Struct Car {
float startKm;
float endKm;
float litre;
};
Declare two objects of car - audia4, fordfigo
Sample Input and Output:
Enter the startKm, endKm, fuel used of audia4 : 2.3 15.6 1.9
Enter the startKm, endKm, fuel used of fordfigo : 5 23 2.5
Mileage of audia4 : 7.000000 km/lt
Mileage of fordfigo : 7.200000 km/lt
Mileage of fordfigo is more than audia4
Note: Do use the printf() function with a newline character (\n) at the end.
Q2
Create a structure called Student.
struct Student {
char name[30];
char department[20];
int yearOfStudy;
float cgpa;
};
Write a program to get the details of n students and to display their details, sorted in ascending order based
on name.
Input and Output Format:
Refer sample input and output for formatting specification.
All float values are displayed correct to 2 decimal places.
Note: Do use the printf() function with a newline character (\n) at the end.
Q3
Find the time taken to bake a cake for a cooking competition.Enter the starting time and ending time. Use
the following structure.
struct Time {
int hours;
int minutes;
int seconds;
};
Sample Input and Output:
Enter first time in HH:MM:SS : 3:59:59
Page 237
Note: Do use the printf() function with a newline character (\n) at the end.
Q4
Write a menu driven program to find the area of the following shapes. Use the structures and use PI value
as 3.14.
struct Rectangle {
int length;
int breadth;
int area;
};
struct Circle {
int radius;
float area;
};
struct Triangle {
float base;
float height;
float area;
};
Note: Do use the printf() function with a newline character (\n) at the end.
Q5
Define a Student union as shown below:
union Student{
int rollNo;
int age;
Page 238
char gender;
};
Q6
Define a Student union as shown below:
union Student {
int rollNo;
float cgpa;
char gender;
}
First get the number of students from the user and get their cgpa. Print all the details of the student and
check what is being printed.
Sample Input and Output:
Page 239
Q7
Create a student record for three students, get their details from user and find the student with the highest
average marks.
Q8
Define a Employee union as shown below:
union Employee{
char name[32];
int workerNo;
};
Write a program to illustrate the working of union. Get the name and worker id of an employee and print the
same and check what is being printed.
Sample Input and Output:
Enter name : Shiva
Enter worker number : 123
Job Details : Name = { WorkerNo = 123
Q9
Define a Student union as shown below:
union Student {
int rollNo;
int age;
char gender;
};
Student-1 Age : 49
The content of the student union is
Student-1 : Roll no = 49 Age = 49 Gender = 1
Student-1 gender : F
The content of the student union is
Student-1 : Roll no = 70 Age = 70 Gender = F
Q10
Write a program to to read a book details and print them using structures and functions.
Sample Input and Output:
Enter book name : LetUsC
Enter book price : 250
Enter book pages : 320
Name : LetUsC Price : 250.000000 Pages : 320
Q11
Write a program to find which car gives the highest mileage.
Struct Car {
float startKm;
float endKm;
float litre;
};
Declare two objects of car - audia4, fordfigo
Sample Input and Output:
Enter the startKm, endKm, fuel used of audia4 : 2.3 15.6 1.9
Enter the startKm, endKm, fuel used of fordfigo : 5 23 2.5
Mileage of audia4 : 7.000000 km/lt
Mileage of fordfigo : 7.200000 km/lt
Mileage of fordfigo is more than audia4
Q12
Write a program to display the product details of iPhone in Flipkart by using the following structure
struct Phone {
int emino;
char name[30];
Page 242
char color[30];
int modelno;
};
Sample Input and Output:
Enter the emino : 112233
Enter the name : iPhone
Enter the colour : Blue
Enter the model : 8
The Details are
Emi number : 112233
Name : iPhone
Colour : Blue
Model No : 8
Q13
Find the time taken to bake a cake for a cooking competition.Enter the starting time and ending time. Use
the following structure.
struct Time {
int hours;
int minutes;
int seconds;
};
Sample Input and Output:
Enter first time in HH:MM:SS : 3:59:59
Enter second time in HH:MM:SS : 4:0:1
Time difference is : 00:00:02
Q14
Write a menu driven program to find the area of the following shapes. Use the structures and use PI value
as 3.14.
struct Rectangle {
int length;
int breadth;
int area;
};
Page 243
struct Circle {
int radius;
float area;
};
struct Triangle {
float base;
float height;
float area;
};
Q15
Create a student record for three students, get their details from user and find the student with the highest
average marks.
Marks of 5 subjects : 55 66 43 57 68
Rollno : 3
Name : Kedar
Marks of 5 subjects : 54 55 67 68 64
Student Details
Name : Kedar
RollNo : 3
Total : 308
Average : 61.60
Q16
SUM OF NON-EDGES :
A set of numbers forming a matrix N*N is passes as input. The program has to print the sum of numbers
which are not along the edges.
Input Format:
The first line will contain the value of N
The next lines will contain N numbers each separated by one or more spaces
Boundary Conditions:
3<=N<=10
Value of a given number in the matrix is from 0 to 99999999
Output Format:
The sum of the numbers which are not along the edges.
Example Input / Output 1:
Input:
3
567
891
234
Output:
9
Explanation:
All numbers except 9 are along the edges. Hence the sum is 9 which is printed as output.
Q17
LUCKY NUMBER :
A number is considered lucky if it contains either 3 or 4 or 3 and 4 both in it. Write a program to print the nth
lucky number. Example, 1st lucky number is 3, and 2nd lucky number is 4 and 3rd lucky number is 33 and
4th lucky number is 34 and so on. Note that 13, 40 etc., are not lucky as they have other numbers in it.
The program should accept a number 'n' as input and display the nth lucky number as output.
Sample Input 1:
3
Sample Output 1:
33
Explanation:
Here the lucky numbers are 3, 4, 33, 34., and the 3rd lucky number is 33.
Sample Input 2:
34
Sample Output 2:
33344
Note: Do use the printf() with '\n' at the end.
Q18
• The expression 1/2+1/6 evaluates to 4/6, which we reduce to the string 2/3.
• The expression 7/10+13/10 evaluates to 20/10, which we reduce to the string 2/1.
Constraints :
• 1 ≤ n ≤ 500
• 1 ≤ a, b, c, d ≤ 2000
Output Format :
Return an array of strings where each index i contains the fully reduced form of the fraction that resulted
from evaluating expressionsi.
Sample Case 0
Sample Input
5
722 / 148 + 360 / 176
978 /1212 +183 / 183
358 / 472 + 301 / 417
780 / 309 + 684 / 988
258 / 840 + 854 / 686
Sample Output
2818 / 407
365 / 202
145679 / 98412
4307 / 1339
1521 / 980
Explanation
We perform the following n = 5 calculations:
1. 722 / 148 + 360 / 176 evaluates to the reduced fraction 2818 / 407.
2. 978 / 1212 + 183 / 183 evaluates to the reduced fraction 365 / 202.
3. 358 / 472 + 301 / 417 evaluates to the reduced fraction 145679 / 98412.
4. 780 / 309 + 684 / 988 evaluates to the reduced fraction 4307 / 1339.
5. 258 / 840 + 854 / 686 evaluates to the reduced fraction 1521 / 980.
Thus, we return the array ["2818/407", "365/202", "145679/98412", "4307/1339", "1521/980"] as our answer.
Note: Do use the printf() with '\n' at the end.
Q19
PSYCHOMETRIC TESTING :
Psychometric testing is designed to find job-relevant information about an applicant that the traditional
interview process wouldn't otherwise uncover. It typically includes a combination of online aptitude and
personality tests that measure cognitive ability and personality traits.
Page 247
A company has psychometric scores for n candidates, and it will only extend job offers to candidates with
scores in the inclusive range given by [lowerLimit, upperLimit]. Given the list of scores and a sequence of
score ranges, determine how many candidates the company will extend offers to for each range of scores.
Complete the program, it has:
The program must return an array of q integers where the value at each index i denotes the number of
candidates in the inclusive range [lowerLimitsi, upperLimitsi] that the company will extend offers to.
Input Format :
The program reads the following input from stdin:
The first line contains an integer, n, denoting the number of elements in scores.
Each line j of the n subsequent lines (where 0 ≤ j < n) contains an integer describing scoresj.
The next line contains an integer, q, denoting the number of queries.
Each line i of the q subsequent lines (where 0 ≤ i < q) contains an integer describing lowerLimitsi.
The next line contains an integer, q, denoting the number of queries.
Each line i of the q subsequent lines (where 0 ≤ i < q) contains an integer describing upperLimitsi.
Constraints :
• 1 ≤ n ≤ 105
• 1 ≤ scoresj ≤ 109
• 1 ≤ q ≤ 105
• 1 ≤ lowerLimitsi ≤ upperLimitsi ≤ 109
Output Format :
The function must return an array of q integers where the value at each index i denotes the number of
candidates in the inclusive range [lowerLimitsi, upperLimitsi] that the company will extend offers to.
Sample Input :
5
1
3
5
6
8
1
2
1
Page 248
6
Sample Output :
3
Explanation :
Given scores = [1, 3, 5, 6, 8], lowerLimits = [2], and upperLimits = [6], we perform the following q = 1 query:
1. Find all the scores in the inclusive range [2, 6]: there are three such candidates (i.e., scores 3, 5,
and 6), so we store 3 in index 0 of our return array.
ZOMBIE CLUSTERS :
There are n zombies in Seattle, and Liv and Ravi are trying to track them down to find out who is creating
new zombies — thus preventing an apocalypse. Other than the patient-zero zombies (who became so by
mixing MaxRager and tainted Utopium), new people only become zombies after being scratched by an
existing zombie; for this reason, zombiism is transitive. This means that if zombie 0 knows zombie 1 and
zombie 1 knows zombie 2, then zombie 0 is connected to zombie 2. A zombie cluster is a group of zombies
who are directly or indirectly linked through the other zombies they know (such as the one who scratched
them or supplies them with brains).
Complete the program, it has an array of binary strings (i.e., composed of 0s and 1s) named zombies that
describes an n × n matrix of known connected zombies; if zombies[i][j] = 0, then the ith and jth zombies do
not know one another (otherwise, the cell contains a 1 and they do know one another).
Your program must return an integer denoting the number of zombie clusters Liv and Ravi have identified in
Seattle.
Input Format :
Read the following input from stdin and passes it to your function:
The first line contains an integer, n, describing the base size of your zombie association matrix. Each of
the n subsequent lines contains a binary string of length n describing a row in the matrix.
Constraints :
• 1 ≤ n ≤ 300
• 0≤i<n
• |zombies| = n
• Each zombies[i] contains a binary string of n zeroes and ones.
• zombies[i][i] = 1, where 0 ≤ i < n.
• zombies[i][j] = zombies[j][i], where 0 ≤ i < j < n.
Output Format :
Your program must return a single integer denoting the number of different zombie clusters in Seattle. This
is printed to stdout by the locked stub code in your editor.
Sample Input 0
4
Page 249
1100
1110
0110
0001
Sample Output 0
2
Sample Input 1
5
10000
01000
00100
00010
00001
Sample Output 1
5
Explanation :
In the diagrams below, the squares highlighting a known connection between two different zombies are
highlighted in green. Because each zombie is already aware that they are personally a zombie, those are
highlighted in grey.
Sample Case 0:
We have n = 4 zombies numbered Z0 through Z3. There are 2 pairs of zombies who directly know each
another: (Z0, Z1) and (Z1, Z2). Because of zombiism's transitive property, the set of zombies {Z0, Z1, Z2} is
considered to be a single zombie cluster. The remaining zombie, Z3, doesn't know any other zombies and is
considered to be his own, separate zombie cluster ({Z3}). This gives us a total of 2zombie clusters, so we
print 2 on a new line.
Sample Case 1:
Page 250
No zombie knows who any other zombie is, so they each form their own zombie clusters: {Z0}, {Z1}, {Z2}, {Z3},
and {Z4}. This means we have 5 zombie clusters, so we print 5 on a new line.
Note: Do use the printf() with '\n' at the end.
Set 25
2. The rearranged sentence must be formatted to satisfy the regular expression ^[A-Z][a-z ]*\.$ (i.e.,
start with a capital letter, followed by lowercase letters and spaces, and terminated by a period).
3. If two or more words have equal length, they must appear in the same order as in the original
sentence. For example, Cats and hats. would become And cats hats.
Complete the program:
Name : sentence
Type : string
Description : A string of space-separated words satisfying the regular expression ^[A-Z][a-z ]*\.$.
Return a string denoting the rearranged sentence satisfying the criteria above.
Input Format : A single line of space-separated words denoting sentence.
Constraints
• 1 ≤ length of sentence < 105
• It is guaranteed that sentence satisfies the regular expression ^[A-Z][a-z ]*\.$.
Output Format : Return a string denoting the sorted sentence according to length.
Sample Input 0
The lines are printed in reverse order.
Sample Output 0
In the are lines order printed reverse.
Explanation 0
We organize the strings of each respective length in sentence = The lines are printed in reverse order. as:
• Length 2: {in}
• Length 3: {the, are}
• Length 5: {lines, order}
• Length 7: {printed, reverse}
We then reassemble our sequences of words as a sentence string, ensuring that the first letter is uppercase,
the intermediate letters are lowercase, and the string terminates with a period. Thus, we return In the are
lines order printed reverse. as our answer.
Sample Input 1
Here i come.
Sample Output 1
I here come.
Explanation 1
We organize the strings of each respective length in sentence = Here i come. as:
• Length 1: {i}
• Length 4: {here, come}
We then reassemble our sequences of words as a sentence string, ensuring that the first letter is uppercase,
the intermediate letters are lowercase, and the string terminates with a period. Thus, we return I here
come. as our answer.
Sample Input 2
I love to code.
Sample Output 1
I to love code.
Explanation 1
We organize the strings of each respective length in sentence = I love to code. as:
• Length 1: {i}
• Length 2: {to}
• Length 4: {love, code}
Page 253
We then reassemble our sequences of words as a sentence string, ensuring that the first letter is uppercase,
the intermediate letters are lowercase, and the string terminates with a period. Thus, we return I to love
code. as our answer.
Note: Do use the printf() with '\n' at the end.
Q6. SHARING CANDIES:
Jamie has n candies. She is willing to share m of them with Mark, where m is the pth smallest factor
of n (i.e., the pth smallest long integer to divide n with no remainder). For example, the factors of n =
8 are {1, 2, 4, 8}; if p = 3, then Jamie shares m = 4 candies with Mark.
Complete the program, it has:
Name : n
Type : long integer
Description : The number of candies Jamie has.
Name : p
Type : long integer
Description : Used to determine the pth smallest factor of n.
The program must return a long integer denoting m (i.e., the number of candies Jamie gives Mark). If
no pth smallest factor exists, return 0 instead.
Input Format : The first line contains a long integer denoting n. The second line contains a long integer
denoting p.
Constraints : 1 ≤ n ≤ 1015 1 ≤ p ≤ 109
Output Format : Return a long integer denoting m (i.e., the number of candies Jamie gives Mark). If
no pth smallest factor exists, return 0 instead.
Sample Input 0
10
3
Sample Output 0
5
Explanation 0
Jamie has n = 10 candies, and the factors of n are {1, 2, 5, 10}. We then return the p = 3rd smallest factor,
which is 5, as our answer.
Sample Input 1
10
5
Sample Output 1
0
Explanation 1
Jamie has n = 10 candies, and the factors of n are {1, 2, 5, 10}. We want to find the p = 5th smallest factor
of n, but there are only four factors. Thus, we return 0 as our answer.
Sample Input 2
1
1
Sample Output 2
1
Explanation 2
Jamie has n = 1 candies, and the only factor of n is 1. We then return the p = 1st smallest factor, which is 1,
as our answer.
Note: Do use the printf() with '\n' at the end.
Page 254
Q7. DATE:
Write a program to find the number of days between two given dates (date/month/year) with maximum
accuracy. DO NOT USE INBUILT FUNCTIONS.
You should consider the leap year and accurate number of days in each month (30 or 31).
TestCase-1
Input:
07/05/2016
09/05/2016
Output:
2
TestCase 2
Input:
09/01/2015
09/05/2016
Output:
486
Note: Do use the printf() with '\n' at the end.
Q8. You are designing a poster which prints out numbers with a unique style applied to each of them. The
styling is based on the number of closed paths or holes present in a given number.
The number of holes that each of the digits from 0 to 9 have are equal to the number of closed paths in the
digit. Their values are:
1, 2, 3, 5, and 7 = 0 holes.
0, 4, 6, and 9 = 1 hole.
8 = 2 holes.
Given a number, you must determine the sum of the number of holes for all of its digits. For example, the
number 819 has 3 holes.
Complete the program, it must must return an integer denoting the total number of holes in num.
Input Format
Input from stdin will be processed:
There is one line of text containing a single integer num, the value to process.
Constraints
1 ≤num≤ 109
Output Format
A single line containing the number of holes in the given number followed by a newline (\n) character
Sample Case 0
Sample Input
630
Sample Output
2
Explanation
Add the holes count for each digit, 6, 3 and 0. Return 1 + 0 + 1 = 2.
Sample Case 1
Sample Input
1288
Sample Output
4
Page 255
Explanation
Add the holes count for each digit, 1, 2, 8, 8. Return 0 + 0 + 2 + 2 = 4.
Q9. Amit is working in a company such that he has to travel to some restaurant every day which is at N
meters distance from his home. Amit has two choices, either to take the restaurant's taxi (where he wants
to visit) or he can walk to the restaurant. Whenever he walks, he walks with a velocity of V 1m/s. The taxi, on
the other hand, moves with a velocity of V2m/s. Whenever he calls for the taxi, the taxi first travels a
distance of N meters from the restaurant to his home and then from home, it travels back to the
restaurant.
The taxi crosses a total distance of N meters while going from home to the restaurant, on the other hand,
he has to cover a distance of sqrt(2)*N (because of some staircases) when he walks.
Write a program to help Amit to decide whether he should use the taxi or he should walk so that his travel
time is minimized.
Input Format:
Three space-separated integers N, V1, V2 in a single line.
Constraints:
1 <= N, V1, V2<= 100
Output Format:
Output a string either "Taxi" or "Walk" depending on the inputs followed by a newline (\n) character.
Sample case 0:
Sample Input:
2 10 14
Sample Output:
Walk
Sample case 1:
Sample Input:
343 56 112
Sample Output:
Taxi
Q10. Given a value X, you want to have change for this amount X. You are provided with the infinite supply
of each of the denominations in Indian Currency i.e. you have the infinite supply of these notes/coins {1, 2,
5, 10, 20, 50, 100, 500, 1000}. Your task is to find the minimum number of coins/notes needed to make the
change. Write your program in C.
Input:
Integer X.
Output:
In a single line, output the required coins/notes denominations, in non-increasing order, separated by
space.
Constraints:
1 <= X <= 105
Sample case 0:
Sample input 0:
70
Sample output 0:
50 20
Explanation:
Page 256
You need a 50 rupees and a 20 rupees note. This is the minimum you can get.
Sample case 1:
Sample input 1:
447
Sample output 1:
100 100 100 100 20 20 5 2
Q11. Gandalf has challenged his old friend and new enemy Merlin to a duel at a place of Merlin's choosing.
Merlin decides the best place to be is behind a lot of minor wizards that Gandalf will have to fight first. As
each minor wizard is encountered, he will fight and lose power. Along the path, he also may find power
packs. Given that his power must never drop below 1, what is the minimum power he must start out with
so he can get to the duel?
For example, his path is described as p = [-2, 3, 1, -5] where a negative number represents an opponent and
a positive value is a power pack. When he fights an opponent, his power drops by the absolute value of the
opponent's value. When he picks up a power pack, his power is boosted by the value. The following shows
Gandalf's energy level if he starts with 4 units of power.Gandalf's Enemy<br>-----------------------</td>
Power or boost<br>
Gandalf's Enemy Power or boost
--------------- --------------
4 -2
2 3
5 1
6 -5
1
Complete the program, it must return the minimum integer energy value Gandalf needs when he starts out.
It has: p[0],...p[n-1]: an array of integers
Constraints
1 ≤ n ≤ 105
−100 ≤ p[i] ≤ 100
Input Format:
The first line contains an integer n, the size of the array p.
Each of the next n lines contains an integer p[i].
Sample Case 0
Sample Input 0
10
-5
4
-2
3
1
-1
-6
-1
0
5
Sample Output 0
Page 257
8
Explanation 0
Gandalf's Enemy Power or boost
--------------- --------------
8 -5
3 4
7 -2
5 3
8 1
9 -1
8 -6
2 -1
1 0
1 5
6
Gandalf's minimum power level is 1.
Sample Case 1
Sample Input 1
5
-5
4
-2
3
1
Sample Output 1
6
Explanation 1
Gandalf's Enemy Power or boost
--------------- --------------
6 -5
1 4
5 -2
3 3
4 1
5
Sample Case 2
Sample Input 2
10
-5
4
-2
3
1
-1
-6
Page 258
-1
0
-5
Sample Output 2
13
Explanation 2
Gandalf's Enemy Power or boost
--------------- --------------
13 -5
8 4
12 -2
10 3
13 1
14 -1
13 -6
7 -1
6 0
6 -5
1
Q12. One day Ajit got a strange feeling of jumping from one point to another on a number line (containing
positive integers). The jumping from one point to another can only be done in one dimension. He will start
from point 0 from which he will do a lot of jumps. He can only jump in a specific sequence: 1-jump, 2-jump,
3-jump, 1jump, 2-jump, 3-jump, 1-jump, and so on. (1->2->3->1->2->3->1...) 1-jump means that if Ajit is at
point x on the number line, he will jump to the point x+1. 2-jump means that id Ajit is at point x on the
number line, he will jump to the point x+2. 3-jump means that id Ajit is at point x on the number line, he
will jump to the point x+3.
Write a program which given the input point a outputs whether Ajit can reach this point a after some
number of jumps or not.
Input:
The first line contains a single integer a denoting the point Ajit asks about.
Output:
Output "YES" without a quotes if Ajit can arrive at point a or "NO" without a quotes otherwise.
Sample Case 0:
Sample Input:
3
Sample Output:
YES
Sample Explanation - 1
He can take jump sequence (1¬>2) to reach point 3.Input:
Output:
Sample Input:
2
Sample Output:
NO
From 0 he can take 1 jump to reach point 1 but after that he can take only 2 jumps which will lead him to
point 3. Jump sequence (1¬>2).
Page 259
Constraints:
0<=a<=1018
Q13. You are provided with N activities with their start and finish times, represented by
array S and F respectively. Your task is to find the maximum number of activities that can be performed by a
single person, assuming that a person can only work on a single activity at a time.
Input Format:
The first line of input contains an integer N denoting the number of activities.
The second line of input contains the elements of S, i.e. start time of each activity separated by space in the
increasing order
The third line contains the elements of array F, i.e. finish time corresponding to the start time of the
activities separated by space.
Output Format:
The maximum number of activities that can be performed in a single line followed by new line.
Sample case 0:
Sample Input 0:
3
10 12 20
20 25 30
Sample Output 0:
2
Constraints:
1 <= N <= 1051 <= Si<= 1051 <= Fi<= 105
Q14. Given an array of integers, your task is to count the number of duplicate array elements. Duplicate is
defined as two or more identical elements. For example, in the array [1, 2, 2, 3, 3, 3], the two twos are one
duplicate and so are the three threes.
Complete the program in the editor below. The program must return an integer denoting the number of
non-unique (duplicate) values in the numbers array.
It has the following:
numbers[numbers[0],...numbers[n-1]]: an array of integers to process
Constraints
• 1 ≤ n ≤ 1000
• 1 ≤ numbers[i]≤ 1000,0 ≤ i < n
Input Format:
The first line contains an integer n, the size of the numbers array.
The next n lines contain an integer describing the value of numbers[i] where 0 ≤ i < n.
Output Format:
A single line printing the number of duplicates in the given array
Sample Case 0
Sample Input 0
8
1
3
1
4
5
6
3
Page 260
2
Sample Output 0
2
Explanation 0
n= 8 and numbers= [1, 3, 1, 4, 5, 6, 3, 2]. The integers 1 and 3 both occur more than once, so we return 2 as
our answer.
Sample Case 1
Sample Input 1
6
1
1
2
2
2
3
Sample Output 1
2
Explanation 1
n= 6 and numbers= [1, 1, 2, 2, 2, 3]. The integers 1 and 2 both occur more than once, so we return 2 as our
answer.
Q15. A binary tree is a multi-node data structure where each node has, at most, two child nodes and one
stored value. It may either be:
1. An empty tree, where the root is null.
2. A tree with a non-null root node that contains a value and two sub-trees, left and right, which are
also binary trees.
A binary tree is a binary search tree (BST)if all the non-null nodes exhibit two properties:
• Each node's left sub-tree contains only values that are lower than its own stored value.
• Each node's right sub-tree contains only values that are higher than its own stored value.
A pre-order traversal is a tree traversal method where the current node is visited first, then the left sub-
tree, and then the right sub-tree. The following pseudocode parses a tree into a list using pre-order
traversal:
• If the root is null, output the null list.
• For a non-null node:
1. Make a list,left, by pre-order traversing the left sub-tree.
2. Make a list,right, by pre-order traversing the right sub-tree.
3. Output the stored value of the non-null node, append left to it, then append right to the result.
For more detail, see the diagram in the explanation section below.
Given q queries where each query consists of a list of numbers, determine if the sequence of numbers
describes the pre-order traversal of a binary search tree (BST). For each query, print YES on a new line if its
list describes a valid pre-order traversal of a BST; otherwise, print NO.
Input Format
1. The first line contains an integer,n, denoting the number of nodes in the tree.
2. The second line contains a list of n distinct space-separated integers in the inclusive range[1,
n]describing a pre-order traversal of a binary tree.
Constraints
1 ≤ n ≤ 100
Output Format
Page 261
Print YES on a new line if the query describes the pre-order traversal of a valid BST; otherwise,
print NO instead. Print a newline character at the end.
Sample Input 0
3
132
Sample Output 0
YES
Sample Input 1
3
213
Sample Output 1
YES
Sample Input 2
6
321546
Sample Output 2
YES
Sample Input 3
4
1342
Sample Output 3
NO
Sample Input 4
5
34512
Sample Output 4
NO
Explanation
The diagram below depicts the valid binary search trees for the first three queries:
Explanation:
1. Diagram(a)'s pre-order traversal matches the pre-order traversal in the first test case, 1 3 2, so we
print YES on a new line to indicate that the traversal matches a valid BST.
2. Diagram(b)'s pre-order traversal matches the pre-order traversal in the second test case, 2 1 3, so
we print YES on a new line to indicate that the traversal matches a valid BST.
3. Diagram(c)'s pre-order traversal matches the pre-order traversal in the first test case, 3 2 1 5 4 6, so
we print YES on a new line to indicate that the traversal matches a valid BST.
4. The fourth test case,1 3 4 2, is not a pre-order traversal of a binary search tree. We know that the
root is 1 because that is the first value in the list. For the second value to be 3, it must be the right
child of 1. For the third value to be 4, it must be the right child of 3. For 2 to be the last value in the
traversal, it would have to be the left child of 4; however, this would break the order property of a
binary search tree because a value less than 3 would be in 3's right sub-tree. Thus, we print NO on a
new line.
5. The fifth test case,3 4 5 1 2, is not a pre-order traversal of a binary search tree. We know that the
root is 3 because that is the first value in the list. For the second value to be 4, it must be the right
child of 3. For the third value to be 5, it must be the right child of 4. For the fourth value to be 1, it
Page 262
must be the left child of 5; however, this would break the order property of a binary search tree
because a value less than 4 would be in 4's right sub-tree. Thus, we print NO on a new line.
Q16. Julia is playing a game on an infinite two-dimensional grid, where the bottom left cell is referenced as
(1, 1) and each cell contains an initial value of 0. The game consists of n steps; during each step:
1. Julia has two integers,r and c.
2. Julia increments the value in every(i, j)cell satisfying 1 ≤ i ≤ r and 1 ≤ j ≤ c by 1.
After performing n such steps, Julia finds the maximum value,x, in any cell on the board, and counts the
number of occurrences of x.
Complete the program to count the total number of the greatest integer x in the grid after performing the n
steps.
Input Format
The first line contains an integer n, denoting the number of elements in steps.
Each of the n subsequent lines contains a string of two space-separated integers describing an index in
steps.
Constraints
• 1 ≤ n ≤ 100
• 1 ≤ r, c ≤ 106
Output Format
Return a long integer denoting the total number of occurrences of the greatest integer x in the grid
after n steps. Print a newline at the end.
Sample Case 0
Sample Input 0
3
23
37
41
Sample Output 0
2
Explanation
Given steps = ["2 3", "3 7", "4 1"]:
The portion of the infinite grid corresponding to cells (i,j) where 1 ≤ i ≤ 4 and 1 ≤ j ≤ 7.
After performing all n = 3 steps, the maximum x value in any cell is 3. Because there are two such cells with
this maximal value, we return 2 as our answer.
Sample Case 1
Sample Input 1
7
18 29
32 17
34 9
38 15
36 22
7 14
5 100
Sample Output 1
45
Page 263
Complete the calculate function in the editor so that for each day Ni (where 1 ≤ x ≤ N ≤ Y) in array arr, the
number of chocolates Sam purchased (during days 1 through N) is printed on a new line. This is a function-
only challenge, so input is handled for you by the locked stub code in the editor.
Input Format :
The calculate function takes an array of integers as a parameter.
The locked code in the editor handles reading the following input from stdin, assembling it into an array of
integers (arr), and calling calculate(arr).
The first line of input contains an integer, T (the number of test cases). Each line i of the T subsequent lines
describes the ith test case as an integer, Ni (the number of days).
Constraints : 1 ≤ T ≤ 2 × 105 1 ≤ N ≤ 2 × 106 1 ≤ x ≤ N ≤ Y
Output Format : For each test case, Ti in arr, your calculate method should print the total number of
chocolates Sam purchased by day Ni on a new line.
Sample Input and Output:
Input
3
1
2
3
Output
1
1
4
Explanation
Case 0: N = 1
Sam buys 1 chocolate on day 1, giving us a total of 1 chocolate. Thus, we print 1 on a new line.
Case 1: N = 2
Sam buys 1 chocolate on day 1 and 0 on day 2. This gives us a total of 1 chocolate. Thus, we print 1 on a
new line.
Case 2: N = 3
Sam buys 1 chocolate on day 1, 0 on day 2, and 3 on day 3. This gives us a total of 4 chocolates. Thus, we
print 4 on a new line.
Test case - 1:
3
1
1
2
1
3
4
Note: Do use the printf() with '\n' at the end.
Q20. Number Complement:
The complement of a number is defined here as the number's bitwise inversion from its highest-order 1-bit
through its lowest-order bit. For example, the number n = 5 is represented as 00000101 in binary. The
binary complement of n is 010, which is 2 in decimal notation.
Input Format : Locked stub code in the editor reads a single integer, n from stdin and passes it to the
function.
Page 265
Constraints : 0 ≤ n ≤ 105
Output Format : Return an integer denoting the complement of n.
Sample Input-0
50
Sample Output-0
13
Explanation-0
(50)10 converts to (110010)2. When we invert each bit in the sequence we get (001101)2, which
equals (13)10. Thus, we return 13.
Sample Input-1
100
Sample Output-1
27
Explanation-1
(100)10 converts to (1100100)2. When we invert each bit in the sequence we get (0011011)2, which
equals (27)10. Thus, we return 27.
TestCase-0
Input
401
Output
110
Note: Do use the printf() with '\n' at the end.
Q21. Array Sum:
Given an array A of N positive integers, you are provided with two functions sumprefix(i) and sumsuffix(i).
The sumprefix(i) function computes the sum of first i numbers of the array.
The sumsuffix(i) function computes the sum of last N - i + 1 numbers of the array.
Your task is to find the minimum index i for which the value sumprefix(i) + sumsuffix(i) is the minimum.
Which means you need to minimize the value of sumprefix(i) + sumsuffix(i)
and find the least index i for which this value is attained.
Input: The first line of input contains the integer N denoting the number of elements in array A. The second
line contains the N separated elements of array A.
Output: Output the single line containing the answer.
Constraints: 1 <= N, A[i] <= 105
Example:
Input:
3
123
Output:
1
Explanation:
Let's calculate the sumprefix(i) + sumsuffix(i) for all i.
sumprefix(1) + sumsuffix(1) = 1 + 6 = 7
sumprefix(2) + sumsuffix(2) = 3 + 5 = 8
sumprefix(3) + sumsuffix(3) = 6 + 3 = 9
The minimum value of the function is 7 which is attained at index 1, so the answer is 1.
TestCase-1:
Input
Page 266
10
17 14 14 12 11 11 9 5 4 2
Output
10
Note: Do use the printf() with '\n' at the end.
Q22. Duplicated Products:
Given n complex products, each with name, price and weight, find out how many duplicates of the original
product are present within the products. Here, a duplicate is a product with all parameters, i.e. name, price
and weight, equal to some other product.
Complete the program in the editor below. The program has to return a single integer denoting the
number of duplicates within the products.
It has:
names: string array of size n, where namesi denotes the name of the ith product
prices: int array of size n, where pricesi denotes the price of the ith product
weights: int array of size n, where weightsi denotes the weight of the ith product
Constraints
· 1 ≤ n ≤ 105
· namesi is non-empty, has at most 10 characters, and all its characters are lowercase english letters
· 1 ≤ pricesi, weightsi ≤ 1000
Input Format Format for Custom Testing : Input from stdin will be processed as follows and passed to the
function:
In the first line, there is a single integer n.
Then, n lines follow. In the ith of them, there is a single string namesi
In the next line, there is a single integer n.
Then, n lines follow. In the ith of them, there is a single integer pricesi
In the next line, there is a single integer n.
Then, n lines follow. In the ith of them, there is a single integer weightsi
Sample Case 0
Sample Input
5
ball
box
ball
ball
box
5
2
2
2
2
2
5
1
2
1
1
3
Page 267
Sample Output
2
Explanation
There are 5 products. All 3 balls are the same because they have same names, prices, and weights, so they
contribute 2 duplicates. Two other products are boxes, and they are different because they have different
weights.
Note: Do use the printf() with '\n' at the end.
Q23. Find the Factor:
Determine all positive integer values that evenly divide into a number, its factors. Return the pth element of
your list, sorted ascending. If there is no pth element, return 0.
For example, given the number n = 20, its factors are {1,2,4,5,10,20}. Using 1-based indexing if p = 3,
return 4. If p > 6, return 0.
Complete the program in the editor below. The function should return a long integer value of
the pth integer factor of n.
It has:
n: an integer
p: an integer
Constraints : 1 ≤ n ≤ 1015 1 ≤ p ≤ 109
Input Format for Custom Testing : Input from stdin will be processed as follows and passed to the function.
The first line contains an integer n, the number to factor.
The second line contains an integer p, the 1-based index of the factor to return.
Sample Input-0
10
3
Sample Output-0
5
Explanation-0
Factoring n = 10 we get {1, 2, 5, 10}. We then return the p = 3rd factor as our answer.
Sample Input-1
10
5
Sample Output-1
0
Explanation-1
Factoring n = 10 we get {1, 2, 5, 10}. There are only 4 factors and p = 5. We return 0 as our answer.
Sample Input-2
1
1
Sample Output-2
1
Explanation-2
Factoring n = 1 we get {1}. We then return the p = 1st factor as our answer.
Note: Do use the printf() with '\n' at the end.
Q24. Triangle Or Not?:
Mary has three sticks of lengths a, b, and c, and wants to determine whether she can use them to form
a non-degenerate triangle. For example, the stick lengths a = 3, b = 4, and c = 5 form a valid triangle, but the
stick lengths a = 1, b = 2, and c = 6 do not.
Page 268
Complete the function in the editor below. It has the following parameters:
Name Type Description
a integer array An array of n integers where each index i describes the length of side a for triangle i.
b integer array An array of n integers where each index i describes the length of side b for triangle i.
c integer array An array of n integers where each index i describes the length of side c for triangle i.
The function must return an array of n strings where the value at each index i is Yes if ai, bi, and ci can form
a non-degenerate triangle; otherwise, it's No.
Input Format :
The first line contains an integer, n, denoting the number of elements in a.
Each line i of the n subsequent lines (where 0 ≤ i < n) contains an integer describing ai.
The next line contains an integer, n, denoting the number of elements in b.
Each line i of the n subsequent lines (where 0 ≤ i < n) contains an integer describing bi.
The next line contains an integer, n, denoting the number of elements in c.
Each line i of the n subsequent lines (where 0 ≤ i < n) contains an integer describing ci.
Constraints : 1 ≤ n ≤ 105 1 ≤ ai, bi, ci ≤ 103 , where 0 ≤ i < n
Output Format : Return an array of n strings where the value at each index i is Yes if ai, bi, and ci can form a
non-degenerate triangle; otherwise, it's No.
Sample Input - 0:
3
7
10
7
3
2
3
4
3
2
7
4
Sample Output:
No
No
Yes
Explanation:
We want to check the following n = 3 possible triangles using the values given by a = [7, 10, 7], b = [2, 3, 4],
and c = [2, 7, 4]:
1. a0 = 7, b0 = 2, and c0 = 2 don't form a valid, non-degenerate triangle, so we store No in index 0 of our
return array.
2. a1 = 10, b1 = 3, and c1 = 7 don't form a valid, non-degenerate triangle, so we store No in index 1 of our
return array.
3. a2 = 7, b2 = 4, and c2 = 4 do form a valid, non-degenerate triangle, so we store Yes in index 2 of our
return array.
We then return the array ["No", "No", "Yes"] as our answer.
TestCase-0
Input
3
Page 269
7
10
7
3
2
3
4
3
2
7
4
Output
No
No
Yes
Note: Do use the printf() with '\n' at the end.