Download presentation
Presentation is loading. Please wait.
Published byViolet Anderson Modified over 8 years ago
1
Nested Loops, Break/Continue
2
Nested Loops Nested loops : loop inside a loop – Loop through rows and columns – Loop through every word in every file – Loop through every number less than every number less than 100
3
Nested Loop Regions Regions for nested loops: – With row major ordering //values available through every row/col for/while each row { //start row //values that start over for each row for/while each value in row { one "cell" } //end row }
4
Nested While Loops Careful with init/update for while loops – Broken Attempt
5
Fixed Whiles Outer loop works with i Inner with j – reset each time
6
Multiplication Table Print this table:
7
Multiplication Table Look for patterns – Have to work in rows
8
Header
9
Body
10
Break Complex exit conditions can get ugly:
11
Break Break exits a loop – Use CAREFULLY to avoid complex conditions
12
Continue Continue skips rest of loop body
13
Continue Keep special case special, normal case normal GoodLess Good for(int i = 10; i >= 1; i--) if( i == 5 ) continue; cout << i; } for(int i = 10; i >= 1; i--) if( i != 5 ) { cout << i; } }
14
Continue With While, must still update! int i = 0; while(i < 10) { if( i == 5 ) { i++; //infinite loop without! continue; } cout << i; i++; }
15
Prime Finder Find/Count primes <= n
16
Starting Point Possible primes: 2…n
17
Starting Point All numbers 2…n
18
Starting Point All numbers 2…n Only print primes… – Not divisible by anything in range 2-(number-1)
19
Starting Point Only print primes… – Not divisible by anything in range 2-(number-1)
20
Merged Code
21
Counting Need to count the primes
22
Counting Need to count the primes
23
Limiting line width Limit to 10 numbers per line – Need new counter – Increment at each print – When hits 10: Print newline Reset counter
24
Limiting line width Limit to 10 numbers per line – Need new counter – Increment at each print – When hits 10: Print newline Reset counter
25
Optimization No need to keep going if we find a factor
26
Other Optimizations No need to test evens – Include 2 always – Start from 3 and count by 2's Only go up to sqrt(n) Use a better algorithm
27
Optimizations Premature optimization is the root of all evil – Code a correct solution first – Take obvious measures to speed code – If needed, fix bottlenecks – High level optimizations trump low level ones
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.