Loops GEEN163 Introduction to Computer Programming
Simplicity is prerequisite for reliability. Edsger W. Dijkstra
Programming Assignment A new programming assignment has been posted on Blackboard for this week The program requires you to write three programs from the given flowcharts Either problem 1 or problem 3 must be written with a GUI (but not both) Due by midnight on Friday, October 5
ZyBooks Reading Read chapter 7 of the online ZyBooks textbook Answer all of the participation questions in sections 7.1 through 7.9 Due by midnight on Thursday, October 4
One or the Other With an if else statement, either the if part or the else part are executed, but never both if ( logical expression ) { Executed only if true else { Executed only if false
nested if If the true part is another if, then it becomes a nested if if (cat == 3) else if (bull == 7) else x = 1; // cat is 3 and bull is 7 x = 2; // cat is 3 and bull is not 7 x = 3; // cat is not 3, bull doesn t matter
else if When the false part of an if-else is another if, it become an else if if ( cow > bull ) else dog = 5; if (cow == 0) dog = 3;
else if When the false part of an if-else is another if, it become an else if if ( cow > bull ) dog = 5; else if (cow == 0) dog = 3; // Java allows whitespace
One or maybe the Other With an else if statement, second if is evaluated only if the first if is false if ( logical 1 ) { Executed only if true else if ( logical 2 ){ Executed only if logical 1 is false and logical 2 is true
Connecting else to if An else statement is always related to the if of the previous block or statement if (cow == 3) if (bat == 7) dog = 1; // cow is 3 and bat is 7 else dog = 3; // cow is 3 and bat is not 7
What is displayed? int rabbit = 3, bunny = 5, hare = 7, pika = 9; if (rabbit < 4) if (bunny < hare) else pika = 2; pika = 6; System.out.println( pika ); A. 2 B. 4 C. 6 D. 9 E. none of the above
Conditional Assignment Java provides a little known method for putting an if statement in the middle of an expression logical expression? true part : false part dog = cat == 0? cow : goat; if cat is equal to zero, set dog to the value of cow, else set dog to the value of goat
Conditional Operator Example int cow= 3, cat = 5, dog = 7, goat = 17; dog = keyboard.nextint(); cow = (dog == 0? cat : goat) + 1; is the same as if (dog == 0 ) cow = cat + 1; else cow = goat + 1;
Conditional Used in a Method Call The conditional operator can be using almost any place an equation can be used System.out.println( "You "+ (score >= 50)? "pass" : "fail");
What is displayed? int wren = 2, robin = 5, hawk = 17; hawk = robin > 4? wren-1 : robin+ 2; System.out.println( hawk ); A. 1 B. 4 C. 7 D. 17 E. none of the above
Repeating Many programs do the same task many times Java provides several ways of creating a program loop while do while for
Java while statement A while statement is like an if statement that repeats until the logical expression is false int cat = 47, sum = 0; while (cat > 0) { cat = keyboard.nextint(); sum = sum + cat; System.out.println( sum );
Java while statement A while statement is like an if statement that repeats until the logical expression is false int cat = 47, sum = 0; while (cat > 0) { cat = keyboard.nextint(); sum = sum + cat; System.out.println( sum );
Loop Parts A while loop has a loop condition and a body The body is repeated while the loop condition is true while (loop condition ) { // loop body
while Flowchart comparison true false Do something
while loop operation When the program execution encounters a while statement, it will check the loop condition If the loop condition is false, the loop body will not be executed. Execution will continue with the statements after the loop body The body of the loop will be executed if the loop condition is true At the end of the body of the loop, the loop condition will be evaluated again. If it is true, the body of the loop will be executed again
{ Brackets A while loop can be written without curly brackets around the loop body Without brackets, the loop body will be the one statement following the loop condition It is recommended that you always use brackets
Example Program This is a program to display the average of a series of numbers. The end of the list of numbers is denoted by a value of zero You calculate the average by adding all the values and then dividing by the number of values
import java.util.scanner; public class LoopExample { public static void main(string[] junk) { double num, avg, sum = 0.0; int count = 0; Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number"); num = keyboard.nextdouble(); while (num!= 0.0) { sum = sum + num; count = count + 1; System.out.print("Enter a number"); num = keyboard.nextdouble(); avg = sum / count; System.out.println("The avg is " + avg);
Observations about the Program The program continues until a zero is read. The while loop checks for a zero We need to both sum the numbers and count how many numbers There was a priming read before the while and another read in the while loop body You should not divide until after the loop
Maybe Never The logical expression of a while loop is tested for the first time before the statement is executed If the logical expression is false the first time, the loop is never executed int hen = 5; while ( hen < 4 ) { hen = hen * hen; System.out.println( hen );// 5
A. 2 B. 4 C. 5 D. 8 What is displayed? int dog = 2, cat = 0; while ( cat < 3 ) { dog = dog + cat; cat = cat + 1; System.out.println( dog ); E. none of the above
Infinite Loops Many students have written programs with infinite loops. These programs have a loop that will repeat forever A program with an infinite loop will appear hung or stuck It is necessary that some statement inside a while loop modifies at least one of the variables used in the while statement s logical expression
Infinite Examples int cat = 5, bird = 7; while (bird > cat) { cow = bird + cat; while (bird > cat) { bird = bird + cat;
Looping a Specified Number of Times Frequently you may want your program to loop n times. int i = 1, n = 10; double principle= 10000.0; while (i <= n) { principle = principle * 1.05; i++; System.out.println("The value is "+ principle);
Looping a Specified Number of Times Computer scientist often count starting at zero int i = 0, n = 10; double principle= 10000.0; while (i < n) { principle = principle * 1.05; i++; System.out.println("The value is "+ principle);
What is displayed? int dog = 2, cat = 0; while ( dog > 0 ) { dog = dog + cat; cat = cat + 1; System.out.println(dog); A. 2 B. 4 C. 5 D. 8 E. none of the above
Caution The following loop is wrong because of the semicolon int i=0; Logic Error while (i < 10); { System.out.println("i is " + i); i = i + 1; 33
Flowchart Symbols while (dog == cat) dog = cat if( dog > 5 ) dog > 5 System.out.println(cow); goat = keyboard.nextint(); Output: cow input: goat
Flowchart to Find the Biggest
Java Program to Find the Biggest int number, biggest = 0; System.out.print("Enter a number >"); number = keyboard.nextint(); while (number!= 0) { if ( number > biggest ) { biggest = number; System.out.print("Enter a number >"); number = keyboard.nextint(); System.out.println("biggest is "+biggest);
Practice with your Team With the students around you, write a Java segment that sums all of the whole numbers from 1 to 47
Possible Solution int num = 1; int sum = 0; while (num <= 47) { sum = sum + num; num++;
Boolean Variables A boolean variable can be set to true or false or the result of a logical expression int x=3, y=5, z=7; boolean bat = true, bird = false; bird = x > y; bat = (x!= y) && (z > y); The expression is evaluated once and the boolean variable is then set to true or false Changing x,y or z will not change the value of the boolean variables after the above equations
What is displayed? int sum = 0, number = 47; while (sum < 100) { System.out.print("Enter a number >"); number = keyboard.nextint(); sum = sum + number; System.out.println( sum ); A. 0 B. 100 C. number greater or equal to 100 D. number less than 100 E. unknown
boolean variables in IF You can use a boolean variable in an if statement without a comparison. boolean problem = false; problem = true; if ( problem ) { System.out.println("look out");
boolean variable in a while boolean bear = true; int deer = keyboard.nextint(); while (bear) { // something if ( deer is weird ) bear = false; // some more stuff deer = keyboard.nextint();
boolean Methods A method can return a boolean (true or false) value boolean close(double cat, double dog) { if ( Math.abs(cat dog) < 0.01 ) { return true; return false;
A Shorter boolean Method A comparison results in a true or false value which can be returned boolean close(double cat, double dog) { return Math.abs(cat dog) < 0.01;
Using boolean Methods A boolean method can be used in an if double cobra = 0.666, mamba = 2.0 / 3.0; if ( close( cobra, mamba ) ) { System.out.println("same"); Other boolean methods include equals, equalsignorecase and others
boolean Variables Hold Logical Values A boolean variable can only hold the value true or false true and false are keywords, not strings, but they will print as strings int cat = 3, dog = 5; boolean fish = cat < dog; dog = -1; System.out.println("fish is "+ fish); will print fish is true
What is displayed? int cat = 11, dog = 5, cow = 7, goat = 1; boolean squid; squid = dog + cow == cat + 1; A. 1 dog = 3; if (squid ) B. 5 goat = 8; C. 8 else goat = 5; D. 12 System.out.println( goat ); E. none of the above
Input Validation Using a boolean int input; boolean good = false; while (!good ) { // repeat until good input System.out.println("Enter a number from 1-5"); input = keyboard.nextint(); if (input < 1 input > 5) { System.out.println("Pay attention!!"); else { good = true;
Thinking about programs If a program has to do something many times, it will need a loop The parts of the program that are not repeated will be outside the loop If a program does something different sometimes, the program will have an if statement
Write this in Java with your team good = 0 better = number good = better? yes display better good = better better = no good + number good 2
Complete the Program import java.util.scanner; public class Root { public static void main(string unused) { Scanner keyboard = new Scanner(System.in); int good = 0, better, number; System.out.print( Enter a number > ); number = keyboard.nextint(); // your Java here System.out.println( Answer is +better);
Possible Solution import java.util.scanner; public class Root { public static void main(string unused) { Scanner keyboard = new Scanner(System.in); int good = 0, better, number; System.out.print( Enter a number > ); number = keyboard.nextint(); better = number; while (good!= better) { good = better; better = (good + number/good) / 2; System.out.println( Answer is +better);
Summations in Mathematics In mathematics you can specify a sum as sum = which is equivalent to n i=1 1 2i sum = 1 2 + 1 4 + 1 8 + + 1 2n
Summations in Java We can write the same sum in Java n sum = i=1 1 2i double sum = 0.0; int i = 1, n = something; while ( i <= n ) { sum += 1.0 / (2.0 * i); i++;
Calculating Terms A more complex summation is e x = xi i=0 i! = 1 + x + x2 2! + x3 3! + The factorial of a number n is 1*2*3* *n In this summation next term = previous term * x i
Sum in Java double x, sum, next, i = 2.0; // set x to a value sum = 1.0 + x; // first two terms next = x; while ( next > 0.0001 ) { next = next * x / i; sum += next; i = i + 1.0; // until only small changes
What while sums the numbers from low to high? int sum = 0, low = 3, high = 12, num; num = low; // which while goes here { sum = sum + num; num++; A. while ( num <= high ) B. while ( low <= high ) C. while ( num > high ) D. while ( sum!= high )
Programming Assignment A new programming assignment has been posted on Blackboard for this week The program requires you to write three programs from the given flowcharts Either problem 1 or problem 3 must be written with a GUI (but not both) Due by midnight on Friday, October 5
ZyBooks Reading Read chapter 7 of the online ZyBooks textbook Answer all of the participation questions in sections 7.1 through 7.9 Due by midnight on Thursday, October 4