AP Computer Science Java: Lesson 3.3 Repetitive Statements - Counts and Sums |
|||||||||||
Let's take an example. Suppose we wish to know how many integer factors a number has. Recall that a factor of a number is an integer that divides evenly into that number. For example, the number 10 has 4 factors: 1, 2, 5, and 10. Let's look at a loop that can accomplish this task. Begin by declaring a counter variable, which we will call factors. A counter variable must be declared as an int since a count must be a whole number. Also, we initialize the counter as 0 since that is where we begin, with a count of nothing. int factors=0, number=10, loop; Here is the loop: for(loop=1; loop<=number; loop++) Let's examine this code. First note that the value of loop begins at 1 and ends at the number. Here this means we will check all numbers from 1 to 10 to see if they are factors of 10. When value of loop is 1, the condition number%loop==0 is true since the remainder of 12 divided by 1is 0. So the statement factors++ will enact. This statement means add one to factors. So factors is now 1. Now loop takes the value 2, which also divides into 10 evenly. So factors is now 2. The next value of loop is 3 which is NOT a factor of 10, so factors does not change. In the end, only four numbers are found to be factors of 10, so the variable factors is 4.
int sum=0, loop; Here is the loop: for(loop=1; loop<=100; loop++) Another example: Suppose we wish to find the total cost of a purchase of 5 items in which decimal values are involved. First, declare the variables: int loop; and now the loop... for(loop=1; loop<=5; loop++)
|
|||||||||||
© DanShuster.com