Download presentation
Presentation is loading. Please wait.
Published byRosa Byrd Modified over 8 years ago
1
Loops
2
Review Control Structure – making decisions if-statement Program Design Understand what you want to do Design your solution Write and test your code Consider alternatives
3
Overview Loops Array basics
4
Loops A loop enables you to repeat a series of commands in your program. There are a few different types of loop structures, but will focus on the while loop today. A loop must have the following three components: A sentry or guard that will stop the program from repeating. This is called a condition. A block of code to repeat. A way to make the condition false.
5
While loop format int i = 0; while ( i<10 ) { System.out.println(i); i=i+1; } System.out.println(“Done!”); Condition – like an if-statement. Some type of true/false question Curly braces – form a box that has the lines of code you want to repeat. Increment/decrement – will increase/decrease the value of i so that the condition will become false To Do: copy this code into your TestMe class. Compile & execute. What happens?
6
Exercise Modify the code you just wrote so that the loop will count backwards.
7
Array Basics Variables hold single values An array can hold multiple values of the same type. It is like a list. For example, a list of grades or characters in a word. Each line in the array is called an ‘element’ double gradeschar charactersInWord 99.0 85.6 68.1 79.6 ‘p’ ‘e’ ‘a’ ‘c’ ‘e’
8
Array Basics How do you assign or retrieve values? Every element is identified by a unique number called an index. The index always starts with 0 and increases by 1 until the end of the list. The array has a length with represent how many elements it contains double gradeschar charactersInWord 099.0 185.6 268.1 379.6 0‘p’ 1‘e’ 2‘a’ 3‘c’ 4‘e’ Length = 4 Length = 5
9
Hangman Game A game that Reads a user’s guess Checks to see if the guess is a character in the hidden word If it is then the character replaces each mask character in position. If the player guesses a wrong character then the hangman is advanced one body part at a time. If the player misses 6 guesses they lose. If the player guesses the word within 6 wrong guesses, then they win.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.