38
Introduction to Computers and Programming Lecture 7:

Introduction to Computers and Programming Lecture 7:

  • View
    226

  • Download
    3

Embed Size (px)

Citation preview

Page 1: Introduction to Computers and Programming Lecture 7:

Introduction to Computers and Programming

Lecture 7:

Page 2: Introduction to Computers and Programming Lecture 7:

First MidtermMarch 7th

• I will tell you the exact material covered in the coming classes.

• I will also talk about the format of the exam.• There will be no make up exam so your attendance is

mandatory.

Page 3: Introduction to Computers and Programming Lecture 7:

Road map

• char data type

Page 4: Introduction to Computers and Programming Lecture 7:

Review

• True or False: An int variable can contain any integer.

• When must you use an if / else if / else statement instead of using a switch statement?

• When is it preferable to use a switch statement?• What is a magic number? How should you deal

with a magic number? Why?• Explain what the exclusive or (^) operator tests.

(exp a) ^ (exp b)

• Define the purpose of each part of this expression:

(part a) ? (part b) : (part c)

Page 5: Introduction to Computers and Programming Lecture 7:

Review continued

• What is the output of the following code fragment?

int a = 100, b = 50;

if ((a == 60) && (b <= 100))

System.out.println ("Yes");• What is the output of the following code

fragment?

int a = 100, b = 50;

if ((a == 60) || (b <= 100))

System.out.println ("Yes");

Page 6: Introduction to Computers and Programming Lecture 7:

Review continued

• What is the output of this switch statement?int a = 90;switch (a){case 80:System.out.println (80);

case 90:System.out.println (90);

case 100:System.out.println (100);

}

Page 7: Introduction to Computers and Programming Lecture 7:

char data type

Page 8: Introduction to Computers and Programming Lecture 7:

char data type

• Java allows us to store "single" character values.• char character = 'a'; // not the same as "a";• char character = '7';• char newline = '\n';• char tab = '\t';• char space = ' ';• The characters are actually stored as integers (ascii values).• See http://asciitable.com/

• Note: chars use single quotes. We have seen that Strings use double quotes.

Page 9: Introduction to Computers and Programming Lecture 7:

ASCII Table

Source: Liang

Page 10: Introduction to Computers and Programming Lecture 7:

char arithmetic

• Given:

char letter = 'a';• The following code:

letter = (char) (letter + 1);• Would result in letter storing a 'b' character.• If we add or subtract two char values, the result is

an int value.– For example 'c' – 'a' would result in the value 2.

Page 11: Introduction to Computers and Programming Lecture 7:

Casting between char and int values

• A char uses 16 bits of memory. – You can implicitly cast a char to an int

char c = 'a';

int i = c;– You must explicitly cast an int to a char

int i = 65;

char = (char) i;

• Note: Even though chars are equal to shorts in the amount of memory they use, they do not hold the same values (shorts can hold negative numbers).

Page 12: Introduction to Computers and Programming Lecture 7:

Reading char values from the user

• You should use charAt(0) to parse the character from user input.

• For example:char c;

String cAsString;

cAsString = JOptionPane.showInputDialog (null, "Enter a character");

c = cAsString.charAt(0);

• Will grab the first character from the user's input.

Page 13: Introduction to Computers and Programming Lecture 7:

Warning about numeric digit characters

• The value of a the single digit numeric characters are not equivalent to the values themselves. In fact the ASCII value of '0' is 48, '1' is 49, …, '9' is 57.

• How do you think we could convert a numeric char to an int?

Page 14: Introduction to Computers and Programming Lecture 7:

Unicode

• In Java, there are many more characters available then in the basic ascii table.

• The ascii table only has 128 characters in it.• Java uses 2 bytes to store characters which allows it to

hold 65536 unique characters.• Java can store any Unicode (see: unicode.org) character in

a char variable. • That means you can print any character from any language

on any platform.• To print a Unicode character, use '\uxxxx' where xxxx is a

hexadecimal representation of the Unicode for the desired character.

Page 15: Introduction to Computers and Programming Lecture 7:

