0% found this document useful (0 votes)
143 views15 pages

Computer Programming - Seminary Work

This document contains programming problems and questions about computer science concepts like arrays, memory addressing, and algorithms. It includes 12 programming problems ranging from easy to hard, as well as additional questions testing understanding of topics like array storage formats, memory addressing formulas, and recursive functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
143 views15 pages

Computer Programming - Seminary Work

This document contains programming problems and questions about computer science concepts like arrays, memory addressing, and algorithms. It includes 12 programming problems ranging from easy to hard, as well as additional questions testing understanding of topics like array storage formats, memory addressing formulas, and recursive functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

COMPUTER PROGRAMMING – SEMINARY WORK

1. In a language in which operations of the same priority are associated right to left, i.e. x–
y+z = x–(y+z), the value of the expression 7-(16/(3+1)*2)-4 is:
a. –1 c. 3
b. 1 d. 9

2. Assume that the values of the boolean expressions “A>B” and “B>C” are independent
and that, on the average, A>B in 75% of the cases and B>C in 25% of the cases.
Given the program code below, where V is a vector and f, g are functions:
if A>B then
V[I] := f(i)
else
if B>C then
V[I] := g(i)
then how many times do you expect functions f and g to be executed?
a. 2500 times f, 1875 times g c. 7500 times f, 1875 times g
b. 7500 times f, 625 times g d. 7500 times f, 2500 times g

3. Do users of the subway system, and respectively users of the telephone system, reach their
destinations by processes analogous to:
a. Selection, respectively traversal
b. Traversal, respectively selection
c. Both processes are analogous to traversal
d. Both processes are analogous to selection
4. If you assume an element array needs a single memory cell:
a. How many memory cells are required by A[0 . . 5]? #6
b. What about B[-1 . . 4, 5 . . 10]? #36
c. What about C[-5 . . -2, 2 . . 5, -2 . . 2]? #80

5. Assume that the arrays A, B, and C of the example above are stored linearly in row-major
order, beginning in addresses α, β and γ, respectively. What are the indices for the cells with
addresses:
a. α + 2, #A[2] d. γ + 7, #C[-5,3,0]
b. β + 12, #B[1,5] e. γ + 16, #C[-5,5,-1]
c. β + 17, #B[1,10] f. γ + 37? #C[-4,5,0]

6. What is the address of A[0,0,0] in an array stored linearly in row-major order beginning in
address α if:
a. It is declared as A[-5 . . 0,-2 . . 3,-2 . . 0]? # α+98
b. What if A is declared as A[-1 . . 5,-2 . . 2,0 . . 3]? # α+28

7. Suppose that the array B is stored linearly in column-major order, beginning in address β.
a. If B is declared as B[1 . . 3,1 . . 4], what is the address of B[2,3]? #β+7
b. If B is declared as B[1 . .U1,1 . . U2], what is the address of B[i,j]? # β + (j-1)U1 +
(i-1)
c. If B is declared as B[1 . . U1,L2 . . U2], what is the address of B[i,j]? # β + (j-I2)U1
+ (i-1)
d. If B is declared as B[L1 . . U1,L2 . . U2], what is the address of B[i,j]? # β + (j-
L2)(U1-L1+1) + (i-L1)
e. If B is declared as B[L1 . . U1,L2 . . U2,L3 . . U3], what is the address of B[i,j,k]?
# β + (k-L3)(U1-L1+1) )(U2-L2+1) + (j-L2)(U1-L1+1) + (i-L1)
f. If B is declared as B[-4 . . 3,0 . . 4,-5 . . 5,-2 . . 6], what is the address of B[0,0,0,0]?
# β + 880+200+4

8. The array a with r rows and c columns is stored using the row wise representation, with
a[0][0] corresponding to the actual base location of a, abase. Given an integer number k
(abase ≤ k ≤ abase + r × (c - 1)), write formulas that will yield the row and column of a to
which actual location k corresponds. That is, if a [i] [j] is stored in k, then your formula for
the row will yield i and for the column will yield j.
# k = ic+j

