Lecture Notes, class 5 for csc211.

Prepared by: Anthony Larrain

These notes serve as an outline to the lecture, they are not intended to be complete. You should be reading the assigned sections. During class I may include or omit certain topics.


The while Statement

Recall three ways to alter flow of control

while( condition )
{
   // Execute this block while the condition is true.
}

Examples using while loop.

// Prints the numbers 1 to and including 10
int i = 1;
while( i <= 10 )
{
   System.out.println( i );
   i += 1;        // Same as i = i + 1;
 }
 
 // Count down from 100, stop at 1

int i = 100;
while( i > 0 )
{
   System.out.println( i );
   i -= 1;                      // Same as i = i - 1;
}

// Print the numbers 1 to 100 except 50;

int i = 1;
while( i <= 100 )
{
   if ( i == 50 )
     ++i;
   System.out.println(i);
   ++i;
}


More on if - else


Logical Operators

Simple boolean expressions can be joined together using the relational operators. A simple boolean expression consists of two operands and one relational or equality operator.

!    -- NOT
&&   -- AND
||   -- OR

NOT has the highest precedence of the Logical operators, followed by AND then by OR. The logical operators have lower precedence than the relationaloperators.

if( age > 12 && age < 20)
    Your a teen

if( result == 7 || result == 11 )
    you won

boolean value = false;
if( !value )
   value is false

if( score >= 0 && score <= 100)
  valid score


Increment and Decrement Operators


More Operators

Characters

Question

What is the difference between ..

'F'  AND  "F"  

Example 1

This program will assign a letter grade to an average

import java.util.Scanner;
class Grade {
	public static void main(String [] args){
		Scanner readScore = new Scanner(System.in):
		
		System.out.println("Enter you final average");
		int avg = readScore.nextInt();
		
		char grade;
		if(avg >= 90){
			grade = 'A';
		}
		else if(avg >= 80){
			grade = 'B';
		}
		else if(avg >= 70){
			grade = 'C';
		}
		else if(avg >= 60){
			grade = 'D';
		}
		else{
			grade = 'F';
		}
		
		System.out.println("Your grade is " + grade);
	}
}

Example 2

Same as example 1, except braces are removed.

import java.util.Scanner;
class Grade {
	public static void main(String [] args){
		Scanner readScore = new Scanner(System.in):
		
		System.out.println("Enter you final average");
		int avg = readScore.nextInt();
		
		char grade;
		if(avg >= 90)
			grade = 'A';
		else if(avg >= 80)
			grade = 'B';		
		else if(avg >= 70)
			grade = 'C';		
		else if(avg >= 60)
			grade = 'D';		
		else
			grade = 'F';
			
		System.out.println("Your grade is " + grade);
	}
}

Increment and Decrement Operators