Student Lab 1: Input, Processing, and Output
Lab 6: Functions
This lab accompanies Chapter 6 of Starting Out with Programming Logic & Design.
Name: ___________________________
Lab 6.1 – Functions and Pseudocode
|Critical Review |
| |
|You have been coding with modules in pseudocode and when using Java. |
| |
|Modules can be made into functions by returning a value. |
| |
|In other words, a function is a special type of module that returns a value back to the part of the program that called it. |
| |
|In addition, most programming languages provide a library of prewritten functions that perform commonly needed tasks. |
| |
|Library functions are built into the programming language and you can call them as needed. They are commonly performed tasks. |
| |
|Help Video: Double click the file to view video |
|[pic] |
Writing Your Own Function that Returns an Integer
Step 1: A function contains three parts: a header, a body, and a return statement. The first is a function header which specifies the data type of the value that is to be returned, the name of the function, and any parameter variables used by the function to accept arguments. The body is comprised of one or more statements that are executed when the function is called. In the following space, complete the following: (Reference: Writing Your Own Functions, page 250).
a. Write a function with the header named addTen.
b. The function will accept an Integer variable named number.
c. The function body will ask the user to enter a number and the add 10 to the number. The answer will be stored in the variable number.
d. The return statement will return the value of number.
Function d.__________ a.____________ (b.______________)
Display “Enter a number:”
Input c._________________
c._____________ = number + 10
Return d.___________________
End Function
Step 2: In the following space, write a function call to your function from Step 1.
number = ____________________ (__________________)
Writing Your Own Function that Returns a Boolean Value
Step 1: A Boolean function will either return a true or a false value. You can use these functions to test a condition. They are useful for simplifying complex conditions that are tested in decision and repetition structures. In the following space, complete the following: (Reference: Returning Boolean Values, page 263).
a. Write a function with the header named gender.
b. The function will accept a Boolean variable named answer.
c. The function body will ask the user to enter their gender into the variable type and then determine if they are male or female with an if statement.
d. The return statement will return the value of answer.
Function d.__________ a.____________ (b.______________)
Declare String type
Display “Enter your gender (male or female):”
Input c._________________
If (c.___________ == “male”) then
answer = False
Else
answer = True
End If
Return d.___________________
Step 2: In the following space, write a function call to your function from Step 1.
answer = ____________________ (__________________)
Using Mathematical Library Function: sqrt
Step 1: The sqrt function accepts an argument and returns the square root of the argument. In the following space, complete the following: (Reference: The sqrt Function, page 265).
a. Declare a variable named myNumber of type Integer and a variable named squareRoot of the data type Real.
b. Ask the user to enter a number of which they want to find the square root. Store the input in myNumber.
c. Call the sqrt function to determine the square root of myNumber.
d. Display the square root to the screen.
Declare Integer a.___________________
Declare Real a.______________________
Display “Enter a number:”
Input b._________________________
c.______________ = _______________________
Display “The square root is”, d.____________________
Using Formatting Functions
Step 1: Most languages provide one or more functions that format numbers in some way. A common use of formatting functions is to format numbers as currency amounts. While a specific programming language will have its own name for formatting currency, use the function currencyFormat for pseudocode. In the following space, complete the following: (Reference: Formatting Functions, page 270).
a. Declare Real variables named subtotal and total and a constant Real variable named TAX set to the rate of .06.
b. Ask the user to enter the subtotal. Store the input in subtotal.
c. Calculate the total as subtotal + subtotal * TAX
d. Make a call to the currencyFormat function and pass it total. Since you are not displaying it on this line, simply set the return value to total.
e. Display the total to the screen.
Declare Real a.___________________
Declare Constant Real a.______________________
Declare Real a.____________________________
Display “Enter the subtotal:”
Input b._________________________
c.______________ = _______________________
total = d.___________________(________________)
Display “The total is $”, e.____________________
Send .doc file to rjanson@fscj.edu
Lab 6.2 – Functions and Algorithm
This lab requires you to create an algorithm similar to the program on page 246 in Using Random Numbers and the RANDOM function.
Step 1: Start by reading page 245 and 246 of your textbook (Using Random Numbers). In addition to simply displaying the random values, the program will also meet the following requirements:
• Allow the two players of the dice game to enter their names
• Based on the random roll of the dice, the program will determine which value is higher or if they tie and display the winners name or display “Tie”.
• Additionally, the program should allow the same players to play as many times as they want.
Step 2: Write the Algorithm to perform the above
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
Lab 6.3 – Functions and Pseudocode
Step 1: In addition to the above, the program will also meet the following requirements:
• When the player’s names are entered they are stored in variables named playerOne and playerTwo.
• When it is determined which value is higher or if they tie, the winners name or the text “Tie” will be assigned to a variable called winnersName.
• Create structure in the program by creating the following modules:
o An inputNames( ) module that will ask a player to enter their name, store the value in a variable called playerName, and return playerName.
o A rollDice( String p1Name, String p2Name) module that will
▪ Call the RANDOM function twice and store the values in variables called p1Number and p2Number
▪ Determine the winner or a tie and assign the winners name or “Tie” to winnersName and return winnersName.
o A displayInfo(String name) module that will display the winners name to the screen.
• Additionally, the program will prompt the player if they want to play again and store the users reply in a variable called endGame. If endGame is yes the program will loop and play again.
External design
[pic]
Step 1: In the pseudocode below, declare and initialize the following variables under the documentation for Step 1.
• A variable called endProgram that is initialized to “no”
o This variable will be used to run the program again
• Variables called playerOne and playerTwo that are initialized “NO NAME”
o Theses variables will hold the player names
• A variable called winnersName
Step 2: In the pseudocode below, write calls to the inputNames function under the documentation for Step 2.
• The first call assigns the returned value to playerOne.
• The second call assigns the returned value to playerTwo.
Step 3: In the pseudocode below, write a condition controlled While loop using the endProgram variable under the documentation for Step 3.
Step 4: Write the call to the rollDice function that passes the two player names and assigns the returned value to winnersName under the documentation for Step 4.
Step 5: Write the Call to the displayInfo method that passes the winners name under the documentation for Step 5.
Step 6: Specify the variable name to hold the users response under the documentation for Step 6.
Module main ()
//Step 1: Declare and initialize local variables
___________________________________________________
___________________________________________________
___________________________________________________
___________________________________________________
//Step 2: Calls to inputNames
___________________________________________________
___________________________________________________
//Step 3: Loop to run program again
While _________________________________
//Step 4: Call to rollDice
_____________________________________________
//Step 5: Call to displayInfo
_____________________________________________
Display “Do you want to end the program? (Enter yes or no).”
//Step 6: Read user response
Input _________________________________
End While
End Module
Step 7: In the pseudocode below, write the missing lines, including:
a. Declare the variable to hold the user supplied name
b. Display statement to prompt the user
c. Input statement to assign the name to the variable
d. The return statement that returns the players name.
//This function gets and returns a player’s name
Function String inputNames()
a. ___________________________________________________
b. ___________________________________________________
c. ___________________________________________________
d. ___________________________________________________
End Function
Step 8: In the pseudocode below, write the missing lines, including:
a. The missing parameter list for the player names
b. The variable declarations hold the two random numbers and the winners name
c. The second call of the Random function
d. The nested if structure to determine the winner or a tie and assign the correct value to winnersName
e. The return statement that returns the winners name.
//This function returns the winners' name
Function String rollDice(a._______________________________)
b. ___________________________________________________
__________________________________________________
__________________________________________________
p1Number = Random(1,6)
c. ___________________________________________________
d. ___________________________________________________
___________________________________________________
___________________________________________________
___________________________________________________
___________________________________________________
___________________________________________________
e. ___________________________________________________
End Function
Step 9: In the pseudocode below, write the missing lines, including:
a. The missing parameter list
b. The missing display statement
//This module displays the winner
Module displayInfo(a.____________________________________)
b. _______________________________________________
_______________________________________________
End Module
Send .doc file to rjanson@fscj.edu
Lab 6.4 – Functions and Flowcharts
|Critical Review |
| |
|When creating a flowchart for a program that has functions, draw a separate flowchart for each function. |
| |
|The starting terminal symbol usually shows the name of the function, along with any parameters that the function has. |
| |
|The ending terminal symbol reads Return, followed by the value or expression being returned. |
| |
|In Flowgorithm, there are built-in procedures and functions that perform a wide variety of tasks on the programmer's behalf, saving|
|development time and reducing the chance for errors. |
| |
|Flowgorithm has the following built-in functions. |
|basic math: Sqrt, Abs, Sgn, Log,Log10,Int |
|trigonometry: Sin, Cos, Tan, Arcsin, Arccos, Arctan, arccot |
|data conversion: ToChar, ToCode,ToFixed,ToInteger,ToReal, |
|ToString |
|miscellaneous: Random, Len,Char,Size |
| |
|If you want to learn what each of these functions do, click the Help icon in Flowgorithm (to be directed to the online |
|documentation) and click on Intrinsic Functions. |
| |
|The Random function in Flowgorithm takes one argument. To generate a random integer from 1 to n, use Random(n) + 1. For example, |
|you can simulate the roll of a die (random number from 1 to 6) with Random(6) + 1. |
This lab requires you to convert your pseudocode in Lab 6.3 to a flowchart.
Step 1: Start Flowgorithm and save your document as Lab 6_4. The .fprg file extension will be added automatically. Start by adding a Comment box that specifies your name, the date and a brief description of the program function. Then add the main method comment(s) from the pseudocode.
Step 2: Add the needed Declare and Assign symbols for the necessary variables.
Step 3: Add the calls to inputNames.
Step 4: Add the loop to run until the user specifies not to run again.
Step 5: Inside the loop:
Add the module calls to rollDice and displayInfo
Add the Display statement to prompt the user about ending the program
Read in the user response
Step 6: Code the inputNames( ) function that a player is prompted to enter their name and the function returns that name.
Step 7: Add the rollDice( ) function and add the Declare symbols for the required variables.
Step 8: In rollDice( ) add an Assign symbol. Assign the value returned by the RANDOM function to p1Number. The assign box input box should look as follows:
[pic]
Step 9: Add a second assignment statement and do the same for p2Number.
Step 10: Add an If structure that will determine which number is larger, or if there is a tie. The best way to do this is to create a nested If where you first check to see if p1Number is greater than p2Number. If so, assign the first player’s name to winnerName. If not, create a second decision to see if p1Number is less than p2Number. If so, then winnerName should be set equal to the second player’s name. If not then assign “TIE” to winnerName.
Step 11: Add a displayInfo method that accepts the winners name and displays it on the screen with the text as describe in the pseudocode.
Step 12: Run and test the flowchart. The results should look like the following:
[pic]
[pic]
Send the .fprg file to rjanson@fscj.edu
Lab 6.5 – Java Code and Random
The goal of this lab is to convert the Dice Game in Lab 6.3 to Java code.
When completed and executed the program interface should look like this:
[pic]
Step 1: Start Notepad++. Prior to entering code, save your file by clicking on File and then Save. Select your location and save this file as Lab6_5.java. Be sure to include the .java extension.
Step 2: Document the first few lines of your program to include the file name, your name, the date, and a brief description of what the program does.
Step 3: Start your program with the following code for main that creates a global variable called keyboard and assigns a Scanner object to it:
import java.io.*;
import java.util.Scanner;
public class Lab6_5{
static Scanner keyboard = new Scanner(System.in);
// The main function
public static void main(String[] args){
// Declare and initialize local variables
String endProgram = new String("no");
// Calls to inputNames
// Loop to run program again
while (endProgram.equals("no")){
//Call to rollDice
//Call to displayInfo
System.out.println("Do you want to end program? (Enter yes or no): ");
//Read user response
}
}
// This function gets and returns a player’s name
// This function returns the winners' name
//This module displays the winner
}
Step 4: Under the documentation for initialize variables, after endProgram is set to ‘no’, create playerOne and playerTwo variables with the value of “NO NAME” and a variable named winnersName.
Step 5: Under the documentation for making a call to inputNames, create two function calls to get both playerOne and playerTwo’s names. This is done as follows:
playerOne = inputNames();
Step 6: Make a call to rollDice and pass the necessary variables needed in this function. This function will return the value for the winnersName. This is done as follows:
winnersName = rollDice(playerOne, playerTwo)
Step 7: Make a call to displayInfo and pass it winnersName.
Step 8: After the user prompt, add the statement to read in the answer and assign it to endProgram.
Step 9: The next step is to write the inputNames function that will allow both players to enter their names. Write a function heading that matches your function calls in Step 5, making sure to accept no arguments. The body of this function needs to define the String variable to hold the user name, prompt the user to enter their name with the following “Enter Player Name: ” and use the Scanner object’s (assigned to the variable keyboard) nextLine() function to read the players name. There should be one return statement that returns the players name variable. The return statement should look as follows:
return playerName;
Step 10: The next function to code is the rollDice function. Write the function header to match the function call in Step 6. Define the need variables and then call the random function to determine p1Number and p2Number. The code should look as follows:
p1Number = (int)((Math.random() * 6) + 1);
p2Number = (int)((Math.random() * 6) + 1);
Step 11: Next, inside this function write a nested if else statement that will set winnersName to either playerOne name, playerTwo name, or “TIE”.
Step 12: The final step in this function is to return winnersName.
Step 13: The final method to code is the displayInfo function. Write the function header to match the call made in Step 7. The body of the function should simply print the winnerName variable to the screen with the appropriate text.
Step 14: Execute and test the program to prove that all the loops work.
Send the .java file to rjanson@fscj.edu
Lab 6.6 – Graded Assg – Math Test
Write the pseudocode, flowchart, and Java code for the following programming problem.
Design and write a program that will allow a student to enter their name and then ask them to solve 5 mathematical equations. The program should display two random numbers that are to be added, such as:
247
+
129
The program should allow the student to enter the answer. The program should then display whether the answer was right or wrong, and accumulate the correct values. After the 5 questions are asked, calculate the average correct. Then display the student name, the number correct, and the average correct in both decimal format.
In addition to any system functions you may use, you should have the following functions:
• A function that allows the student to enter their name.
• A function that gets a random number, anywhere from 1 to 500.
• A function that displays the equation and asks the user to enter their answer.
• A function that checks to see if the answer is right and accumulates the number right.
• A function that calculates the results.
• A module that displays the student name, the number right, and the average right.
Your sample output should look as follows (random numbers will be different):
Enter Student Name: Katie
What is the answer to the following equation
424
+
28
What is the sum: 472
Wrong
What is the answer to the following equation
163
+
233
What is the sum: 396
Right
What is the answer to the following equation
285
+
453
What is the sum: 688
Wrong
Etc…(through 5 iterations)
Information for student: Katie
The number right: 3
The average right is 0.60
The Pseudocode
Module main()
//Declare local variables
Declare Integer counter = 0
Declare String studentName = “No Name”
Declare Real averageRight = 0.0
Declare Real right = 0
Declare Integer number1 = 0
Declare Integer number2 = 0
Declare Integer answer = 0
studentName = inputName()
//Add loop to display the 5 problems
???????
//Add statements to retrieve the two random numbers
number1= ??????
number2= ??????
//Add statements to retrieve the answer and the number right
answer = ??????
right = ??????
counter = counter + 1
???????
//Add statements to retrieve the average right and display results as shown above
???????
End Module
Function String inputName()
Declare String studentName
Display “Enter Student Name:”
Input studentName
Return studentName
End Function
Function Integer getNumber()
//Add statements to retrieve and return a random number between 1 and 500
???????
End Function
Function Integer getAnswer(Integer number1, Integer number2, Integer answer)
Display “What is the answer to the following equation”
Display number1
Display “+”
Display number2
Display “What is the sum:”
Input answer
Return answer
End Function
Function Real checkAnswer(Integer number1, Integer number2, Integer answer, Real right)
//Add statements to check if answer correct, display if answer is correct or not, calc total
// right so far
???????
Return right
End Function
Function Real results (Real right, Real averageRight)
averageRight = right / 5
Return averageRight
End Function
Module displayInfo(Real right, Real averageRight, String studentName)
//Add statements to display results as shown above
???????
End Module
Send the pseudocode file to rjanson@fscj.edu
The Flowchart
When run, the flowchart results should look like the following:
[pic]
[pic]
3 more equations should be displayed then:
[pic]
Send the .fprg file to rjanson@fscj.edu
The Java Code
Send the .java file to rjanson@fscj.edu
-----------------------
Critical Review
A value-returning function is a function that returns a value back to the part of the program that called it. In Java, you have been using functions that do not return a value.
Recall the function calls from Lab 6-4.
getBottles() //function returns no value
calcPayout() //function returns no value
printInfo() //function returns no value
Standard Library Functions
Java comes with a standard library of functions that have already been written for you. These functions, known as library functions, make a programmer’s job easier because they perform many of the tasks that programmers commonly need to perform. In fact, you have already used several of Java's library functions. Some of the functions that you have used are input, raw_input, and range. Java has many other library functions.
The random Function
To use the random function in Java, you will use the Math class. One of the functions in the Math class is the Math.random() method. This module accepts no arguments and returns a decimal number between 0 and 1(not inclusive – meaning 1 will never be returned as a value). To get a number between 1 and 6 we must multiply the returned number by 6, add 1 to it, and then truncate the remainder. The following shows example numbers that random would return and how the algorithm will modify them into a value between 1 and 6.
random number 0.0000000000000001
* 6
0.0000000000000006
+ 1
1.0000000000000006
Truncating results in 1
random number 0.7206412075059009
* 6
4.3238472450354054
+ 1
5.3238472450354054
Truncating results in 5
random number 0.9999999999999999
* 6
5.9999999999999994
+ 1
6.9999999999999994
Truncating results in 6
In Java you truncate a number with decimal places by converting it to an integer. This is done in an assignment statement by preceding the decimal number with (int) as follows:
int ranNum = (int)((Math.random() * 6) + 1);
Writing your own Value-Returning Functions
For a function to send a value back, it must contain a return statement. The return statement identifies the variable or value that will be returned to the call statement.
The function call might look as follows:
playerOneNumber = getDiceRoll();
In getDiceRoll, the return statement would look as follows:
return ranNum;
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- input and output calculator
- input and output table calculator
- java input and output stream
- java input and output file
- input and output equations
- input and output function math
- input and output math solver
- input and output equation
- input and output in math
- input and output equation calculator
- input and output tables
- input and output in java