CS99 |
Fundamental Programming Concepts
Summer 2001 |
|
Prelim 2: Solutions
Tracing Output
TokenReader
in = new TokenReader( System.in );
int p = in.readInt();
int d = 0;
int n = 0;
while ( p > 1 ) {
d = 2;
while ( ( p
% d) != 0 )
d = d + 1;
if ( d == p )
n = n + 1;
p
= p - 1;
}
System.out.println();
p: | 5 | 4 | 3 | 2 | 1 | |||||||||||||
d: | 0 | 2 | 3 | 4 | 5 | 2 | 2 | 3 | 2 | |||||||||
n: | 0 | 1 | 2 | 3 |
Part 2: Dangling Elses & Formatting Code
Part A properly indented:
if (
x < 10 ) System.out.print( "!!!" ); if ( y > 10 ) System.out.println( "***" ); else System.out.print( "###" ); System.out.println( "$$$" ); |
Output for Part A:
x=9, y=11: !!!*** $$$ |
x=11, y = 9: ###$$$ |
Part B properly indented:
if (
x > 10 ) {
if ( y < 10 ) System.out.println( "***" ); } else { System.out.println( "###" ); System.out.println( "$$$" ); } |
Output for Part B:
x=9, y=11: ### $$$ |
x=11, y = 9: *** |
TokenReader in = new TokenReader( System.in );
int n = in.readInt();
// other declarations
int stars;
Solution 1.
while ( n > 0 ) {
stars = in.readInt();
while ( stars > 0 ) {
System.out.print("*");
stars--;
}
n--;
}
Solution 2.
// other declarations
int stars;
int count = 1;
int countStars;
while ( count <= n ) {
stars = in.readInt();
countStars = 1;
while( countStars <= stars ) {
System.out.print("*");
countStars++;
}
count++;
}
Part 4: Determining
Output [10 points]
Output:
6
3
1