September 28, 2008

Small Code Cloze Excercises for Computer Science

1. Visual Basic (Random Number Generator):
The user inputs a range of two numbers: lowNum, highNum. From this input, the sub routine will change the lblNumbers.Caption value to a random number between the user-defined range (inclusive). If the code is ran again, we want the program to always supply a random number that is different from the first.

Bolded code would be deleted to assess student comprehension.
lowNum = txtLow.Text
highNum = txtHigh.Text

prevNum =
lblNumber.Caption

Do
randomNum = Int(Rnd * (
highNum - lowNum + 1)) + lowNum
Loop Until randomNum <>
prevNum

lblNumber.Caption = randomNum

2. Java (Determine the Sum of Each Digit from a 7-Digit Number):
Reviews division, modulus, and Math() functions in Java. Students have to try and determine a brute-force and a more elegant solution (using For-Loops) to solve the problem. While a bit "mathy," I think it gives students a chance to make connections as to why elegant solutions save programmers time and energy (e.g. How much code would you have to write to get the sum of a 20-digit number? Which version would be easier to modify?).

Bolded code would be deleted to assess student comprehension.
String inputString;
int digitString, digitSumLong, digitSumQuick;

inputString = JOptionPane.showInputDialog ("Input a 7-digit integer: ");
digitString = Integer.parseInt(
inputString);

// sum the individual digits the LONG way...
digitSumLong = digitString%
10 + (digitString/10)%10 + (digitString/100)%10 + (digitString/1000)%10 + (digitString/10000)%10 + (digitString/100000)%10 + digitString/1000000;

// sum the individual digits the QUICK way!
for (int i = 0 ; i <=
6 ; i++)
{
if (i == 6)
digitSumQuick += digitString/Math.pow(10,i);
else
digitSumQuick += (digitString / Math.pow(
10,i)) % 10;
}
That's all for now!

1 comment:

Brad B said...

Good idea by bolding the items you would delete. I just sent them in blank! Your demonstration of literacy knowledge tests has been noted. Luchidor!