9. An antisymmetric array a is a square array that satisfies the condition that a[i][j] = -a[j][i] for
all 0 ≤ i, j < n. Hence the diagonal elements must be zero. Storing the antisymmetric array can
be done just as storing the symmetric array was done, except that now the diagonal entries
can be omitted, since they are known. Determine the formula for the offset of a[i] [j].
# pt. i<j: β + (n-1)n/2 –i(i+1)/2+j-i+1
pt. i>j: β + (n-1)n/2 –j(j+1)/2+i-j+1

10. An array a is said to be tridiagonal if the nonzero entries of a fall along the three diagonals
a[i] [i], a[i] [i+1], and a[i] [i-1], where i goes, respectively, from 0 to n - 1, 0 to n - 2, and 1 to
n - 1.
a. Construct a rowwise representation of the nonzero entries of a, and find a formula for
the offset of a[i] [j] in this array.
# a[i][i]: β + 3(i-1); a[i][i+1]: β + 3(i-1)+1; a[i+1][i]: β + 3(i-1)-1
b. Construct a diagonal representation of the nonzero entries of a tridiagonal array, and
find a formula for the offset of a[i] [j] in the array.
# a[i][i+1]: β + (i-1); a[i][i]: β + (n-1)+(i-1); a[i+1][i]: β + (2n-1)+(i-1)

11. Set i and j be two integers and define q(i, j) by q(i, j) = 0 if i < j and q(i-j, j) + 1 if i  j
a. What is the value of q(7,2)? #3
b. Can we determine q(0,0)? # No
c. Can we determine q(-3, -4)? # No

12. Let a be an array of type float and i and n be positive integers. The function rec(a,i,n) is
defined by rec(a,i,n) = a[i] if i = n and max(rec(a,i + 1,n) ,a[i]) if i < n
a. Find m(a,i,n) if i = 1, n = 6, and a is
i. 6.8 iv. # 14.6 vii. 3.2
ii. 3.2 v. 7.8 viii. 4.0
iii. -5.0 vi. 9.6
b. What does m(a,i,n) do? # max{a[1], a[2], …, a[n]}
Programming Problems (they vary in difficulty from easy through medium to hard, but if you
have worked through the tutorials in C you should find that all of them are accessible)
1. (E) Read a natural number n, then the natural sequence a1, a2, …., an. Determine the number
of ending 0s for the product p=a1a2 ….an. No product computation is required.
2. (E) For page numbering of a given book n digits are required. How many pages are there in
the book?
3. (E) Find every possible representation of the natural number n, as sum of natural consecutive
numbers.
4. (E) a) The proper divisors of a positive integer n are those integers, excluding n itself, that
divide n exactly. For example, the proper divisors of 12 are 1, 2, 3, 4 and 6. Write a program
that inputs a positive integer and outputs its proper divisors.
Sample run:
Input: 8
Output: 1 2 4
b) A perfect number is a positive integer that is equal to the sum of its proper divisors. For
example, 6 is a perfect number because 6=1+2+3. Write a program that inputs a positive
integer and outputs all perfect numbers less or equal than this number.
5. (E) The greatest common divisor (GCD) of two positive integers a and b is the largest integer
that divides each of a and b exactly. If the GCD of two numbers is known, their smallest
common multiple (SCM) is determined by the quotient between their product and their GCD.
a) Write a program that inputs two positive integers and outputs their GCD.
Sample run:
Input: 36 90
Output: 18
Hint: Here is a form of Euclid's algorithm for finding the HCF of two integers (illustrated
with numerical values supposing we want to find the HCF of 36 and 90):
 Write down the numbers: 36 90
 ... and also write down their difference: 36 90 54
 Form a "number chain" by repeatedly writing down the difference between the last
two numbers, stopping when you get to zero. The last non-zero number is the HCF:
 36 90 54 36 18 18 0
 The HCF of 36 and 90 is 18
