Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Loops Review

2 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.

3 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

4 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++)

5 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.

6 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.

7 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);

8 Example int k = 0; while(k < 50) { k = (int)(Math.random()*100); System.out.println(k); }

9 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.

10 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.

11 Exercise 3 Use a double for loop to display the following 1089765


Download ppt "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."

Similar presentations


Ads by Google