Many students had difficulty figuring out how to code the number guessing game in class on Monday, Feb. 24.
You already know ALL of the building blocks of programming. This is (pretty much) everything:
- if statements
- loops (for and while)
So here is something else to think about:
An algorithm is like a recipe: a step-by-step process for performing some activity. You may look at an algorithm as the steps your program goes through to solve a problem. For example:
High Score Algorithm
- Game is over
- Compare player’s score to high score
- If player’s score is greater than the high score then the high score variable is reassigned the player’s score
- Display new high score
There are algorithms that exist for many common programming problems such as sorts and indexes. (source)
This is the problem-solving method you will need to develop. When I told you “break it down,” this shows one example of breaking down a problem that needs to be solved. What do I want to do? I want to tell the player if she has the high score. How do I find out of she has the high score? And so on.
You must first reason through the TASKS you want to do. THEN think about the code you will need to write to make it happen.
Imagine a dice-throwing game: Any player who gets doubles will win.
- Player throws two dice.
- Computer throws two dice.
- Did both get doubles? (What happens?)
- Did only one get doubles? (What happens?)
- Did no one get doubles? (What happens?)
Now, the algorithm:
- Throw two dice for the player. Save two numbers, possible 1 through 6 for each.
- Throw two dice for the computer. Save two numbers, possible1 through 6 for each.
- Compare two faces of the player’s dice to check for doubles.
- Compare two faces of the computer’s dice to check for doubles.
- If no one has doubles, announce or print that.
- If both have doubles, announce that it is a tie.
- If the human has doubles, announce that the human wins.
- If the computer has doubles, announce that the computer wins.
The order of 5 through 8 might change, depending on how you want to write your if-statement.
Here is another example (a very simple one).