st12-recursion-sol

st12-recursion-sol - CSC 1111 Introduction to Computing...

This preview shows pages 1–7. Sign up to view the full content.

1 CSC 1111 Introduction to Computing using C++ Recursion (Self-test questions)

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 What's the output? void foo(int x) { if (x <= 0) return; foo(x / 10); cout << x % 10; } foo(6201); 6201 Answer:
3 What's the output? void foo(int x) { if (x <= 0) return; cout << x % 10; foo(x / 10); } foo(6201); 1026 Answer:

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
4 What's the output? int foo(int x, int y) { if (x < 0 || y < 0) return 0; if (x > y) return x + foo(x – 1, y); else return y + foo(x, y – 2); } cout << foo(3, 7); 21 Answer:
5 foo(3,7) = 7 + foo(3, 5) = 7 + (5 + foo(3, 3)) = 7 + (5 + (3 + foo(3, 1))) = 7 + (5 + (3 + (3 + foo(2, 1)))) = 7 + (5 + (3 + (3 + (2 + foo(1, 1))))) = 7 + (5 + (3 + (3 + (2 + (1 + foo(1, -1)))))) = 7 + (5 + (3 + (3 + (2 + (1 + 0))))) = 7 + (5 + (3 + (3 + (2 + 1)))) = 7 + (5 + (3 + (3 + 3))) = 7 + (5 + (3 + 6)) = 7 + (5 + 9) = 7 + 14 = 21

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
6 What's the output? int foo(int a[], int idx1, int idx2, int x) { if (idx2 < idx1) return -1; int m = (idx1 + idx2) / 2; if (a[m] > x) return foo(a, idx1, m-1, x); else
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 12/28/2010 for the course CSC CSC1110 taught by Professor Cjyuan during the Fall '06 term at CUHK.

Page1 / 11

st12-recursion-sol - CSC 1111 Introduction to Computing...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online