Problem Sheet 5

This problem sheet was created by Sir Narasimhan T, Assistant Professor, IT Department LBS College of Engineering, Kasaragod

The softcopy in .pdf is available here. There is  a bit more in the file.

1) Calculate the mean, variance and standard deviation of a set of numbers.

2) A m × n matrix M is said to have a saddle point if there is an entry M[i][j] such that it is the smallest value in row i and the largest value in column j. For example, consider the matrix:
20   30   40
56   78   45
1   2   3
Here 45 is the saddle point because it is the smallest in row1 but largest in column2. Given a matrix, find the saddle point if it exists.

3) Determine the norm of a matrix. Norm is defined as the square root of the sum of the squares of matrix elements. A sample input and output is shown below:
Enter the size of matrix
2  3
Enter 6 elements
1  2  3  4  5  6
The matrix is
1  2  3
4  5  6
The norm is 9.539392

4) A magic square of order n is a square matrix of integers from 1 to n^2 arranged randomly in a square grid fashion. The peculiarity of magic square is that the numbers in each row, and in each column, and the numbers in the forward and backward diagonals, all add to the same constant M where M =
n(n^2+1)/2.  For example, the matrix
2  7  6
9  5  1
4  3  8
is a magic square since each row, each column and the two diagonals add to (3×10)/2 =15. Write a program to input a square matrix from the user and that checks whether it is a magic square or not. The order of the matrix should also be input.

5) Convert decimal number to binary.

6) Interchange two rows in a matrix. Sample input and output is shown below
Enter number of rows
3
Enter number of columns
4
Enter the elements
4 8 12 16 1 2 3 4 3 9 12 18
The input matrix is
4 8 12 16
1 2 3 4
3 9 12 18
Which two rows you want to interchange?
0 2
The matrix after exchanging row 0 and row 2 is
3 9 12 18
1 2 3 4
4 8 12 16

7) The following is known as Pascal’s triangle.
1
1  1
1  2  1
1  3  3  1
1  4  6  4  1
1  5  10  10  5  1

Any element p[i][j] (except the 1’s at the left and right ends) in this triangle p is given by
p[i][j] = p[i-1][j-1] + p[i-1][j]
Input the number of rows and print the Pascal triangle.

8)Interchange two columns in a matrix. Sample input and output is shown below
Enter number of rows
4
Enter number of columns
3
Enter the elements
4 8 12 16 1 2 3 4 3 9 12 18
The input matrix is
4 8 12
16 1 2
3 4 3
9 12 18
Which two columns you want to interchange?
1 2
The matrix after exchanging column 1 and column 2 is
4 12 8
16 2 1
3 3 4
9 18 12

9) Input a string and print all its prefixes and suffixes. A sample input and output is given below:
Enter a string
cprogram
The prefixes of cprogram are
cprogram
cprogra
cprogr
cprog
cpro
cpr
cp
c
The suffixes of cprogram are
cprogram
program
rogram
ogram
gram
ram
am
m

10) A square matrix is called lower triangular if all the entries above the main diagonal are zero. Conversely a square matrix is called upper triangular if all the entries below the main diagonal are zero. A matrix that is both upper and lower triangular is a diagonal matrix. (A diagonal matrix will have non zero entries only on the main diagonal). Find whether an input matrix falls under any of these categories.

11) Write a program that takes nouns and that forms their plurals on the basis of these rules:
• If the noun ends in “y”,remove the y and add “ies”
• If the noun ends in “s”, “ch” or “sh”, add “es”.
• In all other cases just add “s”.
Print each noun and its plural. Sample input and output is listed here:
Enter how many nouns
5
Enter the nouns
chair
dairy
dish
church
circus
The nouns and their plurals are
chair – chairs
dairy – dairies
dish – dishes
church – churches
circus – circuses

12) Perform addition, subtraction and transpose operations on matrices. The user will enter ’a’ for addition,’s’ for subtraction and ’t’ for transpose. Only if the user enters ’a’ or ’s’, the second matrix needs to be input.

13) The alphabetic distance between 2 letters x and y is defined by assigning ’A’=1, ’B’=2, … ’Z’=26. Then the distance is y − x if y ≥ x, and (y + 26) − x if y < x. For instance, the alphabetic distance between ’B’ and ’D’ is 4 − 2 = 2, while the distance between ’D’ and
’B’ is (2 + 26) − 4 = 24. Given two words of equal length, the distance between them is the sum of alphabetic distances between the corresponding characters. Your aim is to input two words and print the distance between them.
Sample input and output – 1
Enter the words
AAAA ABCD
Distance between AAAA and ABCD is 6
Sample input and output – 2
Enter the words
DEADLY ULTIMO
Distance between DEADLY and ULTIMO is 65
[Note above that 6 = 0 + 1 + 2 + 3 and 65 = 17 + 7 + 19 + 5 + 1 + 16]

