CS100J
For-loop exercises
Spring 2007
1
This document contains two sets of exercises dealing with for-loops that process a range m.
.n of integers. When
doing them, do not worry about declaring variables; assume all variables are declared.
These exercises were written early in the morning and were not proofread by anyone. Further, the code was not
checked in DrJava. Hence, there may be mistakes. We apologize for them in advance.
A.
In each of the problems below,
1. Write an assertion at the end, the “postcondition”,
that indicates what is true at the end.
2. Fill in the first line of the loop, with initialization,
loop condition, and increment.
Note that we are not asking you to complete the loop,
but just to gain practice in the two tasks shown above.
Answers are given at the end.
A1.
// Store in x the sum of 3.
.n
for
(
int
k= ) {
// Process k
}
//
A2.
// Set x to the number of ‘e’s in String s
for
(
int
k= ) {
// Process k
}
//
A3.
// Set b to the value of the assertion
// “no int in 2.
.n-1 divides n”
for
(
int
k= ) {
// Process k
}
//
A4.
// Assume s1 and s2 have the same length
// Given are two string s1 and s2
// Set b to the value of the assertion
// “s2 is the reverse of s1”
for
(
int
k= ) {
// Process k
}
//
A5
.
int
n= s.length() – 1;
// Set b to the value of the sentence,
// “String s is a palindrome”, i.e.
// “s[0.
.n/2 – 1] is the reverse of s[n – n/2.
. n–1]”
for
(
int
k= ) {
// Process k
}
//
A6
. For this problem, note that the number of days in
each month of the year is: Jan, Mar, May, Jul, Aug, Oct,
Dec: 31, Apr, June, Sep, Nov: 30. Feb: 28. Therefore,
the number of days before month 3 (March) is 31 + 28 =
59.
// 1
≤
m
≤
12: so m is the number of a month.
// Set n to the no. of days in months 1.
.m–1.
for
(
int
k= ) {
// Process k
}
//
A7.
// Set v to the sum
// 1*(n–1) + 2*(n–2) + … + (n-1)*(n – (n–1))
for
(
int
k= ) {
// Process k
}
//
A8.
Assume that a function isPrime(n) yields true if n is