Question 1) Illustrate that how iteration works in programming languages by writing programs given below.
a) A program to sum number of integers from 1 to a given number n.
b) A program that sums the contents of a integer list or array.
c) Transform the following for loop into a while loop (which does the same thing as the for loop):
for i in range(1,10):
print "i = ", i
d) Transform the following while loop into a for loop (which does the same thing as the while loop):
i = 20
while (i > 0):
print "i = ", i
i =- 1
a) What do you mean by a recursive function?
b) The iterative function given below returns the sum of all elements in a list. For instance, given the list [1, 2, 3] the function will return 1+2+3 or 6. Re-write the function as a recursive function.
def sum(arg):
result = 0
for i in arg:
result += i
return result
c) The code given below implements a recursive function in Python called foobar. What does foobar function do? Write a line of code that calls the foobar function with a appropriate argument and state what the return value will be.
def foobar(arg):
if arg == []:
return arg
else:
return foobar(arg[1:]) + [ arg[0] ]
d) The following code implements two mutually recursive functions – functions that call each other:
def ise(n):
if n==0: return True
else: return iso(n-1)
def iso(n):
if n==0: return False
else: return ise(n-1)
What will the following function calls return:
i) iso(3)
ii) iso(2)
iii) ise(3)
iv) ise(2)
What do the functions iso and ise perform?