Showing posts with label Phrogram. Show all posts
Showing posts with label Phrogram. Show all posts

Wednesday, January 2, 2008

Console Input

 

In all of our examples so far, we have had to modify the program each time to change the values of a variable. Many programs though require input from the user. This allows us to ask the user of our programs questions and then have our computer program do something based on the input of the user.

In this section, we will program a guessing game where the computer this of a number between 1 and 100 and the user has to try and guess the number. Each time the user guesses, the computer will tell the user higher or lower. The game stops when the user guesses the number correctly. At the end, the computer will tell the user how many times they guessed before getting the answer write.

To read input from the user, we need to use one of the following two methods

ConsoleReadInt()

ConsoleReadLine()

ConsoleReadInt() is used to input integers from the user. ConsoleReadLine() is used to read text from the user. In this example, you are writing guessing game. Because the input are integers, we will use ConsoleReadInt() to get input from the user.

When you ask someone a question, you get an answer. Where do you store the answer? In your memory. The same is true when you use ConsoleReadInt(). The computer asks the user a question and the users answer is stored in the computers memory which we define as a variable.

Before we can use the variable it must be defined. What type of variable should we define? Integer, right?

Let’s take a quick look at an example:

Program MyNewProgram

Method Main()

Define X As Integer

X = ConsoleReadInt("Enter a number: " , False)

ConsoleWriteLine ("You entered: " + X)

End Method

End Program

In this example, we can see that ConsoleReadInt() takes two paramters.

The first Parameter Prompt determines what message is displayed to the user. The second parameter EchoToConsole determines if the value the user enters is displayed in the console window. Typically the value of EchoToConsole should be set to false.

clip_image002[4]

Let’s review the ConsoleReadInt() Method

clip_image004

This program asks the user to input a variable and then write the value of the variable on the screen. Pretty simple.

How do we determine what number the computer is thinking? Since we want the number to be different each time the user plays the game we can have the computer generate a random number using the Random() method. Random() asks the computer to pick a number between two numbers. This is just like when someone asks you to pick a number between 1 and 10.

To tell the computer to pick a number between 1 and 10 we use Random(1,10).

clip_image006[4]

Again, just like with ConsoleReadInt() we need to store the value returned by the method Random(). What type of variable should we use? Let’s define a variable called Answer as an Interger and return a number between 1 and 100.

Define Answer As Integer

Answer = Random (1,100)

Now let’s build program that puts all of the pieces together. We want to

1. Have the computer pick a number between 1 and 100 and store it in the variable answer

2. Have the user guess a number between 1 and 100

3. Repeat this process until the users guess is equal to the anwer

In the next section, we will add logic to the code to tell the computer if the number is higher or lower.

First we need to define our variable. This program will start with 2 variables. One for the Answer and one for Guess.

Define Answer As Integer

Define Guess As Integer

Next, we need the computer to select a number between 1 and 100

Answer = Random (1,100)

Now we need to setup a Loop. Since we want the program to repeat until the user gets the answer correct, we will use a While Loop. The computer will keep asking the user while their guess is NOT equal to their answer.

While Answer <> Guess

Then we will prompt the user to enter a number and display the number the user entered on the console window.

Guess = ConsoleReadInt("Enter a number between 1 and 100: " , False)

ConsoleWriteLine ("You entered: " + Guess)

The program will continue until the user guess the right answer and then we can display a message telling the user they got the answer right.

End While

ConsoleWriteLine ("You guessed right.")

Next, let’s prompt the user to enter a number between 1 and 100.

X = ConsoleReadInt("Enter a number between 1 and 100: " , False)

Here is what our program should look like.

Program GuessANumber

Method Main()

Define Answer As Integer

Define Guess As Integer

Answer = Random (1,100)

While Answer <> Guess

Guess = ConsoleReadInt("Enter a number 1 and 100: " , False)

ConsoleWriteLine ("You entered: " + Guess)

End While

ConsoleWriteLine ("You guessed right.")

End Method

End Program

Now, have some fun and see if you can guess the number the computer is thinking.

Right now, the user has to keep guess until they get the number right. Typically when you play this game, the person you are playing with will say Higher or Lower based on the number you say. Let’s look at how we can modify the computer program to do the same. Here is what we want to do.

If the guess the user enters is higher than the answer then display Lower

If the guess the user enters is lower than the answer then displayer Higher

This can be performed by using an If / Then statement. Basically you are saying, if something is true then do this. Let’s take a look at what this looks like.