14) Write a program to form a Latin square. A Latin square is represented by an m × m two dimensional array filled with m different characters such that no element gets repeated either in the row or in the column. For example, if m = 4; the chosen characters are A, B, C, D and the first row is A B C D , then second row cannot have A as the first element as every column should have unique elements. Input the order m and the first row of the matrix and print the Latin square. A sample input and output is shown below:
Enter the order
3
Enter the first row
C A B
The Latin square is
C A B
A B C
B C A

15) Caesar cipher is a way of creating a code word (secret word) from a given word by substituting each character in the word with another character which is obtained by adding m (a constant which is called key) to the original character. For example if the original character is ’A’ and the value of m is 3, then the substituted character will be ’D’, which is A + 3. Assume that
the input word contains only upper case letters (ASCII 65-90). The following procedure can be used to obtain the codeword:-
• Take each character in the word and add m to it.
• If the number obtained is greater than 90, subtract 90 from the number. Let the result
be r. Now add r-1 to 65. In this way, the substituted character will always lie between A
and Z.
A sample input and output is shown below:
Enter the word
QWERTY
Enter the key
4
The codeword is
UAIVXC

16) Super Mario is studying how to use a mysterious Power Square. The Power Square is an n × n matrix with integer values between 0 and n^2−1. A number y is a neighbour of another number x in the Power Square if y is directly above or below x, or directly to the left or right of x.
Note that some values in the Power Square need not have all the four neighbours. Mario wants you to help him write a program that when given a number x in the Power Square, displays the Power Square and all the neighbours of x. Two sets of sample input and output are shown below:

SET 1
Value of n please?
3
9 Values please?
8 7 6 5 4 3 2 1 0
Neighbours of whom?
7
Power Square is
8 7 6
5 4 3
2 1 0
The neighbours of 7 are
8 6 4

SET 2
Value of n please?
4
16 Values please?
1 5 9 12 0 2 8 10 6 11 15 14 4 7 3 13
Neighbours of whom?
2
Power Square is
1 5 9 12
0 2 8 10
6 11 15 14
4 7 3 13
The neighbours of 2 are
0 5 8 11

Problem Sheet 4

This problem sheet was created by Sir Narasimhan T, Assistant Professor, IT Department LBS College of Engineering, Kasaragod

The softcopy in .pdf is available here. There is  a bit more in the file.

1)Write a program to reverse the contents of an 1D array without using a second array.

2)Assume that an integer array contains duplicate entries. Find the mode of this array. Mode is that element that occurs the most number of times. A sample input and output is shown below:
Enter array size
7
Enter 7 elements
2  1  -1  2  -1  4  -1
The mode is  -1

3)Rotate an array r times. Print the array after each rotation. A sample input and output is shown below.
Enter the array size
5
Enter the elements
10 7 8 25 16
How many times you want to rotate?
3
Array after rotation 1
16 10 7 8 25
Array after rotation 2
25 16 10 7 8
Array after rotation 3
8 25 16 10 7

4)An election is contested by 5 candidates whose symbols are @, #, $, % and &. The voting is done by marking the candidate symbol on the ballot paper. Get the number of voters from the user, conduct the election and announce the result. If a ballot is marked with a symbol other than those given above, it is considered as spoilt ballot. Spoilt ballots should not be considered during the counting process.

5)You are given the task of evaluating a test of 10 questions each of multiple-choice type. There are 4 possible choices A, B, C and D of which only one is correct. The answers are stored in a string ANSWER such that ith character in the string is the answer of (i+1)th question, 0 ≤ i ≤ 9. Say, if the first 5 questions have answers A and all others have B, then ANSWER is AAAAABBBBB. The student takes the test and submits his answer as a 10 character string TEST. If he doesn’t know the answer, he gives ’X’ for the corresponding question. For example, if the student gives ’A’ for 2nd and 7th questions, 4th question, a ’C’, doesn’t know the answer for 10th question and gives all other questions, a ’D’, his answer string TEST will be DADCDDADDX. Get the number of students from the user and get the answer string of each student and display the marks scored by each student. Assume that each correct answer carries 1 mark and wrong answer has a penalty of 0.25 mark.(negative mark)

