# Loops

• We will now start on the last of the control structures
• There are three different looping structures
• We will look at the while loop in chapter 6.
• We will pick up the for and do .. while loops in chapter 7.
• The while loop
• Syntax: while (boolean expression) statement;
• Semantics:
• Evaluate the boolean expression
• If the value of the boolean expression is false, exit the loop
• If the value of the boolean expression is true, execute the statement and return to the top of the loop.
• Preferred use
while (boolean expression) {
statement;
} 
• Phases of loop execution
• Loop Initialization: the code before the loop where the variable(s) which control the loop are initialized.
• Loop Test: The point at which the boolean expression is evaluated to determine if the body of the loop is executed.
• Loop Entry: the first statement inside the body of the loop
• Iteration: An individual pass through the body of the loop.
• Termination: When the boolean expression becomes false and the loop exits.
• The termination condition
• All loops should be built so that the boolean expression can become false.
• All loops should make progress or get closer to the boolean condition becoming false.
• A loop where these conditions are not met is called an infinite loop .
• ctrl-c, ctrl-z
• You should not have infinite loops in your code.
• A variable which is used in the termination condition to control the loop is called a loop control variable
• This is about the only condition when it may be acceptable to use i,j,k ... as variables.
• To make a successful loop
• Initialize the loop control variable
• Build a test on the loop control variable that can eventually become false.
• Add a statement to the body of the loop which changes the loop control variable to get closer to the termination condition.
• Some loops to write.
• Print out the first 10 integers, 1 to 10
• Print out the first n integers, as specified by the user.
• Print the integers from n to 1 as specified by the user.
• Given two integers, m and n, print the integers between m and n
• some string functions.
• From chapter 3.
• If s is a string
• s.size() gives us the size of the string
• so does s.length()
• s.at(n) gives us the letter at position n in the string (0 ≤ n < s.size())
• Note, positions start at 0, not 1
• this can be done with s[n] as well.
• if s.at(n) or s[n] is used on the LHS, an assignment takes place.
• int toupper(int) and int tolower(int) will convert an alphabetic character to the proper case.
• Review int isascii(int c)
• Some more loops to write
• Print out a string one character at a time.
• Convert a string to lower case characters, upper case characters.
• Print a string backwards
• Print the non-alphabetic characters in a string.
• Write a program which given an integer n and a base b, 2 ≤ b < 11, prints the number n in base b.
• Algorithm?
• Test data?
• Tests for valid bases?
• Tests for conversion?
• converter.cpp