80 likes | 224 Vues
This lesson focuses on nested control structures in Java, demonstrating how to calculate the sum and average of user inputs. We will explore while loops and if statements for effective nesting. The example illustrates a while loop that collects five integer inputs, computes their sum, and calculates the average. Additionally, we analyze how to implement nested loops and conditional statements to diversify program behaviors. You will also work on a guessing game project to reinforce these concepts. Master these techniques for your upcoming assessments.
E N D
Calculating the sum or average int sum = 0; int k = 0, num; while ( k < 5) { num = scan.nextInt(); sum = sum + num; k = k + 1; } ...println("sum is " + sum); ...println("avg is " + sum/5.0);
Nesting • The idea of nesting is to put one thing inside of another: • nested: ( [ { } { } ] { } ) • not nested: ( ) [ ] { } [ ] • NOT nested: ( [ { ) ] }
Nesting control structures • We have seen several control structures • do loops • while loops • if statements (including compound if statements with else if and else ) • We can nest any of these structures inside another to get different behaviors
While loop with if inside int i = 0; while ( i < 3) { if ( i == 0) { ...println("zero"); } else { ...println( i ); } i = i + 1; }
While loop with if inside int i = 0, big=0, num; while ( i < 5) { num = scan.nextInt(); if ( num > 50) { big = big+1; } i = i + 1; } ...println("number of big: " + big);
Work on Loop Drills in class • Due next Tuesday • you may finish today • these are exam style questions so make sure you master them
Lab 5 • Guessing Game • pick a random number and store it • Do Loop: • get user guess • if guess is high or low, say it • when guess is correct leave loop