6)Insert an element at a given position in the array. Sample input and output is given below:
Enter array size
7
Enter array elements
5  4  8  100  1024  4015  7
Enter the position and element to insert
3  45
The array after insertion of 45 is
5  4  8  45  100  1024  4015  7

7)Delete an element from a given position in the array. Sample input and output is given below:
Enter array size
6
Enter array elements
7 2 108 10 24 15
Enter the position to delete
4
The element deleted is 24 and the array after deletion is
7 2 108 10 15

8)Assume an array has duplicate entries. Remove the duplicate entries from this array. After the removal of all duplicate entries, the remaining elements should be in continuous positions.
Sample input and output is shown below:
Enter array size
9
Enter array elements
1 45 2 1 7 45 28 1 7
The array after removing duplicates is
1 45 2 7 28

Problem Sheet 3

This problem sheet was created by Sir Narasimhan T, Assistant Professor, IT Department LBS College of Engineering, Kasaragod

The softcopy in .pdf is available here. There is  a bit more in the file.

1)A generalized Fibonacci sequence is a sequence of numbers such that from the third number onwards, each number is the sum of preceding two numbers. An example of generalized Fibonacci sequence is: 2, 5, 7, 12, 19, · · · · · · , but 1, 2, 3, 4, · · · · · · is not. You are to write a program that, given a sequence of numbers, decides whether the sequence is a generalized Fibonacci sequence or not.

2)There are 500 light bulbs (numbered 1 to 500) arranged in a row. Initially they are all OFF. Starting with bulb 2, all even numbered bulbs are turned ON. Next, starting with bulb 3, and visiting every third bulb, it is turned ON if it is OFF, and it is turned OFF if it is ON. This procedure is repeated for every fourth bulb, then every fifth bulb, and so on up to the 500th bulb. Write a C program to determine which bulbs are off at the end of the above exercise.

3)In the Indian currency system, the denominations available are 5, 10, 20, 50, 100, 500 and 2000. To make a sum of 2000, you can use twenty 100 notes or four 500 notes or even a singe 2000 note (and many other combinations are possible). But the last option takes the least number of currency notes. Given the available denominations and the sum (input from user), write a program to make the sum using the available denominations with the least number of currency notes. (Assume the sum is an integer and forget about coins!!!)

4)Write a program that inputs a list of integers and an integer called target, and then prints the pair of elements whose sum is target. A sample input and output is given below.
Input the list
1 6 5 4 2 3 9 12
Input the target
7
The pair of elements that add to 7 are
1     6
5     2
4     3

5)Two players start playing a game. The game board consists of N heaps arranged in a sequence, each containing certain number of coins. The figure shows such a board with 5 heaps.
HEAP 1    HEAP 2    HEAP 3    HEAP 4    HEAP 5
7 coins    2 coins      4 coins      3 coins     5 coins

The two players move alternately from each end. When a player moves, he chooses a heap from either the left end or the right end of the sequence, and removes the selected heap of coins from the sequence. The player should be consistent in the sense that if he chooses to remove heap from left end of sequence, he should continue with left end only. The game is over when the board is exhausted (no coins left). The player who has collected the maximum number of coins wins the game. Write a program to play this game. A sample input and output is shown below:
Input
Enter the number of heaps
5
Enter the number of coins in each heap
7 2 4 3 5
Enter the id (1 or 2) of the player who starts the game
2
Enter L to choose left end or R for right end
L
Output
Player 2 wins with 13 coins
[Player 2 starts with left end and takes off the heap 1. So he has 7 coins. Next player 1 chooses heap 5 from right and gets 5 coins. Next player 2 chooses heap 2 and now has a total of 9 coins. Then player 1 chooses heap 4 and gets 8 coins in total. Finally player 2 chooses heap 3 and has now 13 coins. The game ends now because player 1 has no heap to choose.]

6)Write a program to print the pattern by inputting the number of lines:
1 3 5 7 9
3 5 7 9
5 7 9
7 9
9

7)Write a program to print the pattern by inputting the number of lines:

1
2 6
3 7 10
4 8 11 13
5 9 12 14 15

8)Write a program to print the pattern by inputting the number of lines:

1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1

Problem Sheet 2

This problem sheet was created by Sir Narasimhan T, Assistant Professor, IT Department LBS College of Engineering, Kasaragod

The softcopy in .pdf is available here. There is something much more in the file.