b) Write a program that inputs two fractions in the form a/b and c/d, and outputs their sum in
the form p/q cancelled down to its simplest form.
Sample run:
Input: 5/6 1/10
Output: 14/15
6. (E) Write a program that inputs a string of keyboard characters and outputs the characters in
reverse order.
Sample run:
Input: Computer Science School
Output: loohcS ecneicS retupmoC
7. (M) Determine the exponent of any prime p in the decomposition of n!, the factorial of a
given number n.
8. (M) Let a be a bi-dimensional array. A saddle point in a given array a is an element a[i0,j0]
which is, simultaneously, the maximum of its column and minimum of its row, or vice versa.
Design a program to locate and print the saddle point(s) of the given matrix a (if there is any).
9. (M) Write a program that reads integers from the keyboard ending in 0; the 0 input acts as a
sentinel and is not used in the further processing of the data. All the numbers, except the 0,
will be stored into an array. The program should then read a number from the keyboard,
which indicates the position in the array of one of the numbers (call this number target) with
the first number entered having position 1, a.s.o. The program will then print out how much
each number in the array differs from target.
Sample run:
Enter numbers (ending in 0): 3 6 4 7 6 19 0
Enter position of target: 2
Differences: -3 0 -2 1 0 13
Hint: You have to make sure that the number of integers read is less than the array's size.
10. (E) Write a program to determine the union and intersection of two given sets, using
arithmetic bit operators. The given sets are represented by inclusion in sets like {0, ..., n1}
and {0, ..., n2} (where n1, n2 < 32), applying the binary vector method (this method uses
integers or binary words having bits set on 1 in positions corresponding to elements present in
the set).
Sample run:
Input: {0,3,5} {0,1,2,3,4}
Output: UNION is {0,1,2,3,4,5}, INTERSECTION is {0,3}
Hint: The sets may be represented even in input by numbers corresponding to the binary vectors,
i.e. {0,3,5} by (...)0000000000101001 (binary), (…)0029 (hexadecimal) or (…)00041 (decimal).
11. (H) In order to increase security the network manager has introduced some new rules
concerning passwords:
1. Passwords must consist of a mixture of lowercase letters and numerical digits only, with
at least one of each.
2. Passwords must be between 6 and 12 characters in length.
3. Passwords must not contain any sequence of characters immediately followed by the
same sequence.
Here are some examples:
cakeshop - rejected because it contains no numerical digit
ab34 - rejected because it's too short
A567xcz - rejected because 'A' is not allowed
9apple8 - rejected because 'p' is immediately followed by 'p'
03bananas - rejected because 'an' is immediately followed by 'an'
123xy123 - accepted ('123' does not immediately follow '123')
Write a program that inputs a password and then prints REJECTED if the password is
rejected, or ACCEPTED otherwise.
Sample run:
Input: cucumb3er7
Output: REJECTED
Hint: You have to make sure that the number of integers read is less than the array's size.
12. (E) Define a record (named structure) containing a string for a name, an integer for feet, and
another for arms. Use the new type to define an array of about 10 items. Design a program to
fill the fields with data and print them out as follows:
A human being has 2 legs and 2 arms.
A dog has 4 legs and 0 arms.
An armchair has 4 legs and 2 arms
...
Then redesign the program to dynamically allocate the array of structures.
13. (E) Many computer games and simulations involve randomization. Computers can generate
random numbers (more properly called pseudo-random numbers) and in C, for instance, you
can use the functions srand(seed) to initialize the random numbers generator, and rand() to
generate random integers in the range [0, RAND_MAX] inclusive, with RAND_MAX being
a value defined in stdlib.h, at least 32767.
a. Write a program that inputs an integer n and simulates the tossing of a fair coin n times,
outputting HEADS or TAILS for each toss.
b. Write a program that simulates the rolling of a pair of six-sided dice a large number of
times and outputs the frequency for each of the scores from 2 to 12.
14. (M) Write a program that inputs an integer n and ouputs each of the integers from 1 to n in
random order. Each integer should appear once and once only.
15. (M – BOI, 1999) A digital river is a sequence of numbers where the number following n is n
plus the sum of its digits. For example, 12345 is followed by 12360, since 1+2+3+4+5 = 15.
If the first number of a digital river is k we will call it river k. For example, river 480 is the
sequence beginning {480, 492, 507, 519, ...} and river 483 is the sequence beginning {483,
498, 519, ...}. While normal streams and rivers can meet, the same is true for digital rivers.
This happens when two digital rivers share some of the same values. For example: river 480
meets river 483 at 519, meets river 507 at 507, and never meets river 481.
Every digital river will eventually meet river 1, river 3 or river 9. Write a program which
inputs a single integer n (1<=n<=16384), and outputs the value where river n first meets one
of these three rivers.
16. (D – Mad Hatters Tea Party) The International Society of Mad Hatters meets for a tea party
once a year. At these occasions each hatter arrives - wearing a hat of course - and hangs his or
her hat on an individually numbered peg. Unfortunately, the hatters get very excited during
the course of the party and by the end none of them can remember their peg number. As a
result each hatter simply takes a hat at random and heads for home.
If there are n hatters, the probability that each hatter picks the correct hat is 1/n!, resulting
from the conditional expression: 1/n x 1/(n-1) x 1/(n-2) x ... x 1/3 x 1/2 x 1/1. However, in
this problem we are interested in the probability that no hatter picks the correct hat. Write a
simulation program that estimates this probability when the number of hatters is large.
17. (M -The Towers of Hanoi) We are given n circular disks, with different sizes, each with a
hole in the middle, initially stacked in the increasing size of their diameters on one of three
sticks, forming a “tower”. The objective is to transfer the entire tower to one of the other two
sticks, using the third, moving only one disk at a time and never a larger tower on top of a
smaller one.
18. (E) Write a program to sort exactly three numbers using only if--else statements.
19. (E) Produce a multiplication table in the form given below. The top left hand corner will
show 1x1 and the bottom right shows 10x10, as below.
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