Assignment Operators

• Given the following:

x = 2;

x = x + 1;

System.out.println ("x: " + x);• There are actually several ways to rewrite this

more concisely.

Page 16: Introduction to Computers and Programming Lecture 7:

Short Cut Operator

• One option is to use the += operator

x = 2;

x += 1; // same as x = x + 1;

System.out.println ("x: " + x);• There are similar operators for *, -, /.%

– x = x * 5 is equivalent to x *= 5;– x = x – 5; is equivalent to x -= 5;– x = x / 5; is equivalent to x /= 5;– x = x % 5; is equivalent to x %= 5;

• Good Practice: place a space before and after your short cut operators.

Page 17: Introduction to Computers and Programming Lecture 7:

Increment Operator

• A second option is to use an increment operator:

x++ Post-Increment Operator

++x Pre-Increment Operator• Both operators will increment x by 1, but they do

have subtle differences.

Page 18: Introduction to Computers and Programming Lecture 7:

Pre v. Post Increment

• PostIncrement Operator (x++):– use the current value of x in the expression.

Then, increment by 1.• PreIncrement Operator (++x):

– Increment x by 1. Then, use the new value of x in the expression.

Page 19: Introduction to Computers and Programming Lecture 7:

How about a real example?

// Preincrementing v. PostIncrementing public class PrePost{

public static void main (String[] args){

int c = 5;System.out.println (c);System.out.println (c++);System.out.println (c);System.out.println();c = 5;System.out.println (c);System.out.println (++c);System.out.println (c);

}}

Output:

5

5

6

5

6

6

Post Increment

Pre Increment 2000 Prentice Hall, Inc. All rights reserved. Modified by Evan Korth

Page 20: Introduction to Computers and Programming Lecture 7:

Pre v. Post Decrement

• PostDecrement Operator (x--):– use the current value of x in the expression.

Then, decrease by 1.• PreDecrement Operator (--x):

– Decrease x by 1. Then, use the new value of x in the expression.

• Good practice: Place unary operators directly next to their operands, with no intervening spaces.

Page 21: Introduction to Computers and Programming Lecture 7:

Introduction to While Loops

Page 22: Introduction to Computers and Programming Lecture 7:

While Loops

• While Loop: Keep repeating an action while some condition remains true.

• Examples:– Every Stairmaster Machine contains a while

loop (end condition is based on mode used).• while the person is still climbing, keep

displaying the status, e.g. number of stairs climbed, calories burned, etc.

– Keep prompting for book orders until the user is done.

Page 23: Introduction to Computers and Programming Lecture 7:

while loop (continued)

• For example (in pseudocode)

while (some Boolean expression is true)

{ do this (again and again...)

}

Page 24: Introduction to Computers and Programming Lecture 7:

Parts of a While Loop

• Every while loop will always contain three main elements:

1) Priming: initialize your variables.

2) Testing: test against some known condition.

3) Updating: updates part (or all) of the expression that is tested.

Page 25: Introduction to Computers and Programming Lecture 7:

Simple While Loop

public class While1{

public static void main (String args[]){ int index = 1; while (index <= 10) {

System.out.println ("Index: " + index);index++;

}}

}

Index: 1

Index: 2

Index: 3

...

Index: 8

Index: 9

Index: 10

1. Priming

2. Test Condition

3. Update: In this case, you can use either the pre or post increment operator.

Page 26: Introduction to Computers and Programming Lecture 7:

While Loop Flowchart

1. Priming

Set index=1

2. Test

index

<= 10

3. Print value of index

Update index++

TRUE

FALSE

Page 27: Introduction to Computers and Programming Lecture 7:

Infinite Loop

• Infinite Loop: A loop that never ends.– Generally, you want to avoid these!– There are special cases, however, when you do

want to create infinite loops on purpose.• Common Exam Questions:

– Given a piece of code, identify the bug in the code.

– You may need to identify infinite loops.

Page 28: Introduction to Computers and Programming Lecture 7:

Infinite Loop Example #1

