- In general, we will use "while" when the iterative part might never repeat (eg, when reading a file: if the file is empty, there is no data to read).
- Similarly, we will use "do...while" when it should be repeated at least once (for example, to enter a password, which should be asked at least once, perhaps more times).
- And about "for", it is equivalent to a "while", but its usual syntax makes it especially useful when we know exactly how many times we want to repeat (for instance, 10 times might be: "for (i=1; i<=10; i++)").
Suggested exercises:
- Create a program in which the user must guess a number from 1 to 100 (which is preset in the program) using a maximum of 6 attempts. Each pass it must tell the uses if the entered number is too big or too little.
- Create a program that expresses a number (entered by the user) as a product of its prime factors. For example, 60 = 2 • 2 • 3 • 5
- Create a program which raises a number to another, using consecutive multiplications.
No comments:
Post a Comment