20. (E) Develop an algorithm to give exact change for a purchase. The input is the purchase (in
dollars and cents) and the payment value. The purchase is in decimal notation. The output is
the number of U.S. coins and bills. Assume that the coins are the penny (1), nickel (5), dime
(10), and quarter (25). The bills are the $1, $5, $10, and $20.
Sample run:
Input: $216.70 $300
Output: 4 of $20, 3 of $1, 1 of $.25, 1 of $.05
21. When you pay for stuff with cash and get change back, the number of coins you get could
vary. For example, 10 cents in change can be done with 1 dime, or 2 nickels, or 1 nickel and 5
pennies, or 10 pennies. The rule of thumb for the cashier is to give the least amount of coins
from the selection of coins in the register. Write a program that produces the correct amount
of change in the fewest coins.
Each line of input will contain 5 integers: the amount of change to make, the number of
pennies available, followed by the number of nickels, then the number of dimes and finally
the number of quarters. For each input, print a line that has the number of pennies, the
number of nickels, the number of dimes and the number of quarters needed to make the given
change using the least number of coins. If the requested amount of change can't be made from
the given amount of coins, then print the message "Not enough change".
Sample run:
Input: 89 3 0 1 2 Output: Not enough change
89 10 10 10 10
4 0 1 3
89 0 0 0 4
Not enough change
45 45 0 0 0
45 0 0 0
22. (E) Write a program that reads in three real numbers. Determine computationally which of the
following cases are true: the three numbers
(a) Do not represent a triangle.
(b) Represent an equilateral triangle.
(c) Represent an isosceles triangle.
(d) Represent a right triangle.
(e) Represent a triangle that is not one of the three immediately above cases.
23. (E) The strtok function is rather important when it comes to programming in C. It can be used
to quickly parse some sort of input string into tokens. In this problem, the first line of input
will be a string of delimiters (don't ignore a space!). The following lines are lines you need to
parse using the strtok function (you are guarenteed to have at least one line to parse). The
delimiters used are on the first line of input you read in. No input line will be more than 80
characters long. For each input line to be parsed, your program will print out the tokens
generated by calling strtok. Each token should be on its own line. When finished parsing the
line, your program should print END.
Sample run:
Input: ; : END
the first; line parsed the
the *second *** line *second
Output:the ***
first line
line END
parsed

Hint: The function char *strtok( char *str1, const char *str2 ) returns a pointer
to the next "token" in str1, where str2 contains the delimiters that determine the token.
strtok() returns NULL if no token is found. In order to convert a string to tokens, the
first call to strtok() should have str1 point to the string to be tokenized. All calls after
this should have str1 be NULL.
Solution: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
char delim [85], s [85], *ptr;
gets (delim);
while (gets (s) != NULL) {
ptr = strtok (s, delim);
while (ptr) {
printf ("%s\n", ptr);
ptr = strtok (NULL, delim);
}
printf ("END\n");
}
return 0;
}
24. (E) Recurrence relations define a function in terms of itself and (maybe) other functions as
well. Being given two functions of interest:
F (N) = F (N - 1) + G (N - 1) ; F (1) = 1, and
G (N) = G (N - 1) + G (N - 3) ; G (1) = 1, G (2) = 0, G (3) = 1
For a given value of N, compute F (N).
25. (M) Postfix expressions are arithmetical expressions, important because they maintain
precedence without the use of (), and they're "easy" to evaluate. Being given several lines of
the input, no more than 80 characters in length, containing on a line only one expression to be
evaluated, you are required to output the result of evaluations. All expressions should be
correct postfix expressions. All numbers are non-negative integers. Note that while the input
numbers will not be negative, the answer may be negative. There will be one space between
each number/operator. The operators we're interested in are + (addition), - (subtraction), *
(multiplication) and / (integer division).
Sample run:
Input: 2 4 +
3 6 + 100 2 - 8 * - 600 + 20 10 * -
100 10 - 30 100 * + 80 10 * - 3 - 1 10 * 100 * + 0 *
Output: 6
-375
0
26. (E) Multiplying integers is easy, provided they fit within the range for integers (usually this
means they can be represented on 32 bits). Unfortunately, not everything falls within 32 bits.
Write a program to provide exact results when multiplying two large numbers.
Sample run:
Input: 9 7 Output: 63
105679 103457 10933232303
Hint: Use arbitrary precision arithmetic, like in cryptography. See also:
http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic , or
http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Intro/
27. (E) For each value of N, print out how many digits are in N!.
Sample run:
Input: 3 Output: 1
32000 130271
1000000 5565709
Hint: Use the function double floor (double x); that returns the largest integral value
that is not greater than x (truncates x if it is positive).
Solution: #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int digs (unsigned long int N);
int main (void)
{ unsigned long int N;
char s [100];
while (gets (s) != NULL) {
sscanf (s, "%lu", &N);
printf ("%d\n", digs (N));
}
return 0;
}
int digs (unsigned long int N)
{
unsigned long int i;
double ans;
ans = 0.0;
for (i = N; i > 0; i--) {
ans += log (i) / log (10);
}
return (1 + (int)(floor (ans)));
}
28. (M) N! is easy to be computed for values of N! that fit into the range of integers but more
difficult for larger values of N!. Write a program to compute the factorial of a given integer
between 0 and 100, being known that 100! has no more than 200 digits.
Sample run:
Input: 8
50
Output: 40320
30414093201713378043612608166064768844377641568960512000000000000
29. (M) a) A palindrome is a string that reads the same both backwards and forwards. For
example, atoyota is a palindrome because if you read it backwards, you get atoyota again.
Write a program to check if the input is a palindrome or not.
b) Any word that is not already a palindrome can be made into one by attaching the
appropriate letters. ab may not be a palindrome, but by attaching an a, we get aba which is a
palindrome. Note that we could also attach ba to get abba which is also a palindrome. There
are an infinite number of strings you can attach to get a palindrome. In this problem, we're
interested in the shortest-length string that gives us the palindrome.
Hint: Each line of input will be one test case - a string of no more than 80 characters. All the
characters will be lower case letters. There will be no spaces, or other characters on the line.
30. (H) Being given a rectangular maze, with no more than 80 columns and 80 rows, you are
required to determine how long is the shortest path through the maze. Each position of the
maze is one of two characters. An ‘O’ means you may move onto that position. A ‘X’ means
that space is occupied by a wall. You are allowed to move in any direction (up, down, left,
right, diagonal) provided that the square you move into isn't an `X'. You always start in the
upper left hand corner of the maze. The exit is always at the lower right hand corner of the
maze. There will always be at least one path through the maze.
Sample Run:
Input:OXXXOOXXX
OOXXXOOXX
OOXXXXOXX
OXXXXXOXO
OOXXXXOXO
XOOOOOOOO
XOXXXXXOO
Output: 12
31. (M) Write a program that reads in a phrase, containing words (each word is no more than 20
lower or uppercase characters), separated by spaces, commas, !, ?, and periods, and outputs
the duplicate words, in lower case and in sorted order. All comparisons should ignore case.
32. (M) Write a program to implement a simple calculator, with register variables and support for
instructions of the form z = x op y where op is some operation, x, y can be either variables or
integer numbers (all integers given will be between -32767 to 32767, inclusive), and z is a
variable (btw: this syntax is similar to 3 address code, which simple compilers make use of).
For our purposes, op can only be +, or * (each with their usual, obvious, meanings) and the
variables can be a, b, c, d, e, n. All of them, except n can store values. n is a "null" variable;
you can write to it, but its value always stays at 0. All the variables are initialized to 0 at the
start. Each variable can store a full 32-bit number. On the input line, no embedded spaces will
appear; no other characters, other than the ones for variables, numbers, or operations, will
appear; and all variable names will be lower case. On the output, for each input line given,
first print the value of x op y (the semantics are that the value is first printed, then it's stored
into the variable), and, after all lines of input have been read in, print the final values of each
register. These values should be printed one per line in the form var=val.
Sample Run:
Input: a=0*2 0
b=a+2 0
c=b*10 200
d=c+-20 a=0
e=n+d b=2
n=100*b c=20
d=0
Output: 0 e=0
2
n=0
20
33. (E) Being given a finite sequence of n real numbers, write a program to determine the values
of all maximal and minimal elements in the sequence, and their ranks. Each input will consist
of two lines: the value of n on the first, followed by the n values in the sequence on the next
line. The output will consist of four lines for each pair of input lines: the first will be the
maximal value, then its ranks, then the minimal value and its ranks.
Sample run:
Input: 8 -2
1 2 4 –2 –2 4 3 4 4 5
5 10
2 4 6 8 10 5
2
Output:4 1
3 6 8
34. (M) Being given a finite sequence of n real numbers, write a program to determine the longest
increasing subsequence(s), and to print their minimal rank. Each input will consist of two
lines: the value of n on the first, followed by the n values in the sequence on the next line.
The output will consist of two numbers: the first will be the rank from where the first minimal
increasing subsequence begins, and the second will be the length of this subsequence.
Sample run:
Input: 11 Output:4 3
1 1 2 –2 –1 0 0 1 2 -4 2 3 4
6
2 3 –1 3 4 9
35. (E) Being given a finite sequence of n real numbers, write a program to determine the values
of all maximal elements in the odd ranks subsequence, and the values of all minimal elements
in the even ranks subsequence, and their ranks. Each input will consist of two lines: the value
of n on the first, followed by the n values in the sequence on the next line. The output will
consist of four lines for each pair of input lines: the first will be the maximal value, then its
ranks, then the minimal values and its ranks, with respect to the initial sequence.
Sample run:
Input: 8 Output:1
1 2 0 –1 1 2 -1 -1 1 5
-1
4 8
36. Let f : [a,b]  R a continuous function which satisfies the condition f(a)f(b) < 0. Write a C
program which reads the precision factor eps > 0 and the number of iterations n > 0, and
computes a root of the equation f(x) = 0, a  x  b, in maximum n iterations, using the bisection
method.
Hint: Because f(a)f(b) < 0, function f has at least one root x0 in [a,b]. With the bisection
method, we compute c = (a + b)/2, and if f(a)f(c) < 0, we replace b with c, otherwise
we replace a with c. This step is repeated until the difference |a - b| is sufficiently
small, that is a - b < eps, or the maximum number n of iterations is obtained.
Alternative stopping techniques are: a - b/b < eps or f(c) < eps.
37. Write a program which finds a decomposition of a given natural number n as the sum of a
minimum number of Fibonacci numbers. Fibonacci numbers are generated according to the
following recurrence: F0 = F1 = 1, Fk+1 = Fk + Fk-1, k  1. The program will print the values
and also the ranks of the Fibonacci numbers whose sum is n.
Sample Run:
Input: 320
Output: 320 = F12 + F9 + F7 + F5 + F3 = 233 + 55 + 21 + 8 + 3
Hint: The algorithm will first compute the largest Fibonacci number which is less or equal than
n, let it be f. Then, the value of f will be printed, and n will become n - f. If the new value of n is
zero, the algorithm stops; otherwise, the above step is repeated until this condition is met.
38. A magic square is a n  n matrix of the integers 1 to n2 such that the sum of every row, column
and diagonal is the same. For example, if n = 5 we have the magic square:

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