1) Predict the output of the following code snippets. Clearly specify the reasons for your answer.
a) main()
{
float a = 0.7;
printf(“%d %d”, sizeof(a),sizeof(0.7));
}
b) main()
{
float expr = 2.0;
switch(expr)
{
case 1.0: printf(“One\n”);
case 2.0: printf(“Two\n”);
default: printf(“Default\n”);
}
}
2) A character is entered through the keyboard, write a program to determine whether the character entered is a capital letter, a small case letter, a digit or a special symbol. The following table shows the range of ASCII values for various characters.
Characters                            ASCII values
A–Z                                          65 – 90
a–z                                           97 – 122
0–9                                           48 – 57
special symbols                   0 – 47, 58 – 64, 91 – 96, 123 – 127
3) Predict the output of the following code snippets. Clearly specify the reasons for your answer.
a) main()
{
float a=1.5;
int b = 3;
a = b/2 + b * 8 / b – b + a / 3 ;
printf(“a = %f”, a);
}
b) main()
{
int expr = 2, j = 1;
switch(expr)
{
case j: printf(“This is case1\n”);
case 2: printf(“This is case2\n”);default: printf(“This is default case\n”);
}
}
4) A library levies a fine for every book returned late. For first 10 days the fine is | 0.5 per day, for next 10 days fine is | 1 per day and for further 10 days fine is | 2 per day. If you return a book after 30 days, 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 or the appropriate message.
5) Predict the output of the following code snippets. Clearly specify the reasons for your answer.
a) main()
{
int x=0;
if(x=0)
printf(“Well done!”)
else
printf(“Sorry!”);
}
b) #define j 1
main()
{
int expr = 2;
switch(expr)
{
case j: printf(“This is case1\n”);
case 2: printf(“This is case2\n”);
default: printf(“This is default case\n”);
}
}
6) A university has the following rules for a student to qualify for a degree with A as the main subject and B as the subsidiary subject:
i. He should get 55% or more in A and 45% or more in B.
ii. If he gets less than 55% in A he should get 55% or more in B. However, he should get at least 45% in A.
iii. If he gets less than 45% in B and 65% or more in A he is allowed to reappear in an
examination in B to qualify.
iv. In all other cases he is declared to have failed.
Write a program to receive marks in A and B and output whether the student has passed, failed or is allowed to reappear in B.
7) Predict the output of the following code snippets. Clearly specify the reasons for your answer.
a) main()
{
if(!3.14)
printf (“I have robbed and killed…”);
else
printf (“Until my evil purse was filled”);}
b) main()
{
int planet=1;
switch(planet<<2+planet)
{
default:printf(“Solar system”);
case 6: printf(“Saturn”);
case 3: printf(“Earth”);
case 8: printf(“Neptune”);
}
}
8) Steel is graded according to the following conditions:
i. Hardness must be greater than 50
ii. Carbon content must be less than 0.7
iii. Tensile strength must be greater than 5600
The grades are as follows:
• Grade is 10 if all three conditions are met
• Grade is 9 if conditions (i) and (ii) are met
• Grade is 8 if conditions (ii) and (iii) are met
• Grade is 7 if conditions (i) and (iii) are met
• Grade is 6 if only one condition is met
• Grade is 5 if none of the conditions are met
Write a program, which will require the user to give values of hardness, carbon content and tensile strength of the steel under consideration and output the grade of the steel.

9) Predict the output of the following code snippets. Clearly specify the reasons for your answer.
a) main()
{
int x = 3, y = 4, z = 4;
printf(“%d”, (z>=y>=x?100:200));
}
b) main()
{
int i=1,j=3;
switch(i)
{
case 1:
printf(“This is outer case1\n”);
switch(j)
{
case 3:
printf(“This is inner case1\n”);
break;
default:
printf(“Inner case 2\n”);
}
case 6:printf(“This is outer case2\n”);
}
}
10) You are the computer programmer of a big firm which has recently shifted to a new 7-storey building. To help the clients easily locate the rooms, your boss has assigned you with the task of writing a program that will accept the room number as input and output the directions to reach the room. The room numbers are three digit numbers and follow a fixed pattern. The first digit indicates the floor and the last two digits denote the room number on that floor.
For example the room number 207 denotes the 7 th room on the second floor and room number 015 denotes the 15 th room on ground floor (zeroth floor). Further, on a floor, odd numbered rooms are on the left and even numbered rooms on the right and there are 16 rooms on every floor. Figure 1 shows the floor plan of 7 th floor and all the floors follow this plan. Accomplish your task. Two sample inputs and outputs are shown below:
Sample 1
Input
Enter the room number: 408
Output
Please follow the directions below to reach room number 408
Go to floor number 4
Turn right
Go to room number 4 onto your right
Sample 2
Input
Enter the room number: 011
Output
Please follow the directions below to reach room number 011
Turn left
Go to room number 3 onto your right
stair case
708    706    704    702  Stair case   701    703    705    707
710    712    714    716                        715    713    711    709
(Floor plan of 7 th floor for Question 10)