If Guess > Answer Then

ConsoleWriteLine ("The number is LOWER")

End If

Here we are telling the computer if the value of the variable Guess is greater than the value of the variable Answer then display a message “The number if Lower”. Now we need to do the same and tell the user if the number is higher.

If Guess < Answer Then

ConsoleWriteLine ("The number is HIGHER")

End If

Now our complete program looks like this.

Program GuessANumber

Method Main()

Define Answer As Integer

Define Guess As Integer

Answer = Random (1,100)

While Answer <> Guess

Guess = ConsoleReadInt("Enter a number between 1 and 100: " , False)

ConsoleWriteLine ("You entered: " + Guess)

If Guess > Answer Then

ConsoleWriteLine ("The number is LOWER")

End If

If Guess < Answer Then

ConsoleWriteLine ("The number is HIGHER")

End If

End While

ConsoleWriteLine ("You guessed right.")

End Method

End Program

In this section we are going to create a program to write a math quiz for students. The program will ask the user 10 questions and allow the user to enter the answer for each question. At the end of the quiz the program will display the number of questions right and the number of questions wrong.

Learn To Phrogram

Learn to Program

Variables

A variable is used to store a value in the computer’s memory. Before you can use a variable, you must first Define the variable. This allows the computer to know the name of the variable and what type of data the variable will store. Let’s define our first variable.

Define guess As Integer

In this example, the name of the variable you are defining is guess and the data type is Integer. Now, you must be asking yourself, what is an integer? An integer is a whole number. For example, 1,2,3 etc. You could not assign the value 2.5 to the variable guess because 2.5 is not a whole number.

By default, when you define a variable as an integer, the value of the integer is zero. Try the following program.

Method Main()

Define guess As Integer

Print (guess)

End Method

Before you run the program, try and think what the console window will display. This is how you start to think like a computer and is an important part of becoming a good computer programmer.

clip_image002

If you said 0, then you are correct. Guess is equal to zero because it hasn’t been assigned a value. Let’s move to the next step and assign a value to the variable we defined.

To assign a variable a value, you need to set the variable equal to something. To assign a variable, we use the equal sign. The equal sign on the computer is =.

To assign the variable guess the number 5, we use the following command.

guess = 5

Now try the following program.

Method Main()

Define guess As Integer

guess = 5

Print (guess)

End Method

What will the output be now?

clip_image004

Simple, right?

Now, let’s practice some basic computer math. Try to answer the following problems. Remember, think like a computer. If you need help, write a small computer program to help you answer the questions.

1.

x = 5

y = 10

x + y = _____________

2.

x = 5

y = 15

y – x = ____________

3.

Y = 10

Y = Y + 1

Y = ____________

4. X = 15

Y = 10

Z = _____________

5. X = 10

Y = 5

Z = X + Y

Z = ______________

A variable is used to store a value in the computer’s memory. Once you have defined a variable and assigned it a value, you can use the variable. In the first chapter, you already started to use variables by adding and subtracting them. Let’s now take a look at how we can comparison operations. When you compare something, what are you doing? You are looking to see what is the same and what is different between two items. If you were to compare two apples, you may compare their size, shape, type and color.

A computer program can be used to compare variables as well. Now, it is time to start thinking like a computer. Answer the following questions

Define X As Integer

Define Y As Integer

X = 5

Y = 10

Is X > 5? _________

Is Y < 10? _________

Is X = Y? _________

Let’s review the three comparison operators you used. These should be familiar to you already from math lessons.

>

Greater than

<

Less than

=

Equal too

Enter the following program to see the results for yourself in the console window.

Method Main()

Define X As Integer

Define Y As Integer

X = 5

Y = 10

ConsoleWriteLine ("Answer: " + (Y > 5) )

ConsoleWriteLine ("Answer: " + (Y < 10) )

ConsoleWriteLine ("Answer: " + (X=y))

End Method

When you run the program, you should see the following results.

clip_image006

Hey, why is there a + sign in the method ConsoleWriteLine? Good question. First, we are using a new Method to tell the computer to write information to the console window. The Method ConsoleWriteLine() tells the computer to output information to the console window and start a new line. Try changing your program to use the ConsoleWrite() method instead of the ConsoleWriteLine(). What do you see now?

Method Main()

Define X As Integer

Define Y As Integer

X = 5

Y = 10

ConsoleWrite ("Answer: " + (Y > 5) )

