Tom Kelliher, CS 116
Dec. 1, 2000
Course evaluation Monday.
Will post exam solution Friday afternoon.
Will post postlab solution (MPG problem) Monday afternoon.
Final review on 12/12 from 1--3pm in HS 134.
Read 8.3, lab handout.
Loops
for
loops.
Lab 7.
int summation(int n) { int sum = 0; int i; for (i = 0; i <= n; ++i) sum += i; return sum; }
n
.
int evenSummation(int n) { int sum = 0; int i; for (i = 0; i <= n; i += 2) sum += i; return sum; }
Complete the bodies of the following methods:
for
loop:
double pow(double x, int n) { // ... }
while
loop.
int fact(int n) { // ... }
Yes, loops can be nested, like if
s.
What are the values of count1
and count2
after each code
segment executes?
int i; int j; int count1 = 0; int count2 = 0; for (i = 0; i < 5; ++i) { ++count1; for (j = 0; j < 5; ++j) ++count2; }
int i; int j; int count1 = 0; int count2 = 0; for (i = 0; i < 5; ++i) { for (j = i; j < 5; ++j) ++count2; ++count1; }
final int SIZE = 3; int idata[] = new int[SIZE]; double ddata[] = { 0.0, 100.0, 123.4, 67.89 }; int i; double sum; data[0] = 12; data[1] = -4; data[2] = 7; sum = 0.0; for (i = 0; i < ddata.length; ++i) sum += ddata[i];Note use of
[]
, indexing starts with 0
, and the use of
.length
.
Write a method to determine if the data in an int
array are sorted
into ascending order. Should work for any size array.
boolean sorted(int d[]) { int i; for (i = 0; i < d.length - 1; ++i) if (d[i] > d[i + 1]) return false; return true; }
sorted()
void sort(int d[]) { int i; boolean sorted = false; int temp; while (!sorted) { sorted = true; for (i = 0; i < d.length - 1; ++i) if (d[i] > d[i + 1]) { sorted = false; temp = d[i]; d[i] = d[i + 1]; d[i + 1] = temp; { } }
See class homepage for full applet.
// Instance variables. private String faculty[] = { "Kelliher", "Koppelman", "Lewand", "McKibben", "Morrison", "Tutinas", "Zimmerman" }; private TextField search = new TextField(20); private Button searchB = new Button("Search"); private Label result = new Label("No search yet"); // ... public void actionPerformed(ActionEvent e) { int i; String target = search.getText(); for (i = 0; i < faculty.length; ++i) if (faculty[i].equals(target)) { result.setText("Found at index " + i); return; } result.setText("Not found"); }