Magic squares exist for all orders n ≥ 1 except n = 2, although the case n = 1 is trivial - it
consists of a single cell containing the number 1.
a. Write a C program for creating a n x n magic square for n odd.
b. Write a C program for creating a n x n magic square when n is double even (multiple of 4).
Hint: a. When n is odd the following algorithm can be used to generate a magic square: "start
with 1 in the middle of the top row; then go up and left assigning numbers in increasing order to
empty squares; if you fall off the square imagine the same square as tiling the plane and
continue; if a square is occupied, move down instead and continue". Similar patterns can also
be obtained by starting from other squares.
b. When n is double even the following algorithm can be used:” All the numbers are
written in order from left to right across each row in turn, starting from the top left hand
corner. Numbers are then either retained in the same place or interchanged with their
diametrically opposite numbers in a certain regular pattern”. I.e., in the magic square of order
four, the numbers in the four central squares and one square at each corner are retained in the
same place and the others are interchanged with their diametrically opposite numbers.
39. (min-max) Given an array of integers in which the no of elements is a power of 2, find both
the maximum element and the minimum element in the array, in the “best” possible way (in
terms of the least number of comparisons needed). Why you think your algorithm is “best”?
Then, modify the previous algorithm so that arrays of any size can be handled. What happens
with the efficiency in this last case? (is the algorithm still the “best”? is it still very efficient at
least?)
40. A knight is a chess piece that can move in the pattern of the letter “L”. On the 64 squares
chessboard, the knight can make 2 legal moves if placed at a corner square and 8 legal moves
if placed in the middle. The connectivity of a square is given by this number of legal moves a
knight can make if placed in the square. Write a function to compute the connectivity of the
square and a program to find and print the connectivity of each of the 64 squares.
Homework: A knight’s tour is a path the knight takes that covers all 64 squares without
revisiting any square. From any starting square, write a program to find and print a knight’s
tour (for each position you print the no of moves it took the knight to reach that square).
Hint: For combinatorially difficult problems you can apply a heuristic algorithm called the
Warnsdorf-Pohl rule, that has always found to work. Warnsdorfs greedy strategy is “go to a
next square which has the fewest ways out”; on the chessboard this means favoring corner
squares over all others and edge squares in preference to central squares. Pohl’s improvement
says: “when two squares have the same smallest connectivity, break the tie by computing
recursively which square leads to a further smallest connectivity and choose that square.”
41. Define a structure that contains the name of a food, its calories per serving, its food group (i.e.
from: soup, appetizer, salad, meat, cake or fruit), and its cost. The foods may be stored as an
array of structures, or in a file with the above structure. Given the calories and the cost
constraints (upper limits) write a program that is able to produce a list of balanced meals, that
is, meals that contain four food groups and meet calories and cost constraints.
42. Gill Bates has a million dollars to invest. She is considering the following alternatives:
- 9 % interest compounded yearly;
- 8.75 % compounded quarterly;
- 8.7 % compounded daily,
for a period of either 10 or 20 years.
Develop a program that prints a table with 6 rows, one for each alternative that helps you to
give Gill a quick advice. The program should input the above data as parameters.
Hint: You may consider as a reasonable approximation 365 days/ year.
43. Given three sparse square matrices A, B, C (these are arrays with more than 90% null
elements), stored in the most efficient way in the form (i, j, non-zero element value in line i
and column j), write the appropriate functions and then develop a program to compute the
matrix D=A∙B+C. The program must work in the most efficient way and the result should be
printed on the screen in the usual matrix form.
44. (Chain matrix multiplication) You are given 3 sparse rectangular matrices Amxn, Bnxp, Cpxq
(that is, bidimensional arrays with more than 90% null elements), stored in an efficient way at
your choice (i.e. in the form list of (i, j, non-zero element value in line i and column j), or
array of lines written as lists of non-zero elements and corresponding column number).
a) Write the appropriate functions, one to multiply two matrices written in sparse form and
another to print a sparse matrix in the usual rectangular form, and then develop a program to
compute the matrix D=AxBxC and print it.
b) The product being associative, you can look for an optimal way of parenthesizing the
expression so that a minimal number of operations will be performed. What is required for
you now is to monitor the performance, that is, to record the number of operations that lead to
a non-zero result and compare the sums in the two possible cases. So, change the above
program to do so: to do multiplication two ways and to monitor performance in each case.
45. Write a program to test whether or not an input integer has the cube property. The cube
property holds for a three digit number if the sum of the cube of the digits gives the number
itself. A correct number is 153= 1+ 125 + 27.
46. (Russian Peasant Multiplication) This program allows one to do multiplication by just doing
muliplication or division by 2, and addition (this is interesting since computers generally use
base 2 arithmetic). The algorithm is as follows. Start two rows, one with the multiplicand
(say, A) and the other the multiplier (say B). The goal is to multiply A by B. The first number
is successively divided by 2 while the second number is multiplied by 2. If the number in the
first column is odd, then the corresponding number in the second column is added to the sum.
The final sum is the product.
Example:
Multiplicand Multiplier Product
37 41 41+0 = 41
18 82
9 164 164+41 = 205
4 328
2 656
1 1312 1312+205 = 1517
47. Write a C program to reverse digits of a number