ConsoleWrite ("Answer: " + (Y < 10) )

ConsoleWrite ("Answer: " + (X=y))

End Method

clip_image008

Using ConsoleWriteLine() looks much better, doesn’t it.


Methods

Methods are computer commands. A computers programming language has hundreds of built in methods it knows how to execute. You as a computer programmer have the ability to define your own new methods. Most methods take a parameter. A parameter simply provides the method additional information. For example, let’s take a look at the method ConsoleWriteLine().

When you start typing ConsoleWriteLine ( the following tooltip will be displayed.

clip_image010

The tool tip tells you what type of parameter is required and provides a brief description. In this example, the method ConsoleWriteLine() requires a String which is the message to display on the console window.

Now, lets go back to our last example. Look at the following line.

ConsoleWriteLine ("Answer: " + (Y > 5) )

In this example, we are calling the method ConsoleWriteLine() and passing the String value of

“Answer: “ + (Y>5)

The + sign is used here to join two strings together. The + sign can be used to add numbers together or to join two strings together. Take a look at the following examples.

If the plus sign come between two numbers, the + sign will add the numbers

For example:

Define X As Integer

X = 5 + 10

ConsoleWriteLine (X)

If the plus sign comes between two Strings, the + sign will join the two values together.

Define X As String
X = " Answer: " + " True"
ConsoleWriteLine (X)

clip_image012

A few more points about using string. When you define strings they MUST be between quotation marks. Try the following

Define X As String

X = What is your name?

ConsoleWriteLine (X)

The program looks ok, but you will get a syntax error. What do you need to do to correct the syntax error? Add quotation marks, right?

Define X As String
X = "What is your name?"
ConsoleWriteLine (X)

Review Time

1.

Define X As String

X = "What is your name?"

ConsoleWriteLine (X)

What type of variable is X? ____________

2.

Define X As Integer

Define Y As Boolean

Y = X > 5

What is the value of Y? ______________

3.

Define X As String

X = What is your name?

ConsoleWriteLine (X)

What is wrong with the program above above?

Rinse and repeat

Computers are very good at repeating the same tasks over and over. They never get tired of doing the same tasks again and again. In this section we are going to learn how to repeat a set of tasks multiple times.

Suppose you want to display your name on the screen 5 times. What’s the best way to do this? You could choose to use the ConsoleWriteLine() method 5 times. While this would work ok for repeating a task 5 times, what if you wanted to change the program and display your name 100 times? This would be very tedious. The language Phrogram provides several commands to accomplish this.

Method Main()

ConsoleWriteLine("Jon Smith")

ConsoleWriteLine("Jon Smith")

ConsoleWriteLine("Jon Smith")

ConsoleWriteLine("Jon Smith")

ConsoleWriteLine("Jon Smith")

End Method

LOOP LOOP

The first way is to use the command LOOP. LOOP takes one argument, the number of time to repeat. Place LOOP before the section of code you want to repeat and END LOOP at the end of the section. Let’s look at how to repeat Jon Smith using the Loop command.

Method Main()

Loop 5

ConsoleWriteLine("Jon Smith")

End Loop

End Method

Much simpler. The code is easier to read and easier to update. Change the program above to output the name Jon Smith 25 times. Only one line of code to change.

FOR LOOP

Another method to repeat a section of code multiple times is to use the FOR NEXT command.

Method Main()

Define X As Integer

For x = 1 To 5

ConsoleWriteLine("Jon Smith")

Next

End Method

First, you must define a variable as an Integer. In this example we define X. Next we call For and specify the start and end values. In this case, we instruct to start at the value of 1 and end at 5. Each time the computer executes the Next command, the value of the integer X is incremented. To see this better, lets modify the program to display the value of X each time the method ConsoleWriteLine() is called.

Method Main()

Define X As Integer

For x = 1 To 5

ConsoleWriteLine("Jon Smith:" + X)

Next

End Method

When you run the program, you will see the following.

clip_image014

Let’s review.

This instructs the computer to start at the value 1 and continue until X = 5. Every time Next is called, the value of X increase by 1.

In this example, using both Loop and For / Next produce the same results. Loop is somewhat easier to use because you do not need to define a variable first.

While LOOP

A third method is to use the While command. Using the While command allows you to control when code is executed. While a given condition is true, the computer code will be executed. If the condition is not true, the computer code will not be executed. Let’s look at two examples. The first example will again display the name Jon Smith on the screen 5 times.

Method Main()

Define X As Integer

While X < 5

X = X + 1

ConsoleWriteLine("Jon Smith: " + X)

End While

End Method

In the next example, we will continue to display the name Jon Smith on the screen until you press Q on the keyboard to quit. If you don’t hit Q, the program will continue to execute the method ConsoleWriteLine() forever. Remember, computers never get tired.

clip_image016

Let’s review the program line by line.

Line

Description

2

Name of the program

4

Defines the variable X as an Integer

5

Checks to see if the value of IsKeyDown(“A”) is equal to “A”. IsKeyDown(“A”) checks to see if the user is pressing the “A” key on the keyboard. If FALSE then the code on lines 7 and 8 is executed. If TRUE then the execution of the code resumes at line 9.

6

Prints Jon Smith and the value of the integer X on the console

7

Increments the value of X

8

End of the conditional loop

9

Prints Done on the console window

Lab questions

1. Write a program that counts down starting at number 10 and ending at 1. When done counting, display the message All Done. The output should look like the following. There are a couple of ways this can be done.

clip_image018

One way is to use the While statement and subtract 1 from the variable X each time. By starting with the variable X equal to 11, the program counts backward from 11 to 1 and stops when X is less than 1.

Program MyNewProgram

Method Main()

Define X As Integer

X = 11

While X > 1

X = X - 1

ConsoleWriteLine("The Number is: "+ X)

End While

ConsolewriteLine("All Done")

End Method

End Program

Another method is to use the For / Next statement and use an argument to tell the For / Next statement to count by negative 1. Notice in this example we do not need to set X = 11 before the loop we are defining.

Program MyNewProgram

Method Main()

Define X As Integer

For X = 10 To 1 Step -1

ConsoleWriteLine("The Number is: "+ X)

Next

ConsolewriteLine("All Done")

End Method

End Program

Lab Work

1. What is the value of Y after the following program is run?

Define X As Integer

Define Y As Integer

For X = 1 To 5

Y = Y + 1

Next

ConsoleWriteLine (y)

Answer: 5

2. What is the value of X after the following program is run?

Define X As Integer

Define Y As Integer

For X = 1 To 5 Step 2

Y = Y + 1

Next

ConsoleWriteLine (y)

Answer:3

3. What is the value of X after the following program is run?

Define X As Integer

Define Y As Integer

For X = 10 To 1 Step -2

Y = Y + 1

Next

ConsoleWriteLine (y)

Answer 5

4. What is the value of X after the following program is run?

Define X As Integer

Define Y As Integer

For X = 10 To 1

Y = Y + 1

Next

ConsoleWriteLine (y)

Answer 0

Decisions, Decisions, Decision

Everyone makes decisions and computers can to using the IF/THEN statement. An IF/THEN statement allows your computer program to execute code when an expression is TRUE. The code between the IF and END IF statement is only executed if the expression is TRUE. IF the expression is FALSE, the statement after the END IF statement is executed. Let’s look at the following program.

Define X As Integer

X = 10

If X > 1 Then

ConsoleWriteLine ("A")

End If

ConsoleWriteLine ("B")

End Method

X > 1 is the expression being evaluated. If X > 1 = TRUE then the code between IF and END IF is executed. In this case, ConsoleWriteLine (“A”) . If the expression is FALSE, then the code after END IF is executed.

What will be displayed when this program is executed?

clip_image020

Let’s modify the program and change the expression.

Define X As Integer

X = 10

If X < 1 Then

ConsoleWriteLine ("A")

End If

ConsoleWriteLine ("B")

End Method

clip_image022

In addition to IF we can also add ELSE. This executes code if the statement is NOT true. This is useful if you need the computer to choose between two choice and you know if the first one is not true, then the second one must be true. For example, if a person is not a girl, they must be a boy. Of if the light is not on, it must be off.

Method Main()

Define X As Integer

X = 1

If X = 1 Then

ConsoleWriteLine ("Girl")

Else

ConsoleWriteLine ("Boy")

End If

End Method

clip_image024

The expression used to test if the statement is true or false can be a combination of multiple expressions. For example X = 1 And Age > 17. Let’s look at another example.

X = 1

Age = 18

If X = 1 And Age > 17 Then

ConsoleWriteLine ("Women")

Else If X = 1 And Age < 17 Then

ConsoleWriteLine ("Girl")

Else If X = And Age > 17 Then

COnsoleWriteLine ("Man")

Else

ConsoleWriteLine ("Boy")

End If

clip_image026