11) Predict the output of the following code snippets. Clearly specify the reasons for your answer.
a) main()
{
printf(“%d %d”, 4/-3, 4%-3);
}b)
main()
{
int expr = 2;
switch(expr)
{
case 1:
printf(“This is case1\n”);
break;
case 2:
printf(“This is case2\n”);
continue;
default:
printf(“This is default case\n”);
}
}
12) In a company, worker efficiency is determined on the basis of the time required for a worker to complete a particular job. If the time taken by the worker is between 2 – 3 hours, then the worker is said to be highly efficient. If the time required by the worker is between 3 – 4 hours, then the worker is ordered to improve speed. If the time taken is between 4 – 5 hours, the worker is given training to improve his speed, and if the time taken by the worker is more than 5 hours, then the worker has to leave the company. If the time taken by the worker is input through the keyboard, find the efficiency of the worker.

13) Predict the output of the following code snippets. Clearly specify the reasons for your answer.
a) main()
{
int x = 10,y = 100%90;
if(x!=y);
printf(“x = %d y = %d”, x, y);
}
b)
main( )
{
int c = 3 ;
switch(c)
{
case ’v’:
printf(“I am in case v \n”);
break;
case 3:
printf(“I am in case 3 \n”);
break;
case 12:
printf(“I am in case 12 \n” );
break;
default:
printf(“I am in default \n” );
}}
14) A hotel has a pricing policy as follows:
• 2 people: | 450
• 3 people: | 650
• 4 people: | 950
• Additional people: | 150 per person
If the customer is staying on company business, there is a 20% discount. If the customer is
over 60 years of age, there is a 15% discount. A customer does not receive both discounts.
Write a program to input the required data and then to print the cost of the room.

15) Predict the output of the following code snippets. Clearly specify the reasons for your answer.
a)main()
{
int a, b;
a = 5.999999;
b = 5.000001;
printf(“a = %d b = %d”, a, b);
}
b)
main( )
{
int i;
printf(“Enter any number”);
scanf(“%d”,&i);
switch(i)
{
case 1:
printf(“Sa\n”);
case 3:
printf(“Ga\n”);
case 2:
printf(“Re\n” );
case default:
printf(“Ma Pa Da Ni Sa\n” );
}
}
16) The seat numbers of reserved coaches in Indian Railways follow a fixed pattern as follows:
Seat numbers                                            Berth
1, 4, 9, 12, 17, 20 · · · · · ·                            Lower
2, 5, 10, 13, 18, 21 · · · · · ·                          Middle
3, 6, 11, 14, 19, 22 · · · · · ·                          Upper
7, 15, 23, · · · · · ·                                          Side lower
8, 16, 24, · · · · · ·                                          Side upper

Write a program to input the seat number and print the type of berth. Recall that seat number cannot be greater than 72.

Problem Sheet 1

This problem sheet was created by Sir Narasimhan T, Assistant Professor, IT Department LBS College of Engineering, Kasaragod

The softcopy in .pdf is available here.

1. A C program contains the following declarations and initial assignments:
int i = 8, j = 5, k;
float x = 0.005, y = -0.01, z;
char a, b, c = ’c’ , d = ’d’ ;
Determine the value of each of the following assignment expressions
(a) 2 * ((i / 5) + (4 * (j – 3)) % (i + j – 2))
(b) (i – 3 * j) % (c + 2 * d) / (x – y)
(c) 5 * (i + j) > c
(d) (x > y) && (i > 0) || !(j < 5)
(e) k = (j==5) ? i : j
(f) z = (y >= 0) ? y : 0
(g) a = (c < d) ? c : d
(h) i -= (j > 0) ? j : 0
(i) i *= i++ * j – –i
2. Suppose that a is an unsigned integer whose value is 0xa2c3. Evaluate the following
(a) a & 0x3f06
(b) a | 0x3f06
(c) a∧0x3f06
(d) a << 3
(e) a >> 4
(f) a | ∼0x3f06 << 3