Spring Semester 2005


Lecture Notes Ten: for loops and Other Homework Considerations

Structured Programming

Any possible program can be constructed using modules of the following types:

Examples

int x, y, max, min;
double avg, dist; 
ConsoleReader c; 
c = new ConsoleReader(System.in); 
System.out.print("Please enter the first number: "); 
x = c.readInt();
System.out.print("Please enter the second number: "); 
y = c.readInt(); 
avg = (x + y) / 2.0; 
dist = Math.abs(x - y); 
max = (int)Math.round((avg + dist) / 2.0); 
min = (int)Math.round((avg - dist) / 2.0); 
System.out.println(max + " is greater than " + min); 


int x, y, max, min;
double avg, dist; 
ConsoleReader c; 
c = new ConsoleReader(System.in); 
System.out.print("Please enter the first number: "); 
x = c.readInt(); 
System.out.print("Please enter the second number: "); 
y = c.readInt(); 
if (x > y) { // x is greater than y  
  max = x; 
  min = y; 
} else { // x is smaller or equalt to y  
  max = y;
  min = x; 
}  
System.out.print(max + " is greater than " + min);




int n, m, min, gcd = 1;
ConsoleReader c; 
c = new ConsoleReader(System.in);
System.out.print("Please enter the first number: "); 
n = c.readInt(); 
System.out.print("Please enter the second number: "); 
m = c.readInt(); 
int div = 1; 
min = Math.min(n, m); 
while (div <= min) { 
  if (n % div == 0 && m % div == 0) {
    gcd = div; 
  } 
  div = div += 1; 
}  
System.out.print("The greatest common divisor of "); 
System.out.println(n + " and " + m + " is " + gcd); 


But we have seen examples of these already.

The for loop.

Take the example of last time:

class One {
    public static void main(String[] args) {

        int balance;
        balance = 0; 

	ConsoleReader c = new ConsoleReader(System.in); 
        System.out.print("Type something: "); 
        String user;
        user = c.readLine(); 

        int number; 

	while (! user.equals("bye")) { 
            number = Integer.parseInt(user); 

            balance = balance + number; 

            System.out.println("The current balance is: " + balance); 
            System.out.print("Type something: "); 
            user = c.readLine();
          
        } 

    }
}
We could easily describe the while loop as follows:
for (user = c.readLine(); ! user.equals("bye"); user = c.readLine()) {
    number = Integer.parseInt(user); 

    balance = balance + number; 

    System.out.println("The current balance is: " + balance); 
    System.out.print("Type something: "); 
} 

We described this in general, and will be posting a few more examples here soon.


Last updated by Adrian German for A201/A597/I210 on Fri Feb 11 19:24:14 EST 2005