Do-While Loops

advertisement
For Loops
• For loops are usually the preferred loop among
programmers, although in certain situations, other
loops are more appropriate.
• In a for loop, initialization, condition, and
increment/decrement are all taken care of with
one line of code
1
2
3
• Syntax:
for (initialization; condition; increment/decrement)
{
// loop body
}
• Demo: ForLoopDemo
• Sometimes, one or more of the three
components of a for loop will be empty. (see
demo)
Assignments
•
(ForLoops) Use one for loop for each task, with line breaks in between:
– Display the numbers 55 to 61
– Display every 5th number from 40 to 75 (except 65)
– Display numbers backwards from 2 to -4 (except 0)
– Have the user enter a word. Display each letter of the word on separate lines.
•
(ForCounter)
– Have the user type a sentence.
– Error check – with a while loop: must be at least 10 characters, at most 25, AND
must contain at least 2 words
– Next, Using a for loop, display each character of the sentence (including spaces) on
a separate line.
– Display the number of times that any letters from your own first name are in the
sentence
– Display how many times the letter e is in the sentence
– Display whether this # is a multiple of 3
– Display every character from the 3nd letter to the 2nd-to-last, on the same line
– Display the names of the four Golden Girls (the characters, not the actresses).
Download