Nested Loops, Break/Continue
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
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 }
Nested While Loops Careful with init/update for while loops – Broken Attempt
Fixed Whiles Outer loop works with i Inner with j – reset each time
Multiplication Table Print this table:
Multiplication Table Look for patterns – Have to work in rows
Header
Body
Break Complex exit conditions can get ugly:
Break Break exits a loop – Use CAREFULLY to avoid complex conditions
Continue Continue skips rest of loop body
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; } }
Continue With While, must still update! int i = 0; while(i < 10) { if( i == 5 ) { i++; //infinite loop without! continue; } cout << i; i++; }
Prime Finder Find/Count primes <= n
Starting Point Possible primes: 2…n
Starting Point All numbers 2…n
Starting Point All numbers 2…n Only print primes… – Not divisible by anything in range 2-(number-1)
Starting Point Only print primes… – Not divisible by anything in range 2-(number-1)
Merged Code
Counting Need to count the primes
Counting Need to count the primes
Limiting line width Limit to 10 numbers per line – Need new counter – Increment at each print – When hits 10: Print newline Reset counter
Limiting line width Limit to 10 numbers per line – Need new counter – Increment at each print – When hits 10: Print newline Reset counter
Optimization No need to keep going if we find a factor
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
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