120 likes | 240 Vues
Counter-Controlled Loops. CSIS 1595: Fundamentals of Programming and P roblem Solving 1. Counter-Controlled Loops. Often execute loop specific number of times Fixed number (counting from 1 to 10) Number specified by user Algorithm to execute loop number times
E N D
Counter-Controlled Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1
Counter-Controlled Loops • Often execute loop specific number of times • Fixed number (counting from 1 to 10) • Number specified by user • Algorithm to execute loop number times • Variable keeps track of number of times loop executed • Initialize variable to 1 before loop • Increment variable by 1 inside loop body • Loop while variable < number + 1 counter = 1 while counter < number + 1: statements inside loop counter += 1
For Loops • Built-in statements specifically for counter loops • Syntax to execute loop numbertimes: for counter in range(1, number + 1) statements inside loop • counter variable: • Automatically set to 1 at start of loop • Automatically incremented each time through loop • Loop continues while counter < number + 1
Example: Counting from 1 to 10 • Must use 11 as top of range to count to 10 • Note that increment by 1 done automatically
User-Controlled Counters • Often prompt user for how many times to execute loop
Using Counters in Loops • Often use counters to create tables • For each value of the counter, compute and print some value • Often separate multiple things on same line separated by tab • Tab printed as “\t” • Example: Print the square roots of the first 20 integers
The range Function • General form: for counter = range(start, end, increment) • counterinitialized to start • Loop continues as long as counter<end • counterincremented by incrementeach time through loop • If less than 3 parameters, default values used • range(start, end) increment = 1 • range(end) increment = 1, start = 0
Example: Tax Table • Goal: Print table with tax for all incomes from 2000 to 50000 (and no dependents) in increments of 2000 • Algorithm: • Print “header” with “Income” and “Tax” • Loop income in range 2000 to 50001 with 2000 as increment • Inside loop: • Compute tax on that income based on deduction and tax brackets • Print the income and the tax separated by tab
Multiple Exit Conditions • Some loops have multiple ways to exit • Example: Ask for guesses until user guesses correctly or makes 3 incorrect guesses • While condition in terms of multiple conditions • Guess != number • Guesses < 3 • May need additional if statement (either in or after loop) if different exit conditions require different responses