Chapter IV Part I

Chapter IV Part I - Loops IT108 George Mason University...

Info iconThis preview shows pages 1–8. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Loops IT108 George Mason University Relational operators - Review § § Operators: ==, !=, <, >, <=, >= The comparison expression always produces a boolean value (x > 5) will have a value of true or false depending on the value of variable x. § Result of a relational expression can be used wherever a boolean variable can be used. Relational Operators A relational operator compares two values and determines the relationship between them. For example, != returns true if the two operands are unequal Operator Use Returns true if > op1 > op2 op1 is greater than op2 >= op1 < op2 op1 is greater than or equal to op2 < op1 < op2 op1 is less than op2 <= op1 <= op2 op1 is less than or equal to op2 == op1 == op2 op1 and op2 are equal != op1 != op2 op1 and op2 are not equal Boolean Operators - review Operator Use && op1 && op2 op1 and op2 are both true, conditionally evaluates op2 || op1 || op2 either op1 or op2 is true, conditionally evaluates op2 ! !op Returns true if op is false Incrementing and Decrementing Operator Use Description ++ op++ Increments op by 1; evaluates to the value of op before it was incremented ++ ++op Increments op by 1; evaluates to the value of op after it was incremented -- op-- Decrements op by 1; evaluates to the value of op before it was decremented -- --op Decrements op by 1; evaluates to the value of op after it was decremented Incrementing and Decrementing § § § Increment operator ++ x++ same as x = x + 1 (or x += 1) Decrement operator -x-- same as x = x - 1 (or x -= 1) Postfix versus prefix notation y = x++, first assign, then increment y = ++x, first increment, then assign Assignment Operators - Review § § You use the basic assignment operator, =, to assign one value to another The Java programming language also provides several shortcut assignment operators that allow you to perform an arithmetic, shift, or bitwise operation and an assignment operation all with one operator. i = i + 2; can also be written as i += 2; The above two statements are equivalent. Assignment Operators The following table lists the shortcut assignment for arithmetic operators and their lengthy equivalents: Operator += Use op1 += op2 Equivalent to op1 = op1 + op2 -= op1 -= op2 op1 = op1 - op2 *= op1 *= op2 op1 = op1 * op2 /= op1 /= op2 op1 = op1 / op2 %= op1 %= op2 op1 = op1 % op2 Assignment § Variable assignment is a form of expression. Its result is the assigned value. Ø § § x = y = z = 0 same as x = (y = (z = 0)) The right side of the assignment is always evaluated before the assignment takes place. Shorthand assignment operators Ø x += 2 same as x = x + 2 Ø x /= 2 same as x = x / 2 Loop Structure Loop- A structure that allows repeated execution of a block of statements Loop body- A block of statements; as long as the expression is true, the loop body executes Iteration- One execution of any loop Loop Choices Definite Loop • • #iterations known for loop Indefinite Loop • #iterations unknown (conditional) – – while loop – condition checked at top do/while loop – condition checked at bottom will always execute at least once Repetitions for Loops while Loops do-while Loops break and continue Using a for Loop for loop- A special loop that is used when a definite number of loop iterations is required Keyword for Set of parentheses Three sections within parentheses • • • Initializing the loop control variable Testing the loop control variable Updating the loop control variable for Loops for (initial-action; loopcontinuation-condition; actionafter-each-iteration) { // loop body; statement(s); } i=0 initial-action loopcontinuation -condition false int i; for (i = 0; i < 100; i++) { System.out.println( "Welcome to Java!"); } true statement(s); action-aftereach-iteration i<100 false true print(“welcome”) i++ Trace for Loop Declare i int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } MEMORY i=0 ???? int i CONSOLE true i<2 false print(“welcome”) i++ Trace for Loop, cont. Execute initializer i is now 0 int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } MEMORY i=0 0 ???? int i CONSOLE true i<2 false print(“welcome”) i++ Trace for Loop, cont. (i < 2) is true since i is 0 int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } MEMORY i=0 0 int i CONSOLE true i<2 false print(“welcome”) i++ Trace for Loop, cont. Print Welcome to Java int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } MEMORY i=0 0 int i CONSOLE Welcome to Java! true i<2 false print(“welcome”) i++ Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Execute adjustment statement i now is 1 MEMORY i=0 1 0 int i CONSOLE Welcome to Java! true i<2 false print(“welcome”) i++ Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } (i < 2) is still true since i is 1 MEMORY i=0 1 int i CONSOLE Welcome to Java! true i<2 false print(“welcome”) i++ Trace for Loop, cont. Print Welcome to Java int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } MEMORY i=0 1 int i CONSOLE Welcome to Java! Welcome to Java! true i<2 false print(“welcome”) i++ Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Execute adjustment statement i now is 2 MEMORY i=0 2 1 int i CONSOLE Welcome to Java! Welcome to Java! true i<2 false print(“welcome”) i++ Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } (i < 2) is false since i is 2 MEMORY i=0 2 int i CONSOLE Welcome to Java! Welcome to Java! true i<2 false print(“welcome”) i++ Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Exit the loop. Execute the next statement after the loop MEMORY 2 i=0 int i CONSOLE Welcome to Java! Welcome to Java! true i<2 false print(“welcome”) i++ Note The initial-action in a for loop can be a list of zero or more comma-separated expressions. The action-after-eachiteration in a for loop can be a list of zero or more commaseparated statements. Therefore, the following two for loops are correct. They are rarely used in practice, however. for (int i = 1; i < 100; System.out.println(i++)); for (int i = 0, j = 0; (i + j < 10); i++, j++) { // Do something } Note If the loop-continuation-condition in a for loop is omitted, it is implicitly true. for ( ; ; ) { // Do something } (a) Equivalent while (true) { // Do something } (b) Example: Average 5 assignments • • • • Calculate the average programming assignment grade (based on 5 assignments) for one student INPUT each of the 5 assignments grade OUTPUT averageGrade PROCESS • • • INPUT g1, g2, g3, g4, g5 Compute the averageGrade (g1+g2+g3+g4+g5 )/ 5 DISPLAY averageGrade Pseudo-code: Average 5 assignments • Calculate the average programming assignment grade (based on 5 assignments) for one student • INPUT each of the 5 assignments grade • OUTPUT averageGrade • PROCESS version 1 • • Compute the averageGrade (g1+g2+g3+g4+g5) / 5 • • INPUT g1, g2, g3, g4, g5 DISPLAY averageGrade PROCESS version 2 • • • SUM = 0 FOR each of the 5 assignements – INPUT grade – ADD grade to SUM DISPLAY SUM/5 Pseudo-code: Average 5 assignments Start Calculate the average programming assignment grade (based on 5 assignments) for one student • OUTPUT averageGrade • PROCESS version 2 i=0 INPUT each of the 5 assignments grade • sum=0 • • • false SUM = 0 FOR each of the 5 assignments – INPUT grade – ADD grade to SUM DISPLAY SUM/5 i<5 true DISPLAY sum/5 INPUT grade Stop sum=sum+grade i++ Program: Average 5 assignments package chapter04a; import javax.swing.JOptionPane; /** * Class example:Calculate the average programming assignment grade (based on 5 * assignments) for one student * @author Mihai Boicu */ public class Average5 { /** * Calculate the average programming assignment grade (based on 5 assignments) for one * student<br> * INPUT each of the 5 assignments grade <br> * DISPLAY the average grade * @param commandLineArguments NOT USED */ public static void main(String commandLineArguments) { • } } INPUT each of the 5 assignments grade • OUTPUT averageGrade • PROCESS version 2 • • • SUM = 0 FOR each of the 5 assignements – INPUT grade – ADD grade to SUM DISPLAY SUM/5 Program: Average 5 assignments public static void main(String commandLineArguments) { // the SUM of all grades double sum = 0; // for each of the 5 assignments for (int i = 0; i < 5; i++) { // INPUT the grade for the i'th assignment String gradeString = JOptionPane .showInputDialog("What is the grade for the assignment number " + i + "?"); double grade = Double.parseDouble(gradeString); // ADD the grade to the sum sum += grade; // sum = sum + grade } // DISPLAY the average JOptionPane.showMessageDialog(null, "The average grade for the assignments is: " + (sum / 5)); } int i=1 i is 0 (i+1) • INPUT each of the 5 assignments grade • OUTPUT averageGrade • PROCESS version 2 • • • SUM = 0 FOR each of the 5 assignements – INPUT grade – ADD grade to SUM DISPLAY SUM/5 Program: Average 5 assignments public static void main(String commandLineArguments) { // the SUM of all grades double sum = 0; // for each of the 5 assignments for (int assignment = 1; assignment <= 5; assignment++) { // INPUT the grade for the i'th assignment String gradeString = JOptionPane .showInputDialog("What is the grade for the assignment number " + assignment + "?"); double grade = Double.parseDouble(gradeString); // ADD the grade to the sum sum += grade; // sum = sum + grade } // DISPLAY the average JOptionPane.showMessageDialog(null, "The average grade for the assignments is: " + (sum / 5)); } • INPUT each of the 5 assignments grade • OUTPUT averageGrade • PROCESS version 2 • • • SUM = 0 FOR each of the 5 assignements – INPUT grade – ADD grade to SUM DISPLAY SUM/5 Example: CLASS AVERAGE • Build on that to calculate the class average for the programming assignments • INPUT N - number of assignments • INPUT each of the N assignments grade • OUTPUT average grade • PROCESS • INPUT N • SUM = 0 • • FOR each of the N assignements – INPUT grade – ADD grade to SUM DISPLAY SUM/N Flowchart: CLASS AVERAGE Start • INPUT N sum=0 i=0 • • false true Build on that to calculate the class average for the programming assignments INPUT N - number of assignments INPUT each of the N assignments grade DISPLAY sum/N Stop • INPUT grade sum=sum+grade i++ OUTPUT average grade • i<N PROCESS • INPUT N • SUM = 0 • • FOR each of the N assignments – INPUT grade – ADD grade to SUM DISPLAY SUM/N Program: CLASS AVERAGE public static void main(String commandLineArguments) { // INPUT the number of students String studentsString = JOptionPane .showInputDialog("Which is the number of students?"); double numberOfStudents = Double.parseDouble(studentsString); // the SUM of all grades double sum = 0; // for each of the students for (int student = 1; student <= numberOfStudents; student++) { // INPUT the grade for the i'th assignment String gradeString = JOptionPane .showInputDialog("What is the grade for the student number " + student + "?"); double grade = Double.parseDouble(gradeString); // ADD the grade to the sum sum += grade; // sum = sum + grade • INPUT N - number of students } // DISPLAY the average • INPUT each of the N students grade JOptionPane.showMessageDialog(null, "The average grade for the class is: " • OUTPUT average grade + (sum / numberOfStudents)); • } PROCESS • INPUT N • SUM = 0 • • FOR each of the N students – INPUT grade – ADD grade to SUM DISPLAY SUM/N Program: CLASS AVERAGE public static void main(String commandLineArguments) { // INPUT the number of students String studentsString = JOptionPane .showInputDialog("Which is the number of students?"); double numberOfStudents = Double.parseDouble(studentsString); // the SUM of all grades double sum = 0; // for each of the students for (int student = 1; student <= numberOfStudents; student++) { // INPUT the grade for the i'th assignment String gradeString = JOptionPane .showInputDialog("What is the grade for the student number " + student + "?"); double grade = Double.parseDouble(gradeString); // ADD the grade to the sum sum += grade; // sum = sum + grade } // DISPLAY the average JOptionPane.showMessageDialog(null, "The average grade for the class is: " + (sum / numberOfStudents)); } Example: Multiplication Table Problem: Write a program that uses nested for loops to print a multiplication table. INPUT: none OUTPUT: table PROCESS: • For A from 1 to 9 • For B from 1 to 9 – DISPLAY A*B Example: Multiplication Table Problem: Write a program that uses nested for loops to print a multiplication table. INPUT: none OUTPUT: table PROCESS: • message = “”; • For A from 1 to 9 • • • Message = message + A + “|”; For B from 1 to 9 – // DISPLAY A*B – message = message +” “+ (A*B) message = message + “\n” Example: Multiplication Table public static void main(String commandLineArguments) { // initialize the table String table = "MULTIPLICATION TABLE\n"; // add line with B values table += " | "; for (int b=1; b<=9; b++) { table += b +" "; } table += "\n"; // DISPLAY the table JOptionPane.showMessageDialog(null, table); } • • • • • INPUT: none OUTPUT: table PROCESS: message = “”; For A from 1 to 9 • Message = message + A + “|”; • For B from 1 to 9 • message = message +” “+ (A*B) • message = message + “\n” Example: Multiplication Table public static void main(String commandLineArguments) { // initialize the table String table = "MULTIPLICATION TABLE\n"; // add line with B values table += " | "; for (int b=1; b<=9; b++) { table += b +" "; } table += "\n"; // add separator line table += "------------------------------"; // add each line of the table • • • • • INPUT: none OUTPUT: table PROCESS: message = “”; For A from 1 to 9 • Message = message + A + “|”; • For B from 1 to 9 • message = message +” “+ (A*B) • message = message + “\n” Example: Multiplication Table public static void main(String commandLineArguments) { // initialize the table String table = "MULTIPLICATION TABLE\n"; // add line with B values table += " | "; for (int b=1; b<=9; b++) { table += b +" "; } table += "\n"; // add separator line table += "------------------------------\n"; // add each line of the table for (int a=1;a<=9;a++) { //add the header of the line table += a+" | "; for (int b=1;b<=9;b++) { //add the value a*b table+= a*b+" "; } //go to the next line table+="\n"; } // DISPLAY the table JOptionPane.showMessageDialog(null, table); • • • • • INPUT: none OUTPUT: table PROCESS: message = “”; For A from 1 to 9 • Message = message + A + “|”; • For B from 1 to 9 • message = message +” “+ (A*B) • message = message + “\n” Example: Multiplication Table public static void main(String commandLineArguments) { // initialize the table String table = "MULTIPLICATION TABLE\n"; // add line with B values table += "* | "; for (int b=1; b<=9; b++) { table += "0"+b +" "; } table += "\n"; // add separator line table += "------------------------------------------\n"; // add each line of the table for (int a=1;a<=9;a++) { //add the header of the line table += a+" | "; for (int b=1;b<=9;b++) { //add the value a*b if (a*b<10) table+="0"; table+= a*b+" "; } //go to the next line table+="\n"; } // DISPLAY the table JOptionPane.showMessageDialog(null, table); • • • • • INPUT: none OUTPUT: table PROCESS: message = “”; For A from 1 to 9 • Message = message + A + “|”; • For B from 1 to 9 • message = message +” “+ (A*B) • message = message + “\n” ...
View Full Document

This note was uploaded on 01/26/2012 for the course IT 108, 103, taught by Professor Bruno during the Spring '11 term at George Mason.

Page1 / 42

Chapter IV Part I - Loops IT108 George Mason University...

This preview shows document pages 1 - 8. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online