Loops Review

advertisement
Loops Review
How to generate random numbers
Math.random() will return a random decimal value in the form of a double.
double num1 = Math.random();
num1 = .6895421
If we want integer we need to typecast this thing
int num1 = (int)Math.random();
num1 = 0;  This is because integer conversion drops decimals
int num1 = (int)(Math.random()*100);
num1 = 69;  Multiply the 100 before conversion.
For loop
declaration | condition | iteration
for(int k = 0; k < 10; k++)
This is how this loop reads:
• Start integer k at 0.
• Loop continues as long as k is less than 10
• Increase the value of k by 1 every time you loop
For loop
for(int k = 0; k < 100; k++)
for(int k = 10; k < 10; k++)
for(int k = 0; k < 100; k += 5)
for(int k = 0; k > 5; k++)
While Loops
while(condition)
{
// body of code
}
Unlike a for loop which is an iteration loop, a while loop is a conditional
loop. It executes as long as the condition is true. The condition must
be a logical operation.
Do while Loops
do
{
// body of code
} while(condition);
Like a while loop, a do while loop is a conditional loop. However, a do
while loop will execute at least once before checking its condition.
Essentially, the do while loop checks its condition last.
Example
Scanner type = new Scanner(System.in)
int X = 0;
do
{
System.out.println(“Please enter a number”);
X = type.nextInt();
}while(X % 5 != 0);
Example
int k = 0;
while(k < 50)
{
k = (int)(Math.random()*100);
System.out.println(k);
}
Exercise 1
Write a while loop that generates random numbers between 0-100
repeatedly inside that loop. The loop stops when the number
generated is greater than 80 and is an even number.
Exercise 2
Ask user to input a value between 100-500. Get the squared root of
that number. Run a for loop as many times as that number. Display the
value of that number every time you loop.
Exercise 3
Use a double for loop to display the following
10
10
10
10
10
10
8
8
8
8
8
8
9
9
9
9
9
9
7
7
7
7
7
7
6
6
6
6
6
6
5
5
5
5
5
5
Download