The following solution is accepted and marked above average (7+)…

Data structures: number, reversed number (+intermediary as needed)


ITERATIVE WAY
Algorithm:
read num
rev_num = 0
while num > 0
rev_num = rev_num*10 + num%10;
num = num/ 10
return rev_num

Example:
num = 4562
rev_num = 0
rev_num = rev_num *10 + num%10 = 2
num = num/10 = 456
rev_num = rev_num *10 + num%10 = 20 + 6 = 26
num = num/10 = 45
rev_num = rev_num *10 + num%10 = 260 + 5 = 265
num = num/10 = 4
rev_num = rev_num *10 + num%10 = 265 + 4 = 2654
num = num/10 = 0
Program:

#include <stdio.h>

/* Iterative function to reverse digits of num*/


int reversDigits(int num)
{
int rev_num = 0;
while(num > 0)
{
rev_num = rev_num*10 + num%10;
num = num/10;
}
return rev_num;
}

/*Driver program to test reversDigits*/


int main()
{
int num = 4562;
printf("Reverse of no. is %d", reversDigits(num));

getchar();
return 0;
}

Time Complexity: O(Log(n)) where n is the input number.

RECURSIVE WAY.

#include <stdio.h>;

/* Recursive function to reverse digits of num*/


int reversDigits(int num)
{
static int rev_num = 0;
static int base_pos = 1;
if(num > 0)
{
reversDigits(num/10);
rev_num += (num%10)*base_pos;
base_pos *= 10;
}
return rev_num;
}

/*Driver program to test reversDigits*/


int main()
{
int num = 4562;
printf("Reverse of no. is %d", reversDigits(num));

getchar();
return 0;
}
Time Complexity: O(Log(n)) where n is the input number

Note that the above program doesn’t consider leading zeroes. For example, for 100, the program
will print 1.

You might also like