This preview shows pages 1–2. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: 10
There were 3 numbers. 7. Read a series of positive integers from the keyboard. Keep reading until the user enters a negative number.
Report the number of odd values entered (use %2 to determine if a value is odd or even). 10
There were 3 odd numbers. 8. Read exactly seven integers from the user. Report the sum of the numbers and the number of even numbers.
Also report the sum of the odd numbers and the sum of the even numbers. 12 3O 6O 31 9O 11 15 Even numbers: 4
Even sum: 192
Odd numbers: 3
Odd sum: 57 9. Generate ten random numbers in the range 1 to 100. Report the number of values that were 50 or greater (print
them to the console). 76
80 10. Generate random numbers in the range 1 to 10. Keep generating the numbers (and printing them out) until the
value seven is generated. Stop the program once a seven is generated. 00K)ng ll. Generate random numbers in the range 1 to 10. Keep generating the numbers (and printing them out) until the
value seven is generated. Stop the program once a seven is generated. Report the number of numbers generated
and rint the sum of those numbers. 9
There were 2 numbers, for a total of 12. Solutions to selected exercises. Some Extra Problems If you are eager to try a few more looping problems, then here are a few more.
The for Loop
The number of iterations of a counting loop can be determined from its starting value, ending value, and the amount size of the increment. For example, this loop starts at one, ends at ten, and increments by one -- it will have exactly ten
iterations: int i = l; // start at 1 while (i <: 10) // end at 10 i
// ... do something here ...
i++; // increment by 1 l A common shorthand for a counting loop is the for loop. The for loop pulls the starting, ending, and increment values
onto one line: for (int i = l; i <= 10; i++)
i // ... do something here ... } Even though these three features appear on one line, they take their affect exactly in the places shown in the while
loop at the start of this section. This for loop behaves exactly like the while loop shown above. Experienced
programmers often use the for loop because it compactly describes the core features of a counting loop. gm - About Us Copyright © 2006 by Kiowok, Ann Arbor, Michigan, USA ...
View Full Document
- Summer '08