public class While2{

public static void main (String args[]){ int index = 1; while (index <= 10) {

System.out.println ("Index: " + index); }}

} Here, I have deleted part 3:

The update statement (index++).

Index: 1

Index: 1

Index: 1

Index: 1

Index: 1

… [forever]

Page 29: Introduction to Computers and Programming Lecture 7:

Infinite Loop, Example #2

public class While3{

public static void main (String args[]){ int index = 1; while (index >= 0) {

System.out.println ("Index: " + index);index++;

}}

}

Here, I have changed

Part 2: the test

condition.

Index: 1

Index: 2

Index: 3

Index: 4

Index: 5

… [forever]

Page 30: Introduction to Computers and Programming Lecture 7:

While Loops: Examples

Page 31: Introduction to Computers and Programming Lecture 7:

While Loop Example

• Specification for the program:– Find the first power of 2 larger than 1000.

• For example: 2, 4, 8, 16, 32, etc. are powers of 2.– Which is the first power of 2 larger than 1000?

– Finding the answer to this requires some kind of a while loop.

– Let’s see how…

2000 Prentice Hall, Inc. All rights reserved. Modified by Evan Korth

Page 32: Introduction to Computers and Programming Lecture 7:

While Loop Example

• Example: int product = 2;

while ( product <= 1000 )product = 2 * product;

product <= 1000 product = 2 * producttrue

false

2000 Prentice Hall, Inc. All rights reserved.

Page 33: Introduction to Computers and Programming Lecture 7:

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

int product = 2;while ( product <= 1000 )

product = 2 * product;

System.out.println (product);}

}

2000 Prentice Hall, Inc. All rights reserved.

Page 34: Introduction to Computers and Programming Lecture 7:

Counter-Controlled Repetition

• Counter-controlled repetition– Loop repeated until counter reaches a certain value

– Definite repetition: number of repetitions is known

– Example: A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz

2000 Prentice Hall, Inc. All rights reserved.

Page 35: Introduction to Computers and Programming Lecture 7:

4.8 Formulating Algorithms: Case Study 1 (Counter-Controlled

Repetition)• Counter

– Variable that controls number of times set of statements executes

• Average1.java calculates grade averages– uses counters to control repetition

2003 Prentice Hall, Inc. All rights reserved.

Page 36: Introduction to Computers and Programming Lecture 7:

 Set total to zeroSet grade counter to one

While grade counter is less than or equal to tenInput the next gradeAdd the grade into the totalAdd one to the grade counter

Set the class average to the total divided by tenPrint the class average

Fig. 4.6 Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.

2003 Prentice Hall, Inc. All rights reserved.

Page 37: Introduction to Computers and Programming Lecture 7:

1 // Fig. 4.7: Average1.java2 // Class-average program with counter-controlled repetition.3 import javax.swing.JOptionPane;4 5 public class Average1 {6 7 public static void main( String args[] ) 8 {9 int total; // sum of grades input by user10 int gradeCounter; // number of grade to be entered next11 int grade; // grade value12 int average; // average of grades13 14 String gradeString; // grade typed by user15 16 // initialization phase17 total = 0; // initialize total18 gradeCounter = 1; // initialize loop counter19 20 // processing phase21 while ( gradeCounter <= 10 ) { // loop 10 times22 23 // prompt for input and read grade from user24 gradeString = JOptionPane.showInputDialog(25 "Enter integer grade: " );26 27 // convert gradeString to int28 grade = Integer.parseInt( gradeString );29

2003 Prentice Hall, Inc. All rights reserved.

Page 38: Introduction to Computers and Programming Lecture 7:

30 total = total + grade; // add grade to total31 gradeCounter = gradeCounter + 1; // increment counter32 33 } // end while34 35 // termination phase36 average = total / 10; // integer division37 38 // display average of exam grades39 JOptionPane.showMessageDialog( null, "Class average is " + 40 average, Class Average", JOptionPane.INFORMATION_MESSAGE );41 42 System.exit( 0 ); // terminate the program43 44 } // end main45 46 } // end class Average1

2003 Prentice Hall, Inc. All rights reserved.