quiz1solns

# quiz1solns - 2 for 1 ← i to m 3 if n is even 4 3-← n n...

This preview shows page 1. Sign up to view the full content.

CMPS 10 Fall 2007 Quiz 1 Solutions 1. (12 Points) Consider the following algorithm: 1. get values for n and m from the user 2. 1 i 3. while m i 4. if n is even 5. 3 - n n 6. else 7. n n 2 8. 1 + i i 9. print n 10. print i 11. stop (a) (4 Points) Assume that when line 1 is executed, the values entered by the user are 10 and 11 respectively (i.e. 10 = n and 11 = m ). What will be the value printed by line 9? Answer: 131 (b) (4 Points) Under the same assumption, what will be printed by line 10? Answer: 12 (c) (4 Points) Write an equivalent algorithm which uses a for loop instead of a while loop. (Two algorithms are considered equivalent if given the same input, they produce the same output.) Solution: 1. get values for n and m from the user
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 2. for 1 ← i to m 3. if n is even 4. 3-← n n 5. else 6. n n 2 ← 7. print n 8. print i 9. stop 2. (8 Points) Write an algorithm in pseudocode which takes a positive integer n from the user as input, then prints out the sum of all the odd integers in the range 1 to n . If n itself is odd, then n is included in the sum, while if n is even, it is not included in the sum. Thus if the user enters either 5 or 6, the sum 9 ( 5 3 1 + + = ), is printed. Solution: There are a number of valid solutions, one of which is: 1. get a value for n from the user 2. sum ← 3. 1 ← i 4. while n i ≤ 5. sum ← sum + i 6. 2 + ← i i 7. print sum 8. stop...
View Full Document

## This note was uploaded on 09/15/2011 for the course CMPS 10 taught by Professor Tantalo during the Fall '08 term at UCSC.

Ask a homework question - tutors are online