===================
===================
Swift 5 Help
===================
===================
Swift Programming Assignments for this Course
Programming Assignments (more to come)
Go to Last Programming Assignment
Online Swift Compilers
Swift onlinegdb IDE
Swift repl.it (at WHS only)
Swift IDE JDoodle (backup)
Local Swift Compiler - Xcode (it's in the app store)
This is only available in the Apple App Store
and is only available for computers. It should
be available for the iPad, iPad Air, and iPad Pro
in the Fall. You will need to become a developer.
You can choose the free account. You only need the
paid account if you plan to upload your apps for
apple to review (and if they approve it then they
will put it in the store for you).
You Tube Video free developer account
Apple Website for creating a free account
How to put your app on your iPhone for testing
Online Help Sites for Swift
Tutorials Point tutorials
Online Book
Coding with Chris on YouTube
Importance of Programming and a Brief Introduction
Importance of Programming
Swift Programming Sample Tests for this Course
Sample Tests (more to come)
Data Types
Variables
Operators
Comparison or Relational Operators
Logical Operators
Comments
Hello World
Printing on the Console
Optionals
Math Stuff
import
type casts
Constants
String
Trimming white space from a String
User Input in a Terminal App
Referencing GUI Objects for Input
if else statements
Ternary Operators
Ranges
For Loops
While Loops
Math Functions
Number Conversions
Date and Time Functions
Escape Sequences
Creating Functions
Functions with Arguments
Built in Functions
Lists (Arrays)
Tuples (Immutable Lists)
Dictionaries
Lists 2D(Arrays 2D)
Classes
Reading from the Console
Files
Some Simple Programs
More Labs
Back to the Top
===================
===================
Data Types
===================
===================
Type Swift name Short form How it’s used
Integer Int Int For storing whole numbers and negative numbers, for
Double Double Dbl To store decimal values like 12.54, 8.23, -2.68, 89.99, 3.14159
Boolean Bool Bool Used for storing true/false values.
String String Str Strings are used to store text.
You will need to put import UIKit at the top of your program
for iPhone and iPad apps.
===================
===================
Operators
===================
===================
Arithmetic Operators ( +, -, /, //, *, **)
Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=)
You can NOT mix data types with these operators.
So both operands MUST BE OF THE SAME TYPE.
(Both Double or both Int)
(Both String if you are joining together)
Binary operators need to have operands on both sides.
5 + 7 // 5 is an operand + is an operator 7 is an operand
var x = 5 + 7 // x will receive 12
var y = 3 * 12 // y will receive 36
var z = x + y // z will receive 48
NOTE: Operators cannot operate on different types when you are
using variables. You must convert the variables to
matching types.
Example:
var x = 5
var y = 3.14159
var z = x + y // Not Ok (int + double)
print(x + y) // Not Ok (int + double)
var z = Double(x) + y // Ok
var z = x + Int(y)
You do not have to match types with constants.
Example:
print(7 + 3.14159) // Ok
Also, you must be consistent with spaces.
var x = 5
var y = 8
x + y Ok
x+ y Not Ok
x +y Not Ok
x+y Ok
===================
===================
Comparison or Relational Operators
===================
===================
Relational or Comparison Operators (==, !=, >, <, >=, <=)
Sample 1:
var x = 8
var y = 12
if x > y
{
print(x, "is bigger than", y)
}
Sample 2:
var x = 8
var y = 12
if x > y
{
print(x, "is bigger than",y)
}
else
{
print(y, "is bigger than",x)
}
Sample 3:
var x = 8
var y = 12
if x > y
{
print(x, "is bigger than",y)
}
else if y > x
{
print(y, "is bigger than",x)
}
else
{
print(y, "is the equal to",x)
}
Sample 4:
var temp = 75
if temp >= 90
{
print("It is", temp, "degrees outside. It is so hot!")
print("I really hate this weather unless I am at the pool!")
}
else if temp >= 80
{
print("It is", temp, "degrees outside. It is a little warm!")
}
else if temp >= 65
{
print("It is", temp, "degrees outside. It is a great day!")
print("I really love this weather!")
}
else if temp >= 40
{
print("It is", temp, "degrees outside. It is a little cool out there!")
print("I am not very fond of cool weather!")
}
else
{
print("It is", temp, "degrees outside. It is very cold out there!")
print("I really hate this weather!")
}
Sample 5:
var let x = 9
if x == 10
{
print("x is 10")
}
else if x == 9
{
print("x is 9")
}
else
{
print("x is not 9 or 10")
}
Example 1:
var x:Int = 25
var y:Int = 8
if x > y
{
print(String(x) + " is greater than " + String(y))
// or print("\(x) is greater than \(y))"
}
Example 2:
var x:Int = 25
var y:Int = 8
if x > y
{
print(String(x) + " is greater than " + String(y))
// or print("\(x) is greater than \(y))"
}
Sample 3:
var x = 8
var y = 12
var z = 10
if x > y && x > z
{
print(x, "is bigger than", y, "and bigger than", z, ".")
}
else if y > x && y > z
{
print(y, "is bigger than", x, "and bigger than", z, ".")
}
else if z > x && z > y
{
print(z, "is bigger than", x, "and bigger than", y, ".")
}
else if x == y && x == z
{
print(x, y, z, "are all equal")
}
else if x == y
{
print(x, y, "are equal")
}
else if x == z
{
print(x, z, "are equal")
}
else if y == z:
{
print(y, z, "are equal")
}
else
{
print("It should not ever get here.")
}
===================
===================
Logical Operators
===================
===================
Logical Operators (&&, ||, ! )
// Not And Or
! (not operator)
&& (and operator)
|| (or operator)
Examples:
!true is false
!false is true
5 > 4 is true
5 >= 4 is true
5 < 4 is false
===================
===================
Bitwise Operators
===================
Bitwise Operators (&, |, ^, ~, <<, >>)
Back to the Top
===================
Math Stuff
===================
===================
import Foundation
print("Let's do some Math")
print()
print("3 + 4 - 5")
print(3 + 4 - 5)
print()
print("It knows about my dear aunt Sally (PEMDAS)")
print("7 - 5 * 2")
print(7 - 5 * 2)
print()
print("1/2 * 5")
print(1 / 2 * 5)
print()
// gives back a random Int in the range of 1 to 100 inclusive
let x = Int.random(in:1...100)
print(x)
Back to the Top
===================
Math Functions
===================
===================
NOTE: You will need to import the
Foundation class to use these functions.
import Foundation
sqrt(25)
pow(2,3)
floor(23.7)
ceil(23.7)
abs(-21)
max(10,20)
min(10,20)
// gives back a random Int in the range of 1 to 100 inclusive
let x = Int.random(in:1...100)
Also, for pi, use:
Double.pi
Float.pi
CGFloat.pi
Samples:
print(pow(2, 3))
print(sqrt(16))
print(Double.pi)
print(abs(-20))
Back to the Top
===================
Date and Time
===================
===================
Back to the Top
===================
===================
===================
===================
// This is a one line comment
/*
Swift comments can also
span multiple lines
*/
Back to the Top
========================
========================
import
========================
========================
The keyword import is used to allow you
access to a library (which cointains
functions).
Converting to Bases
-------------------
After the radix: put your base to convert the int into
let hexString = String(31, radix: 16, , uppercase: true)
print(hexString) // prints 1F
NOTE: You must unwrap it!
var x = Int("A2", radix: 16)!
print(x) // prints 162 (10 x 16 + 2 x 1)
Back to the Top
===================
===================
type casts
===================
===================
Example 1:
var x = 12
var y = Double(x) // y is now 12.0
Example 2:
var x = 12.5
var y = Int(x) // y is now 12
Example 3:
var s = String(12) // s is now "12"
Example 4:
import Foundation
print("Enter your first name: ", terminator:"")
var firstName = readLine(strippingNewline:true)!
print(firstName)
Back to the Top
===================
===================
Constants
===================
===================
Use the let keyword instead of var
You must assignment it a value.
let x = 5
let y = 12
Back to the Top
===================
===================
===================
===================
NOTE: readLine always returns a String as an Optional,
so you may want to unwrap it use a if let
statement to see if it is valid data.
NOTE: You must have
import Foundation
at the top of your program.
Example 1:
import Foundation
print("Enter your first name: ", terminator:"")
var firstName = readLine(strippingNewline:true)!
print(firstName)
Example 2:
import Foundation
print("Enter the value for x: ", terminator:"")
var x = Int(readLine(strippingNewline:true)!)!
print(x)
Example 3:
print("Area of a Triangle")
print()
print()
// blank lines in the source code
// help the readability
print("Enter the base: ", terminator:"")
let base = Double(readLine(strippingNewline:true)!)!
print()
print("Enter the height: ", terminator:"")
let height = Double(readLine(strippingNewline:true)!)!
let area = (base * height)/2.0
// THREE ways to print
// You cannot mix types when printing
// All pieces should be a String, and
// therefore the values of variables need
// to be converted to Strings (or use a comma
// to separate).
print()
print("The area is", area, "square units.")
print()
print("The area is " + String(area) + " square units.")
print()
print("The area is \(area) square units.")
// Comments help the programmer and
// others to understand what is going
// on.
Back to the Top
=================================
=================================
=================================
Number Conversions with a String
=================================
=================================
=================================
// converts a String that holds a number into an int
let numberAsString:String = "30"
let someNumber:Int = Int(numberAsString)! //30
// converts an Int to a String that holds the Int
let number:Int = 30
let numberAsString = String(number)
// To convert an Int to a Double, use Double(30)
// You can also convert to other types like Float(30)
// you can convert to other bases with String(Int, radix: base)
let b2 = String(12, radix: 2) // converts 12 to "1100"
let b8 = String(12, radix: 8) // converts 12 to "14"
let b16 = String(12, radix: 16) // converts 12 to "c"
===================
===================
Ranges
===================
===================
5...8 // 5 6 7 8
5..<8 // 5 6 7
Example 1: prints 5 6 7 8
for i in 5...8
{
print(i)
}
Example 2: prints 5 6 7
for i in 5..<8
{
print(i)
}
Back to the Top
===================
===================
Hello World
===================
===================
print("Hello World")
Back to the Top
===================
===================
Variables
===================
===================
A variable refers to a place in RAM memory
where you can store information (numbers,
strings of characters, etc.) Think of box
that holds data.
Variables have names so that us humans can
refer to them. Variable names should be
descriptive of what kind of information they
refer to.
Names must start with a letter of the alphabet.
After that you can have more letters or numbers or
the underscore(_) character. However, you can not
have a space character or any other special characters
in your name. We should always use lower case letters,
except on word boundaries for long names (camel case).
Variables can not be key words of the programming language.
Also, names are case sensitive. So, X and x are actually
different names.
Some examples of variable names:
x
y
answer
b
num
totalSum
total_sum
answer x y
-------- -------- --------
| 12 | | 7 | | 5 |
-------- -------- --------
Some examples of illegal variable names:
total Sum
total-sum
num@
sum!
Types:
------
Int
Double
String
let x = 5 // Int 5 is assigned to the storage box called x (constant)
var y = 5.2 // Double 5.2 is assigned to the storage box called y
var s = "Hello World" # String "Hello World" is assigned to s
let str = "Hello World" # string "Hello World" is assigned to str
Back to the Top
=======================
=======================
Escape Sequences
=======================
=======================
Escape sequence Meaning
=======================
\\ \ character
\' ' character
\" " character
\n Newline
\t Horizontal tab
Back to the Top
=======================
=======================
Printing on the Console
=======================
=======================
print("Hello World") // prints Hello World
print(2 * 3 + 5) // prints 11
NOTE: You can NOT mix data types!
Use interpolation or a type cast instead.
let x = 5
print("The value of x is " + x) // ERROR String + Int
print("The value of x is " + String(x) + ".") // prints The value of x is 5.
// This is interpolation \(x) \(x) means print the value of x
print("The value of x is \(x).") // prints The value of x is 5.
Back to the Top
====================
====================
For Loops
====================
====================
for constant name in collection or range
{
// code to be executed
}
=========================================================
Example: index would be 1 2 3 4 5
for index in 1...5
{
print("Value of index is \(index)")
}
The output would be:
Value of index is 1
Value of index is 2
Value of index is 3
Value of index is 4
Value of index is 5
=========================================================
=========================================================
Example: index would be 1 2 3 4
for index in 1..<5
{
print("Value of index is \(index)")
}
The output would be:
Value of index is 1
Value of index is 2
Value of index is 3
Value of index is 4
=========================================================
=========================================================
Example: index would be 5 4 3 2 1
for index in (1...5).reversed()
{
print("Value of index is \(index)")
}
The output would be:
Value of index is 5
Value of index is 4
Value of index is 3
Value of index is 2
Value of index is 1
=========================================================
=========================================================
Example: index would be 0 2 4 6 8 10
for index in stride(from:0, to:10, by:2)
{
print("Value of index is \(index)")
}
The output would be:
Value of index is 0
Value of index is 2
Value of index is 4
Value of index is 6
Value of index is 8
Value of index is 10
=========================================================
=========================================================
Example: i would be 0 1 2 3 4
let numbers = [2, 3, 5, 7, 9]
for i in numbers.indices
{
print("Value of index is \(i)")
}
=========================================================
=========================================================
Example: num would be 2 3 5 7 9
let numbers = [2, 3, 5, 7, 9]
for num in numbers
{
print("Value of number is \(num)")
}
The output would be:
Value of number is 2
Value of number is 3
Value of number is 5
Value of number is 7
Value of number is 9
=========================================================
Back to the Top
=======================
=======================
Referencing GUI Objects
=======================
=======================
NOTE: When you get text data from a GUI object,
it will come back as an Optional type.
You will need to generally unwrap it with
the ! operator or use an if let statement.
NOTE: If you use a type cast to convert a number
that is stored as a String, you will get back
an Optional type.
You will need to generally unwrap it with
the ! operator or use an if let statement.
@IBOutlet var outputLabel: UILabel!
@IBOutlet var userTextField: UITextField!
var str = userTextField.text!
outputLabel.text = str
var numberAsString = userTextField.text!
if let number = Int(numberAsString)
{
// do something useful with this number
// the number is a valid number at this point
}
else
{
// show an error to the user
}
// Clearing a Text Field
userTextField.text = ""
// NOTE: DO NOT PUT A SPACE " " in a Text Field
Back to the Top
====================
====================
While Loops
====================
====================
You can break out of a loop with the
keyword break
You can continue a loop with the
keyword continue (come through again).
while condition
{
// Swift statements go here
}
=========================================================
var x = 0
while x != 5
{
// do something
x = x + 1
}
=========================================================
=========================================================
var myCount = 0
while myCount < 100
{
myCount = myCount + 1
}
=========================================================
=================================
=================================
repeat loops (or do while loops)
=================================
=================================
repeat
{
// Swift statements here
} while conditional expression
In the repeat ... while example below the loop
will continue until the value of a variable
named i equals 0:
=========================================================
var i = 10
repeat
{
--i
} while (i > 0)
=========================================================
Back to the Top
====================
====================
Creating Functions or Methods
====================
====================
func name of function (_ variableName: variableType, _ variableName: variableType, ... ) -> return type
{
// Function code
}
See the following link for more help.
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html
=========================================================
Example: an example with no parameters and no return type
func sayHello()
{
print("Hello Swift") }
}
sayHello() // prints Hello Swift
=========================================================
=========================================================
// an example with 2 parameters and a String return type
NOTE: _ name means that we do NOT use a label in the
call statement
func buildMessage(_ name: String, _ count: Int) -> String
{
return("\(name), you are customer number \(count).")
}
// a call statement with NO labels
let message = buildMessage("John", 100)
print(message)
// prints John, you are customer number 100.
=========================================================
=========================================================
// an example with 2 parameters and a String return type
// NOTE: There is no _ before the variable
func buildMessage(name: String, count: Int) -> String
{
return("\(name), you are customer number \(count)")
}
// a call statement with labels
let message = buildMessage(name:"John", count: 100)
=========================================================
=========================================================
func buildMessage(name: String, _ count: Int) -> String
{
return("\(name), you are customer number \(count)")
}
let message = buildMessage(name:"John", 100)
=========================================================
=========================================================
func buildMessage(username name: String, count: Int) -> String
{
return("\(name), you are customer number \(count)")
}
When declared in this way, the external parameter name
must be referenced when calling the function:
let message = buildMessage(username: "John", count: 100)
=========================================================
=========================================================
func buildMessage(username name: String, usercount count: Int) -> String
{
return("\(name), you are customer number \(count)")
}
=========================================================
=========================================================
func buildMessage(name: String = "Customer", count: Int ) -> String
{
return ("\(name), you are customer number \(count)")
}
let message = buildMessage(count: 100)
print(message)
=========================================================
Back to the Top
=================================
=================================
Functions with Arguments
=================================
=================================
func name of function (_ variableName: variableType, _ variableName: variableType, ... ) -> return type
{
// Function code
}
See the following link for more help.
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html
=========================================================
Example: an example with no parameters and no return type
func sayHello()
{
print("Hello Swift") }
}
sayHello() // prints Hello Swift
=========================================================
=========================================================
// an example with 2 parameters and a String return type
NOTE: _ name means that we do NOT use a label in the
call statement
func buildMessage(_ name: String, _ count: Int) -> String
{
return("\(name), you are customer number \(count).")
}
// a call statement with NO labels
let message = buildMessage("John", 100)
print(message)
// prints John, you are customer number 100.
=========================================================
=========================================================
// an example with 2 parameters and a String return type
// NOTE: There is no _ before the variable
func buildMessage(name: String, count: Int) -> String
{
return("\(name), you are customer number \(count)")
}
// a call statement with labels
let message = buildMessage(name:"John", count: 100)
=========================================================
=========================================================
func buildMessage(name: String, _ count: Int) -> String
{
return("\(name), you are customer number \(count)")
}
let message = buildMessage(name:"John", 100)
=========================================================
=========================================================
func buildMessage(username name: String, count: Int) -> String
{
return("\(name), you are customer number \(count)")
}
When declared in this way, the external parameter name
must be referenced when calling the function:
let message = buildMessage(username: "John", count: 100)
=========================================================
=========================================================
func buildMessage(username name: String, usercount count: Int) -> String
{
return("\(name), you are customer number \(count)")
}
=========================================================
=========================================================
func buildMessage(name: String = "Customer", count: Int ) -> String
{
return ("\(name), you are customer number \(count)")
}
let message = buildMessage(count: 100)
print(message)
=========================================================
Back to the Top
=================================
=================================
Built in Functions
=================================
=================================
NOTE: You will need to import the
Foundation class to use these functions.
import Foundation
sqrt(25)
pow(2,3)
floor(23.7)
ceil(23.7)
abs(-21)
max(10,20)
min(10,20)
// gives back a random Int in the range of 1 to 100 inclusive
let x = Int.random(in:1...100)
print(x)
Also, for pi, use:
Double.pi
Float.pi
CGFloat.pi
Back to the Top
=================================
=================================
Lists (Arrays)
=================================
=================================
See more at:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html
Example 1:
----------
var players = [String]()
players.append("Bill")
players.append("Sue")
players.append("Jill")
players[0] = "Tim"
for player in players
{
print(player)
}
Example 2:
----------
var players:[String] = ["Bill", "Sue", "Jill"]
players[0] = "Tim"
for player in players
{
print(player)
}
Methods:
--------
append(object) - adds a new object to the end of the list
you can also do list += [object]
insert(object, at:1) - inserts the object at position 1
swapAt(1,3) - swaps the elements at postions 1 and 3
sort() - sorts the elements from small to large
min() - returns the smallest element
max() - returns the largest element
remove(at:2) - removes the element at position 2
removeAll() - removes all elements from the list
removeFirst() - removes and returns the first element
removeLast() - removes and returns the last element
popLast() - removes and returns the last element (Optional)
first - returns the object in the zero position (Optional)
last - returns the object in the last position (Optional)
startIndex - accesses property, value of starting index
endIndex - accesses property, value of ending index
isEmpty - accesses property, value of true if empty
count() - returns the number of elements in the list
reversed() - returns the array in the reversed order
=========================================================
var myArray: [String] = ["One", "Two", "Three"]
print (myArray[0])
print (myArray[1])
print (myArray[2])
var entries = myArray.count
=========================================================
=========================================================
var myArray: [String] = ["One", "Two", "Three"]
myArray.append("Four")
myArray.append("Five")
myArray.append("Six")
=========================================================
=========================================================
var myArray: [String] = ["One", "Two", "Three"]
myArray += ["Four", "Five", "Six"]
=========================================================
=========================================================
var myArray: [String] = ["Two", "Three"]
myArray.insert("One", atIndex: 0)
=========================================================
=========================================================
var myArray: [String] = ["One", "Two", "Three"]
myArray.removeAtIndex(1)
for myString in myArray
{
print(myString, terminator:" ") // stays on same line
}
=========================================================
Back to the Top
=================================
=================================
=================================
Trimming white space from a String
=================================
=================================
=================================
// Swift 3
func trim(_ str: String) -> String {
return str.trimmingCharacters(in: CharacterSet.whitespaces)
}
// Swift 4 and 5
func trim(_ str: String) -> String {
return str.trimmingCharacters(in: .whitespaces)
}
Back to the Top
=================================
=================================
Tuples (Immutable Lists)
=================================
=================================
Back to the Top
=================================
=================================
Dictionary
=================================
=================================
A dictionary has key-value pairs.
The keys cannot be changed, but the
values can be changed.
If you reference an item and the key
does not exist, you will get an error.
Methods:
Back to the Top
=================================
=================================
Lists 2D (Arrays 2D)
=================================
=================================
Example 1:
----------
var numbers = [ [80, 90, 95], [83, 87, 91], [93, 95, 97] ]
for r in 0..<numbers.count
{
for c in 0..<numbers[r].count
{
print(numbers[r][c], terminator:" ")
}
print() // moves to the next line
}
Example 2:
----------
var numbers = [[Int]]()
for _ in 1...3
{
var row = [Int]()
for _ in 1...4
{
row.append(0)
}
numbers.append(row)
}
Example 3:
----------
var rectangles = [[Rectangle]]()
for _ in 1...3
{
var row = [Rectangle]()
for _ in 1...4
{
row.append(Rectangle(15,20))
}
rectangles.append(row)
}
Example 4:
----------
var players = [[String]]()
playersRow = ["Bill", "Sue", "Jill"]
players[0].append(playersRow)
playersRow = ["Sam", "Tia", "Bob"]
players[1].append(playersRow)
for r in 0..<players.count
{
for c in 0..<players[r].count
{
print(players[r][c], terminator:" ")
}
print() // moves to the next line
}
Back to the Top
=================================
=================================
Classes
=================================
=================================
// Declaration of a class
// A class is a template that we can use
// at runtime to build a box in RAM memory that can
// hold information about 1 Student (or 1 Person, or 1 grocery item, ...)
//
// THIS BOX (or boxes) that we build at runtime to hold our information is
// called an object.
//
// ANOTHER WAY TO THINK OF A CLASS object is to think of it as a
// container (a box, a sack, a house, a mailbox, ...)
// THINK about building a house (or anything).
// We need a blue print!
// We can store information (with variables)
// and we can store functions to allow us to
// access the data and/or modify the data, or
// do stuff with our data.
// 1 Student Object
//
// We can create the object using the command or instruction:
// var student = Student("Tom", "Baker", "tb78654", 90)
//
// If we have a variable called student that
// refers to this object in RAM memory, we
// use commands or instructions like:
// student.firstName
// student.lastName
// student.grade
//
// This command or instruction would create room in RAM memory that
// could hold our information. It will run our init function after
// reserving room in the RAM that will put the info in the object
// for us.
//
// The variable named student would actually hold the memory address of where
// the object was created in RAM memory, and thus we say that it refers to
// (or points to) the object. RAM memory is byte addressable.
// We have byte 0, byte 1, byte 2, ... byte 78456, byte 78455, ...
// The OS determines where our object will be stored in RAM memory.
// The OS keeps a map of all used memory.
// So, maybe we would get a location starting at byte 78456,
// and thus student would hold that number for us.
// student
// ============
// | 78456 |
// ============
//
// student would refer to this object stored at
// memory location 78456
//
// Location 78456
// =====================================
// | firstName |
// | ============================= |
// | | "Tom" | |
// | ============================= |
// | |
// | lastName |
// | ============================= |
// | | "Baker" | |
// | ============================= |
// | |
// | id | |
// | ============================= |
// | | tb78654 | |
// | ============================= |
// | |
// | grade | |
// | ============================= |
// | | 90 | |
// | ============================= |
// | |
// | init |
// | ============================= |
// | | code goes here | |
// | | code goes here | |
// | | code goes here | |
// | | code goes here | |
// | | code goes here | |
// | ============================= |
// | |
// | More functions ... |
// | |
// =====================================
Example 1:
----------
# A class is sometimes referred to as record.
# A class is a container. It holds information
# and can have functions.
# So, think of a big box with smaller boxes inside
# to hold the data, and other boxes to hold the
# computer instructions.
# A variable really just refers to a box that holds
# information. (integers, floats, strings, and even
# objects.
# A function really just refers to a box that holds
# computer instructions.
# A class is like a template that tells the computer
# how to create an object with this information inside
# of it.
import Foundation
// to inherit, do
// class Person: SuperClass
// where SuperClass is the name
// of the class that you want to inherit
class Person
{
var firstName = "" // or var firstName: String
var lastName = "" // or var lastName : String
var age = 0 // or var age: Int
// etc.
init()
{
firstName = ""
lastName = ""
age = 0
}
init(_ firstName:String, _ lastName:String, _ age:Int)
{
self.firstName = firstName
self.lastName = lastName
self.age = age
}
func getFirstName() -> String {
return firstName
}
func getAge() -> Int {
return age
}
func setAge(_ age:Int)
{
self.age = age
}
func printMessage() {
print ("Hello")
}
// a class or static function
// you call class functions by using the name
// of the class
// var color = Person.getFavoriteColor()
class func getFavoriteColor() -> String
{
return "Red"
}
}
// In order to create a Person object you can:
var person = Person("Sue", "Baker", 16)
var firstName = person.getFirstName()
person.setAge(17)
print("Your first name is " + firstName)
print("You are \(person.getAge()) years old.")
Example 1: A Book class
=====================
import Foundation
class Book {
var title: String = ""
var author: String = ""
var description: String = ""
// init constructor
// getter and setter methods
// helper methods
}
Example 2:
----------
// A Point class
//
// We can create the object using the command or instruction:
// var point = Point(2, 5)
//
// If we have a variable called point that
// refers to this object in RAM memory, we
// use commands or instructions like:
// point.x
// point.y
// point
// ============
// | 78456 |
// ============
//
// point would refer to this object stored at
// memory location 78456
//
// Location 78456
// =====================================
// | x |
// | ============================= |
// | | 2 | |
// | ============================= |
// | |
// | y |
// | ============================= |
// | | 5 | |
// | ============================= |
// | |
// | |
// | init |
// | ============================= |
// | | code goes here | |
// | | code goes here | |
// | | code goes here | |
// | | code goes here | |
// | | code goes here | |
// | ============================= |
// | |
// | More functions ... |
// | |
// =====================================
import Foundation
class Point
{
var x = 0
var y = 0
init(_ x:Int, _ y:Int)
{
self.x = x
self.y = y
}
func getX() -> Int {
return x
}
func getY() -> Int {
return y
}
func getPoint() -> String
{
return "(" + String(self.x) + ", " + String(self.y) + ")"
}
}
var point1 = Point(3, 5) // creates the object and puts 3 and 5 inside it
print(point1.x) // prints 3 OR point1.getX()
print(point1.y) // prints 5 OR point1.getY()
var point2 = Point(6, 7)
print(point2.x) // prints 6 OR point2.getX()
print(point2.y) // prints 7 OR point2.getY()
print(point1.getPoint()) // prints (3, 5)
print(point2.getPoint()) // prints (6, 7)
What other classes might be useful for an app to have?
Back to the Top
=================================
=================================
Reading from the Console
=================================
=================================
NOTE: readLine always returns a String as an Optional,
so you may want to unwrap it use a if let
statement to see if it is valid data.
NOTE: readLine requires import Foundation
Example 1:
import Foundation
print("Enter your first name: ", terminator:"")
var firstName = readLine(strippingNewline:true)!
print(firstName)
Example 2:
import Foundation
print("Enter the value for x: ", terminator:"")
var x = Int(readLine(strippingNewline:true)!)!
print(x)
Back to the Top
=================================
=================================
if else statements
=================================
=================================
Sample 1:
var x = 8
var y = 12
if x > y
{
print(x, "is bigger than", y)
}
Sample 2:
var x = 8
var y = 12
if x > y
{
print(x, "is bigger than",y)
}
else
{
print(y, "is bigger than",x)
}
Sample 3:
var x = 8
var y = 12
if x > y
{
print(x, "is bigger than",y)
}
else if y > x
{
print(y, "is bigger than",x)
}
else
{
print(y, "is the equal to",x)
}
Sample 4:
var temp = 75
if temp >= 90
{
print("It is", temp, "degrees outside. It is so hot!")
print("I really hate this weather unless I am at the pool!")
}
else if temp >= 80
{
print("It is", temp, "degrees outside. It is a little warm!")
}
else if temp >= 65
{
print("It is", temp, "degrees outside. It is a great day!")
print("I really love this weather!")
}
else if temp >= 40
{
print("It is", temp, "degrees outside. It is a little cool out there!")
print("I am not very fond of cool weather!")
}
else
{
print("It is", temp, "degrees outside. It is very cold out there!")
print("I really hate this weather!")
}
Sample 5:
var let x = 9
var if x == 10
{
print("x is 10")
}
else if x == 9
{
print("x is 9")
}
else
{
print("x is not 9 or 10")
}
Example 1:
var x:Int = 25
var y:Int = 8
if x > y
{
print(String(x) + " is greater than " + String(y))
// or print("\(x) is greater than \(y))"
}
Example 2:
var x:Int = 25
var y:Int = 8
if x > y
{
print(String(x) + " is greater than " + String(y))
// or print("\(x) is greater than \(y))"
}
Sample 3:
var x = 8
var y = 12
var z = 10
if x > y && x > z
{
print(x, "is bigger than", y, "and bigger than", z, ".")
}
else if y > x && y > z
{
print(y, "is bigger than", x, "and bigger than", z, ".")
}
else if z > x && z > y
{
print(z, "is bigger than", x, "and bigger than", y, ".")
}
else if x == y && x == z
{
print(x, y, z, "are all equal")
}
else if x == y
{
print(x, y, "are equal")
}
else if x == z
{
print(x, z, "are equal")
}
else if y == z:
{
print(y, z, "are equal")
}
else
{
print("It should not ever get here.")
}
Back to the Top
====================
====================
Ternary Operators
====================
====================
condition ? do true : do false
print("Largest number is \(x > y ? x : y)")
// Example:
// if x = 5 and y = 7
var x = x > y ? 5 : 8 // x will be 8
Back to the Top
=================================
=================================
string
=================================
=================================
NOTE: YOU CAN NOT DIRECTLY ACCESS A
CHARACTER IN A String
See the following website for more help.
https://swiftludus.org/swfit-strings-tutorial/
NOTE: In Swift 4, the characters property of the
String class does NOT exist. So, instead
of using str.characters.count, use str.count
var str:String = "Abc"
OR
var str = "Abc"
if str.isEmpty
{
// do something
}
var count = str.characters.count // version 3
var count = str.count // version 4
// count is 3
let upper = str.uppercased()
// upper is "ABC"
let lower = str.lowercased()
// lower is "abc"
// version 3
for character in str.characters {
print(character)
}
// version 4
for character in str {
print(character)
}
// version 3
for index in str.characters.indices {
print("\(str[index])")
}
// version 4
for index in str.indices {
print("\(str[index])")
}
Example: Swift 4
================
let str = "sunday, monday, happy days"
for char in str {
print("Found character: \(char)")
}
Example: Swift 4
================
var myIndex = str.startIndex
while myIndex < str.endIndex {
print(str[myIndex])
myIndex = str.index(after: myIndex)
}
Example: Swift 4
================
for myIndex in myString.indices {
print(myString[myIndex])
}
Example: Swift 4 (BEST WAY)
================
let s = "Hello"
for ch in s {
print(ch)
}
// prints out ASCII characters
for ch in s.utf8
{
print(Int(ch))
}
// converts an Int to a character
let value = UnicodeScalar(97)! // must unwrap
let ch = Character(value)
print(ch)
let b2 = String(12, radix: 2) // converts 12 to "1100"
let b8 = String(12, radix: 8) // converts 12 to "14"
let b16 = String(12, radix: 16) // converts 12 to "c"
Back to the Top
=================================
=================================
=================================
Optionals
=================================
=================================
=================================
var age: Int?
age = 23
print(age) // outputs Optional(23)
print(age!) // outputs 23
// a safer way
if let myAge = age {
print(myAge) // outputs 23
print(myAge!) // compiler ERROR
print(age) // outputs Optional(23)
}
=================================
var age: Int?
age = 23
if let myAge = age {
print(myAge) // outputs 23
}
==================================
var age: Int!
age = 23
print(age) // outputs 23 (auto unwrapped)
if let myAge = age {
print(age) // outputs 23 (auto unwrapped)
print(myAge) // outputs 23
}
var age: Int! // here goes the exclamation mark
age = 23
print(age) // outputs 23 (auto unwrapped)
Back to the Top
=================================
=================================
Reading from and Writing to files
=================================
=================================
Back to the Top
================
================
Creating Objects
================
================
import Foundation
// to inherit, do
// class Person: SuperClass
// where SuperClass is the name
// of the class that you want to inherit
class Person {
var firstName = "" // or var firstName: String
var lastName = "" // or var lastName : String
var age = 0 // or var age: Int
// etc.
init() {
firstName = ""
lastName = ""
age = 0
}
init(firstName:String, lastName:String, age:Int) {
self.firstName = firstName
self.lastName = lastName
self.age = age
}
func getFirstName() -> String {
return firstName
}
func getAge() -> Int {
return age
}
func printMessage() {
print "Hello"
}
// a class or static function
// you call class functions by using the name
// of the class
// var color = Person.getFavoriteColor()
class func getFavoriteColor() -> String {
return "Red"
}
}
In order to create a Person object you can:
// creates a variable that can refer to a Person object
var person: Person
// creates the Person object
person = Person()
OR
person = Person("Sue", "Baker", 16)
OR
person = Person(firstName:"Sue", lastName:"Baker", age:16)
var firstName = person.getFirstName()
Example: A Book class
=====================
import Foundation
class Book {
var title: String = ""
var author: String = ""
var description: String = ""
}
Back to the Top
Simple Programs-Reading from the Console
===================
===================
resultGrade = int(input("What grade did you get? "))
print(resultGrade)
Back to the Top
===================
===================
A Simple Program With Functions
===================
===================
// Pay Check
// Test Thursday this week
// Write a function to print
// the title "Pay Check"
// and two blank lines
func printTitle()
{
print("Pay Check")
print()
print()
}
// Write a function to find the
// pay when given the hours
// worked and rate of pay.
// Over time should get time and a half
func getThePay(_ hoursWorked:Double, _ rateOfPay:Double) -> Double
{
let pay = hoursWorked * rateOfPay
return pay
}
// MAIN PROGRAM
//
// print the title "Pay Check"
// print two blank lines
// call a function
printTitle()
// prompt the use to enter the
// hours worked
print("Enter the number of hours worked: ", terminator:"")
// Create a variable called
// hoursWorked (use let) and
// read in the number of hours worked
// (use a double variable)
let hoursWorked = Double(readLine(strippingNewline:true)!)!
// prompt the use to enter the
// rate of pay
print("Enter the rate of pay: ", terminator:"")
// Create a variable called rateOfPay
// (use let) (use a Double variable)
// read in the value
let rateOfPay = Double(readLine(strippingNewline:true)!)!
// print a blank line
print()
// Declare a variable called
// amount (use let)
// Call a function to get the amount of pay
let amount = getThePay(hoursWorked, rateOfPay)
// print out the amount of pay
// "The amount of pay is $xxx.xx"
print("The amount of pay is $\(amount)")
===================
===================
A Simple Program
===================
===================
===================
===================
A Simple Program
===================
===================
===================
===================
A Simple Program
===================
===================
=================================
=================================
=================================
=================================
Back to the Top
Other commands:
Back to the Top
=================================
=================================
Other Labs
=================================
=================================
Quad Form
Area of a Rectangle
Volume of a Sphere
Roman Numerals
Fibonacci
Student Grades
(average, standard deviation, semester grades, ...)
Tic-Tac-Toe
Hangman
Encrypt Data
Magic Squares
Matrix Battle:
Checkers:
Tax Table
Back to the Top
Back to the Top
=================================
=================================
Importance of Computers and Intro to Python
=================================
=================================
Importance of Software
Software or computer programs are what makes a
computer do stuff. Without software, a computer
is nothing but a big paper weight. It takes both
hardware and software (computer programs, apps,
code, ...).
There are millions of lines of computer code
(instructions, commands) in a computer, phone,
car, automation lines, robots, planes, trains, etc.
Software is everywhere!!!
Businesses use it to keep track of products,
employees, etc. Schools use it to keep track
of student information, grades, etc. as well as
to keep track of employees, pay, purchasing, etc.
Every company uses computers and lots of software
to run their operations, including schools, etc.
Software is a big mystery to a lot of people!
And it has caused a lot of problems in industry,
education, etc.
I have been told several times that I was fired by
assistant principals and company execs because they
did not understand software (I luckily never got
fired).
I read once a few years ago that more companies have
gone bankrupt because of poor decisions about software
(including a company that I used to work for).
Hardware and Software (Working together)
CPU
?????????
This component is responsible for carrying
out our instructions (commands).
RAM Memory
?????????
This is very fast memory that is used to store
the OS instructions, all program data, and every
program's code that is open. The OS is loaded
when the computer is first started (turned on).
We call this booting the computer. When you open
an application, it is loaded (copied) from external
storage into the RAM memory along with the data.
When you terminate a program, the program instructions
and data are erased from the RAM memory.
When you shut down (turn off) your computer, all of
the programs and data in RAM memory are gone. It is
like turning off a light.
ROM Memory
?????????
This memory is what starts your computer system when
you turn it on (boot it). It contains the basic start
up commands to allow you to set which drive is the bootable
drive, the boot order, the start up commands to load the
operating system into RAM memory, and more.
Mother Board
This hardware is used to connect the CPU, RAM memory,
drives, ports, etc.
External Storage
Hard Drive (ssd drives, flash drives, etc.)
These devices permanently hold your programs and data,
and if bootable, holds the OS as well.
Software
Computer programs (apps) including the OS.
Operating System (OS) (Windows, Mac OS, Linux, ...)
This is the program that is in total control of the
machine. It displays the desktop or command line,
and allows you to copy files, delete files, organize
files (like in folders, etc.), etc.
What is a computer program? (application)
A computer program is a sequence of instructions
(commands, statements) for a computer to follow.
What is a computer programming language?
A computer language contains high level
commands to allow you to communicate with
the CPU.
Can you name some computer langages?
C, C++, ?????????
Compilers vs. Interpreted languages
Many languages need to be compiled or translated
into machine code before you can run (execute)
them. (C, C++, Pascal, Java, Swift, etc.)
Interpreted languages are converted to machine
code as they run. Interpreted languages are
generally slightly slower (less efficient) than
compiled code. (Python)
Think about how you might talk to a French person
if you did not speak any French.
What is an IDE?
An IDE is an ?????????.
It contains an editor for typing in our code
(instructions, commands), a button or menu item
to run our program, and other utilities.
IDLE, JDoodle for Python, Eclipse are examples of
some IDE's.
What is an algorithm?
An algorithm is a step by step set of ?????????
to someone or some thing to carry out a task.
What does it mean to execute or run a program?
It means to carry out the instructions in your
program.
What is a variable?
A variable refers to a place in RAM memory
where you can store information (numbers,
strings of characters, etc.) Think of box
that holds data.
Variables have names so that us humans can
refer to them. Variable names should be
descriptive of what kind of information they
refer to.
Names must start with a letter of the alphabet.
After that you can have more letters or numbers or
the underscore(_) character. However, you can not
have a space character or any other special characters
in your name. We should always user lower case letters,
except on word boundaries for long names. Variables
can not be key words of the programming language.
Also, names are case sensitive. So, X and x are actually
different names.
Some examples of variable names:
x
y
answer
b
num
totalSum
answer x y
-------- -------- --------
| 12 | | 7 | | 5 |
-------- -------- --------
A simple Swift set of instructions (commands):
print("Swift Sample Program")
print()
var x = 7 // or let x = 7 if you are not going to change x's value
var y = 5 // or let y = 5 if you are not going to change y's value
let answer = x + y
print(answer)
NOTE: Swift will give a warning if you use var to define a variable
but you never change the value later. Use var to define a variable
that you plan to change later, otherwise use let.
Another simple Swift set of instructions (commands):
// readLine is no longer supported
// as of Swift 3 for iOS apps.
// However, it is supported for console apps.
NOTE: All input using readLine or accessing UITextField will
give you back an Optional type. You will either need to unwrap
it with the ! or convert it with an if let statement.
NOTE: readLine is no longer supported
as of Swift 3 for playground.
However, it is supported for console apps.
# The # tells the interpreter to ignore the line
print("Swift Sample Program 2")
print()
print("Enter your first name: ", terminator:"")
var myString = readLine(strippingNewline:true)! # unwrapped with !
Another simple Swift set of instructions (commands):
print("Enter the value for x: ", terminator:"")
let x = Int(readLine(strippingNewline:true)!)! # unwrapped with !
print("Enter the value for y: ", terminator:"")
let y = Int(readLine(strippingNewline:true)!)! # unwrapped with !
let answer = x + y
print(x, "+", y, "is", answer)
Some examples of illegal variable names:
total Sum
num@
sum!
Back to the Top
=================================
=================================
Programming Assignments
=================================
=================================
Back to the Top
############################################################################
Your Name and Favorites (print)
############################################################################
Program #0A - Write a program that prints out your name, a blank line, and:
My favorite color is ???.
My favorite song is ???.
My favorite tv program is ???.
My favorite food is ???.
Remember, a computer runs or executes our commands (instructions)
in the order that we specify.
You will be using the print instruction (command).
Example: print("I love music")
Sample Output:
My name is John Smith (use your name)
My favorite color is red.
My favorite song is Fun, Fun, Fun.
My favorite tv program is Star Trek.
My favorite food is turkey.
############################################################################
Your Name and Favorites (print)
############################################################################
Program #0B - Write a program that prints out your name, a blank line, and some math expressions:
Remember, a computer runs or executes our commands (instructions)
in the order that we specify.
You will be using the print instruction (command).
Type in the following code or make up some on your own:
print("My name is John Smith") // Use your name
print("2 + 8 - 5")
print(2 + 8 - 5)
print()
print("2 * 8 - 5")
print(2 * 8 - 5)
print()
print("2 * 8 / 4")
print(2 * 8 / 4)
print()
Sample Output:
2 + 8 - 5
5
2 * 8 - 5
11
2 * 8 / 4
4
############################################################################
Welcome (Read from the keyboard or stdin, print, String concatenation (+)
############################################################################
Program #1 - Write a program that prompts the user to enter their first name.
Print out Welcome first name! (use the + operator to join strings)
The command or instruction to let the user enter information is:
firstName = input("Enter your first name: ")
firstName is a variable name that I made up.
Variables can hold data (Strings, numbers, etc.)
When you make up a variable name to hold data, you must
start with a letter of the alphabet, followed by more
letters and/or digits (no spaces or special characters).
Here is some starting code that you can type in to get
started.
import Foundation
print("Welcome")
print()
print()
print("Enter your first name: ", terminator:"")
let firstName = readLine(strippingNewline:true)!
// print out a blank line
// now print out "Welcome", firstName, "!")
// or use interpolation
// print("Welcome \(firstName)!")
Sample Output:
Welcome
Enter your first name: (enter your name)
Welcome Tom!
############################################################################
Welcome (Read from the keyboard or stdin, print, String concatenation (+)
############################################################################
Program #2 - Write a program that prompts the user to enter their first name.
Then prompt the user to enter their last name.
Print out Welcome, first name space last name
import Foundation
print("Welcome")
print()
print()
print("Enter your first name: ", terminator:"")
let firstName = readLine(strippingNewline:true)!
// Now ask the user to enter the last name and then
// read in the last name.
// Next print a blank line
// Now print out "Welcome", firstName, "!")
Sample Output:
Welcome
Enter your first name: (user enters first name like maybe Tom)
Enter your last name: (user enters last name like maybe Baker)
Welcome, Tom Baker!
############################################################################
Area of a Rectangle (Read from the keyboard or stdin (input), print(), math operations)
############################################################################
Program #3 - Write a program that prompts the user for the length and width
of a rectangle, calculates the area, and prints out:
The area of the rectangle is ???
Here is some starting code.
print("Area of a Rectangle")
print()
print()
print("Enter the length of a rectangle: ", terminator:"")
let length = Int(readLine(strippingNewline:true)!)!
etc.
Sample Output:
Area of a Rectangle
Enter the length of a rectangle: (user enters maybe 8)
Enter the width of a rectangle: (user enters maybe 5)
The area is 40 square units.
Here is more help:
// When you write a program (application or app)
// We start with what we want our program to do.
// We want our program to find the area of a rectangle
// when we are given the length and width.
// We then sketch out or type in a sample output (see example above).
// Then we plan:
// Step 1: print out a title and 2 blank lines
// Step 2: We ask (prompt) the user to enter the length
// Step 3: We wait for the user to enter the length
// Step 4: We convert the String input into a Int
// Step 5: We store the Int into a variable named length
// Step 6: We ask (prompt) the user to enter the width
// Step 7: We wait for the user to enter the width
// Step 8: We convert the String input into a Int
// Step 9: We store the Int into a variable named width
// Step 10: We calculate the area and store it in a variable called area
// Step 11: We print a blank line
// Step 12: We print out the area
// Step 1:
// We print the title and two blank lines
print("Area of a Rectangle")
print()
print()
// blank lines in the source code
// help the readability
// Step 2:
// Here we prompt (ask) the user
// to enter the length
print("Enter the length: ", terminator:"")
// Steps 3, 4, and 5:
// Now we wait for the user to enter the length.
// Once they type in a number and press return,
// we convert the String number into an Int
// and store it in the variable length.
// This is like a box named length.
// Think of mailboxes, shoe boxes, etc.
let length = Double(readLine(strippingNewline:true)!)!
// Step 6:
// Here we prompt (ask) the user
// to enter the width
print("Enter the width: ", terminator:"")
// Steps 7, 8, and 9:
// Now we wait for the user to enter the width.
// Once they type in a number and press return,
// we convert the String number into an Int
// and store it in the variable width.
// This is like a box named width.
// Think of mailboxes, shoe boxes, etc.
let width = Double(readLine(strippingNewline:true)!)!
// Step 10:
// Here we define a variable called area
// This is like a box that is named area
// and store the area.
let area = length * width
// Step 11:
// Next we print a blank line
print()
// Step 12:
// Finally we print out the value stored in area.
// \(area)
// gets replaced by the value of the variable.
// Think of what is in the box.
// Apple calls this interpolation.
print("The area is \(area) square units.")
/*
Sample Run:
Area of a Rectangle
Enter the length: 5
Enter the width: 6
The area is 30 square units.
*/
############################################################################
Area of a Circle (Read from the keyboard (input), print(), math operations)
############################################################################
Program #4 - Write a program that prompts the user for the radius of a circle,
calculate the area, and then print out:
The area of the circle is ???.???? square units.
Use Double.pi for pi.
Sample Output:
Area of a Circle
Enter the radius of a circle: (user enters maybe 5)
The area of the circle is 78.53975 square units.
Here is more help:
// When you write a program (application or app)
// We start with what we want our program to do.
// We want our program to find the area of a Circle
// when we are given the radius.
// We then sketch out or type in a sample output.
// Then we plan:
// Step 1: print out a title and 2 blank lines
// Step 2: We ask (prompt) the user to enter the radius
// Step 3: We wait for the user to enter the radius
// Step 4: We convert the String input into a Double
// Step 5: We store the Double into a variable
// Step 6: We calculate the area and store it
// Step 7: We print out the area
// Step 1:
// Here we print the title and two blank lines
print("Area of a Circle")
print()
print()
// blank lines in the source code
// help the readability
// Step 2:
// Here we prompt (ask) the user
// to enter the radius
print("Enter the radius: ", terminator:"")
// Steps 3, 4, and 5:
// Now we wait for the user to enter the radius.
// Once they type in a number and press return,
// we convert the String number into a Double
// and store it in the variable radius.
// This is like a box named radius.
// Think of mailboxes, shoe boxes, etc.
let radius = Double(readLine(strippingNewline:true)!)!
// Step 6:
// Here we define a variable called area
// This is like a box that is named area
// and store the area.
let area = Double.pi * radius * radius
// Step 7:
// Next we print a blank line
print()
// Finally we print out the value stored in area.
// \(area)
// gets replaced by the value of the variable.
// Think of what is in the box.
// Apple calls this interpolation.
print("The area is \(area) square units.")
/*
Sample Run:
Area of a Circle
Enter the radius: 5
The area is 78.53981633974483 square units.
*/
############################################################################
Celsius to Fahrenheit (Read from the keyboard(input), print(), math operations)
############################################################################
Program #5 - Write a program that prompts the user for the Fahrenheit temperature,
calculate the Celsius temperature and then print out:
Use: let celsius = 5 / 9 * (fahrenheit - 32)
The Celsius temperature is ???.???? degrees.
Sample Output:
Fahrenheit to Celsius
Enter the Fahrenheit temperature: (user enters maybe 70)
The Celsius temperature is ???.???? degrees.
(70 degrees Fahrenheit is about 21.1111111111111 degrees in Celsius)
// Step 1: Print the title "Area of a Circle"
// and then 2 blank lines
??????
??????
??????
// Step 2:
// Here we prompt (ask) the user
// to enter the Fahrenheit temperature
?????("???????????????: ", terminator:"")
// Steps 3, 4, and 5:
// Now we wait for the user to enter the Fahrenheit temperature.
// Once they type in a number and press return,
// we convert the String number into a Double
// and store it in the variable fahrenheit.
// This is like a box named fahrenheit.
// Think of mailboxes, shoe boxes, etc.
??? fahrenheit = Double(readLine(strippingNewline:true)!)!
// Step 6:
// Here we define a variable called celsius.
// This is like a box that is named celsius
// and store the celsius temperature.
// We will need to do the calculation on the right
// side of =
??? ??????? = ?????
// Step 7:
// Next we print a blank line
print()
// Finally we print out the value stored in celsius.
// \(celsius)
// gets replaced by the value of the variable.
// Think of what is in the box.
// Apple calls this interpolation.
// The output should be:
/ The Celsius temperature is ???.???? degrees.
// ???.???? should be replace with \(celsius)
print("???????????")
############################################################################
Surface Area of a Cube (Read from the keyboard(input), print(), math operations)
############################################################################
Program #6 - Write a program that prompts the user for the length of a side for a cube,
calculate the surface area (6*side*side), and then print out:
The surface area of the cube is ???.???? square units.
You can use the double type or an integer type for your variables.
Sample Output:
Surface Area of a Cube
Enter the length of one side: (user enters maybe 4)
The surface area is ???.???? square units
(if one side is 5, the surface area is 150.0 square units)
############################################################################
Batting Average (Read from the keyboard(input), print(), math operations)
############################################################################
Program #7A - Write a program that prompts the user for the number of hits,
the number of at bats, and the number of walks.
You can call your variables hits, atBats, and walks.
Find the batting average and the on base percentage:
battingAvg = hits / atBats
let onBasePCT = (hits + walks) / (atBats + walks)
Sample Output:
Batting Average
Enter the number of hits: (user enters maybe 2)
Enter the number of at bats: (user enters maybe 8)
Enter the number of walks: (user enters maybe 2)
The user's batting average is .250
The user's on base average is .400
// print the title and
// and then print two blank lines
print("?????????")
?????()
?????()
// Ask the user to:
// Enter the number of hits:
?????("????????????: ", terminator:"")
// Create a variable called hits (use let)
// Assign to hits the Int number that the
// user enters
??? ???? = ???(readLine(strippingNewline:true)!)!
// Ask the user to:
// Enter the number of at bats:
print("??????????????????????: ", terminator:"")
// Create a variable called atBats (use let)
// Assign to atBats the Int number that the
// user enters
??? ?????? = ???(readLine(strippingNewline:true)!)!
// Ask the user to:
// Enter the number of walks:
print("?????????????????????: ", terminator:"")
// Create a variable called walks (use let)
// Assign to walks the Int number that the
// user enters
??? ????? = ???(readLine(strippingNewline:true)!)!
print()
// Create a variable called battingAvg (use let)
// Assign to battingAvg Double(hits) / Double(atBats)
??? ????????? = ?????? / ??????????
// Create a variable called onBaseAvg (use let)
// Assign to onBaseAvg Double(hits + walks) / Double(atBats + walks)
??? ??????????? = ??????????
// print out "The user's batting average is xxx" where xxx
// is replaced with the value of the variable battingAvg
// Use interpolation \(battingAvg) instead of xxx
print(?????????????????????????)
// print out "The user's on base average is xxx" where xxx
// is replaced with the value of the variable onBaseAvg
// Use interpolation \(onBaseAvg) instead of xxx
print(?????????????????????????)
print()
/*
Sample Output
Batting Average
Enter the number of hits: 4
Enter the number of atBats: 8
Enter the number of walks: 2
The user's batting average is 0.5
The user's on base average is 0.6
*/
############################################################################
Throwing Percentage (Read from the keyboard(input), print(), math operations)
#### (also called passing percentage)
############################################################################
Throwing Percentage #7B - Write a program that prompts the user for the number
of passes completed and the number of passes thrown.
You can call your variables passesCompleted and passesAttempted.
Find the throwing percentage:
let throwingPCT = passesCompleted / passesAttempted
Sample Output:
Throwing Percentage
Enter the number of passes completed: (user enters maybe 4)
Enter the number of passes thrown: (user enters maybe 8)
The throwing percentage is .500
Outline:
// print the title and
// and then print two blank lines
print("?????????")
?????()
?????()
// Ask the user to:
// Enter the number of passes completed:
?????("????????????: ", terminator:"")
// Create a variable called passesCompleted (use let)
// Assign to passesCompleted the Int number that the
// user enters
??? ???? = ???(readLine(strippingNewline:true)!)!
// Ask the user to:
// Enter the number of passes passes attempted:
print("??????????????????????: ", terminator:"")
// Create a variable called passesAttempted (use let)
// Assign to passesAttempted the Int number that the
// user enters
??? ?????? = ???(readLine(strippingNewline:true)!)!
print()
// Create a variable called throwingPCT (use let)
// Assign to throwingPCT Double(passesCompleted) / Double(passesAttempted)
??? ????????? = ?????? / ??????????
// print out "The throwing percentage is xxx" where xxx
// is replaced with the value of the variable throwingPCT
// Use interpolation \(throwingPCT) instead of xxx
print(?????????????????????????)
print()
############################################################################
Winning Percentage (Read from the keyboard(input), print(), math operations)
############################################################################
Winning Percentage #7C - Write a program that prompts the user for the number
of wins and the number of losses.
You can call your variables wins and losses.
let winningPCT = wins / (wins + losses)
Find the winning percentage:
Sample Output:
Winning Percentage
Enter the number of wins: (user enters maybe 3)
Enter the number of losses: (user enters maybe 7)
The winning percentage is .300
Outline:
// print the title and
// and then print two blank lines
print("?????????")
?????()
?????()
// Ask the user to:
// Enter the number of wins:
?????("????????????: ", terminator:"")
// Create a variable called wins (use let)
// Assign to wins the Int number that the
// user enters
??? ???? = ???(readLine(strippingNewline:true)!)!
// Ask the user to:
// Enter the number of losses:
print("??????????????????????: ", terminator:"")
// Create a variable called losses (use let)
// Assign to losses the Int number that the
// user enters
??? ?????? = ???(readLine(strippingNewline:true)!)!
print()
// Create a variable called winningPCT (use let)
// Assign to winningPCT Double(wins) / Double(losses)
??? ????????? = ?????? / ??????????
// print out "The winning percentage is " where xxx
// is replaced with the value of the variable winningPCT
// Use interpolation \(winningPCT) instead of xxx
print(?????????????????????????)
print()
############################################################################
Slope of a Line (Read from the keyboard(input), print(), math operations, if else)
############################################################################
Program #7D - Write a program that prompts the user for two points (2D).
You can call your variables x1,y1 and x2,y2.
Find the slope of the line, and then print out:
The slope of the line is ???.????
slope = (y2 - y1) / (x2 - x1)
Sample Output:
The Slope of a Line
Enter the value for x1: (user enters maybe 1)
Enter the value for y1: (user enters maybe 1)
Enter the value for x2: (user enters maybe 2)
Enter the value for y2: (user enters maybe 2)
The slope of the line is ???.????
(The slope for (1,1) and (2,2) is 1.0)
Outline:
// print the title and
// and then print two blank lines
print("?????????")
?????()
?????()
// Ask the user to:
// Enter the value for x1:
?????("????????????: ", terminator:"")
// Create a variable called x1 (use let)
// Assign to x1 the Int number that the
// user enters
??? ???? = ???(readLine(strippingNewline:true)!)!
// Ask the user to:
// Enter the value for y1:
?????("????????????: ", terminator:"")
// Create a variable called y1 (use let)
// Assign to y1 the Int number that the
// user enters
??? ???? = ???(readLine(strippingNewline:true)!)!
print()
// Ask the user to:
// Enter the value for x2:
?????("????????????: ", terminator:"")
// Create a variable called x2 (use let)
// Assign to x2 the Int number that the
// user enters
??? ???? = ???(readLine(strippingNewline:true)!)!
// Ask the user to:
// Enter the value for y2:
?????("????????????: ", terminator:"")
// Create a variable called y2 (use let)
// Assign to y2 the Int number that the
// user enters
??? ???? = ???(readLine(strippingNewline:true)!)!
print()
// Create a variable called slope (use let)
// Assign to slope Double(?? - ??) / Double(?? - ??)
??? ????????? = ?????? / ??????????
// print out "The slope is xxx" where xxx
// is replaced with the value of the variable slope
// Use interpolation \(slope) instead of xxx
print(?????????????????????????)
print()
############################################################################
Letter Grades (Read from the keyboard, print, math operations, if else if)
############################################################################
Program #8 - Write a program that prompts the user for a numerical grade.
Find the letter grade, and then print out:
The letter grade is ?.
You can use an integer type for your input variable.
95 and above - A
87 - 94 - B
75 - 86 - C
70 - 74 - D
69 and below - F
Sample Output:
Letter Grades
Enter the numerical grade: (user enters maybe 82)
The letter grade is a C
Outline:
// print the title and
// and then print two blank lines
print("?????????")
?????()
?????()
// Ask the user to:
// Enter the numerical grade:
?????("????????????: ", terminator:"")
// Create a variable called numberGrade (use let)
// Assign to numberGrade the Int number that the
// user enters
??? ???? = ???(readLine(strippingNewline:true)!)!
print()
// Create a variable called letterGrade (use var)
// Assign to letterGrade the value of "" (for now)
??? ???? = ??
// Use an if else statement to find the letterGrade
// It has been started for you.
if numberGrade >= 95
{
// assign the value of "A" to letterGrade
??????
}
else if numberGrade >= 87
{
// assign the value of "B" to letterGrade
??????
}
// FINISH THIS PART
?????
// print out "The letter grade is a xxx" where xxx
// is replaced with the value of the variable letterGrade
// Use interpolation \(letterGrade) instead of xxx
print(?????????????????????????)
print()
############################################################################
Positive or Negative or Zero (Read from the keyboard, print, math operations,
if else if)
############################################################################
Program #9 - Write a program that prompts the user for a number,
and then prints out:
The number is positive or negative or zero.
You can use an integer type for your input variable.
Sample Output:
Positive or Negative or Zero?
Enter a number: (user enters maybe 7)
7 is a positive number.
Outline:
// print the title and
// and then print two blank lines
print("?????????")
?????()
?????()
// Ask the user to:
// Enter a number:
?????("????????????: ", terminator:"")
// Create a variable called number (use let)
// Assign to number the Int number that the
// user enters
??? ???? = ???(readLine(strippingNewline:true)!)!
print()
// Use an if else statement to find if the number
// is positive, negative, or zero, and then print
// out an appropriate message.
// It has been started for you.
if number > 0
{
// print out The number is positive.
??????
}
else ?? ??????? < ?
{
// print out The number is negative.
??????
}
else
{
// print out The number is zero.
??????
}
print()
############################################################################
Multiplication Table (Read from the keyboard, print,
math operations, for loops)
############################################################################
Program #10 - Write a program that prompts the user to enter a number.
Print out a multiplication table for that number.
Sample Output
Multiplication Table
Enter a number: 7
7 * 0 is 0
7 * 1 is 7
7 * 2 is 14
7 * 3 is 21
7 * 4 is 28
7 * 5 is 35
7 * 6 is 42
7 * 7 is 49
7 * 8 is 56
7 * 9 is 63
Goodbye!
Outline
import Foundation
// print the title Multiplication Table
???????
// print two blank lines
??????
??????
// Prompt the user to Enter a number:
print(?????????, terminator:"")
// Declare a variable called num (use let).
// Read in the number and convert it
// into an Int
??? ??? = ???(readLine(strippingNewline: true)!)!
// Now let's print out the table
// We will loop from 0...9
for x in ?...?
{
// Declare a variable called result (use let)
// and assign it num * x
??? ?????? = ????? * ?
// We will print out
// num, x, and result
?????("\(???) * \(?) is \(?????)")
}
// print a blank line
?????
// print Goodbye!
?????
// print a blank line
?????
############################################################################
The Guessing Game(Read from the keyboard, print,
math operations, while loops)
############################################################################
Program #11 - Write a program that prompts the user to enter a number.
The user will be guessing a number between 1 - 100.
Use var number = Int.random(in:1...100)
They will get 7 guesses to win, else they lose.
You can use the integer type for your variable.
Use a for loop. for numTries in 1...7
Sample Run:
The Guessing Game
low = 1 high = 100
Enter your guess: 50
You number is too low!
low = 51 high = 100
Enter your guess: 75
Your number is too high!
low = 51 high = 74
Enter your guess: 63
Your number is too high!
low = 51 high = 62
Enter your guess: 56
You number is too low!
low = 57 high = 62
Enter your guess: 60
Your number is too high!
low = 57 high = 59
Enter your guess: 58
You number is too low!
low = 59 high = 59
Enter your guess: 59
You guessed the number!!!
An Outline for the Guessing Game
import Foundation
// print out the title "The Guessing Game"
// print two blank lines
// declare a variable called low and set it to 1
// then declare a variable called high and set it to 100
// declare a variable called number to hold the
// computer's number that the user will try to guess
// use ????????
// declare a variable called userGuess that will hold the
// user's guess and set it to 0.
// declare a variable called numTries that will hold the
// user's number of tries and set it to 1.
// now we will loop
while numTries <= 7
{
print("low =",low," high =", high)
// ask the user to enter your guess and store
// it in a variable called userGuess
// convert the input to an int
// check and see if the userGuess == number
// and if so break out of the loop
// the keyword to break out of the loop is break
// elif check and see if the userGuess < number
// and if so:
// print out "Your number is too low!"
// and then set low = userGuess + 1
// else:
// print out "Your number is too high!"
// and then set high = userGuess - 1
// add 1 to the variable location called numTries
print()
} // end of while loop
print()
// check and see if userGuess == number
// and if so print out "You guessed the number!!!"
// else
// print out "You lose. The number was",number
############################################################################
The Dice Game(Read from the keyboard, print,
math operations, while loops)
############################################################################
Program #12 - Write a program that simulates tossing dice.
The user will toss dice (2).
You will be getting two numbers between 1 and 6 (inclusive).
die1 = random.randrange(1,7)
die2 = random.randrange(1,7)
You will add these numbers together.
If the sum is 7 or 11, the player wins, else they lose.
You can use the integer type for your variable.
Sample Run:
The Dice Game
Do you want to toss the dice (y or n)? y y
You tossed a 7 . You win!
Do you want to toss the dice (y or n)? y
You tossed a 6 . You lose!
Do you want to toss the dice (y or n)? y
You tossed a 7 . You win!
Do you want to toss the dice (y or n)? y
You tossed a 12 . You lose!
Do you want to toss the dice (y or n)? n
Wins: 2
Losses: 2
Thank you for playing dice!!!
Outline:
// print out the title "The Dice Game"
// print 2 blank lines
// define variables
// wins, losses, die1, die2, and sum, and set them to zero
while true
{
print("Do you want to toss the dice (y or n)? ", terminator:"")
let answer = readLine(strippingNewline:true)!
// check and see if the answer is equal to "n", and if so break
// toss the dice
die1 = ????? // get a random number from 1 to 6 inclusive
die2 = ????? // get a random number from 1 to 6 inclusive
print("You tossed a", die1, "and a", die2)
print()
// find the sum of the two die
sum = ??????
// check and see if your sum is a 7 or an 11 (if so you win!)
if ???? == ? || ????? == ?
{
// print a You win! message and then add 1 to your wins variable
????
????
}
else
{
// print a You lose! message and then add 1 to your losses variable
????
????
}
print()
}
print()
// print out the number of wins and losses (with a message)
????????
// print out a thank you for playing the game
// print out a Goodbye message
############################################################################
Factors of a Number
############################################################################
Program #13 - Write a program that prompts the user to enter a number.
Print out all of the factors of the number
In order to see if a number is a factor use:
if number % d == 0 where d is your divisor
You will need a loop like the following:
for d in 1...number
You can use the integer type for your variable.
Sample Output:
Factors of a Number
Enter a number: 18
The factors of num are: 1 2 3 6 9 18
Goodbye!
Outline
//
// main.swift
// Factors of a Number
//
// print out the title Factors of a Number
??????????
// print two blank lines
???????
???????
// Prompt the user to enter a number.
?????("Enter a number: ", terminator:"")
// Declare a variable called num (use let).
// Read in the number and convert it
// into an Int
??? ??? = ???(readLine(strippingNewline: true)!)!
// print a blank line
?????
// print "The factors of ??? are: "
// where ??? is the value of num
?????(???????, terminator:"")
// Now we will print out all of the factors of num
// one at a time.
// Write a for loop that loops from 1...num
// Use d for your variable name.
for ? ?? ?????????
{
// Check and see if num is divisible by d
if ??? % ? == ?
{
// print out the value of d and a space
print("\(?) ", terminator:"")
} // end of if statement
} // end of for loop
// print two blank lines
??????
??????
// print "Goodbye!"
??????
// print a blank line
??????
############################################################################
Print the factors of a number and how many factors (Read from the keyboard,
print, math operations % ==, for loops, if else)
############################################################################
Program #14 - Write a program that prompts the user to enter a number.
Print out all of the factors of the number and how many factors.
You can use the integer type for your variables.
You will need a count variable starting at 0.
You will need a for loop to loop through all the possible
divisors (1 - number): for d in 1...number
Sample Output:
The Factors of a Number
Enter a number: (user enters maybe 8)
The factors of 8 are: 1 2 4 8
There are 4 factors.
// print out the title
// "Factors of a Number"
// and two blank lines
?????
?????
?????
// Create a variable called count
// and set it to 0.
// This will keep track of how many factors we
// have found. Every time we find a factor we
// will add 1 to this variable.
??? ????? = ?
// Prompt the user to enter a number.
?????(?????????, terminator:"")
// Create a variable called num. Use let.
// Convert the result to an Int
??? ??? = ???(readLine(strippingNewline:true)!)!
// Print a blank line.
?????
// We will now loop through all the possible
// numbers that might be factors. 1...num
// Use a for loop and use d for your loop variable
for ? in ?...?
{
// Check and see if num can be divided by
// d evenly. Use the % operator.
if ??? % ? == ?
{
// Print out the value of d and a space,
// but leave the cursor on the same line.
print(?,terminator:" ")
// Increase the value of count by 1
// (add 1 to the count)
count = ????? + ?
}
}
// Print a blank line.
??????
// Print out the number of factors that you found.
// "We found xxx factors."
// where the xxx is the count
print("We found xxx factors.")
// Print a blank line.
???????
############################################################################
Print the GCF of two numbers (Read from the keyboard,
print, math operations % ==, for loops, if else, &&)
############################################################################
Program #15 - Write a program that prompts the user to enter two numbers.
Print out the GCF of the two numbers.
You will need to loop through all of your possible divisors.
for d in 1...num1
and then see if num1 % d == 0 && num2 % d == 0
and then save in a variable such as gcf
You can use the integer type for your variables.
Stay in a loop until the user enters 0
Sample Output:
The GCF of Two Numbers
Enter the first number: 12
Enter the second number: 18
The GCF of 12 and 18 is 6
Enter the first number: 16
Enter the second number: 20
The GCF of 16 and 20 is 4
Enter the first number: 0
Goodbye!
Outline
import Foundation
// print out the title The GCF of Two Numbers
???????
while true
{
// print two blank lines
??????
??????
// Prompt the user to Enter the first number:
???????(?????????, terminator:"")
// Declare a variable called num1 (use let).
// Read in the number and convert it
// into an Int
??? ???? = ???(readLine(strippingNewline: true)!)!
// Check and see if num1 is equal to 0
if ???? == ?
{
// break out of the loop
?????
}
// print a blank line
?????
// Prompt the user to Enter the second number:
?????(??????, terminator:"")
// Declare a variable called num2 (use let).
// Read in the number and convert it
// into an Int
??? ???? = ???(readLine(strippingNewline: true)!)!
// print a blank line
?????
// print The GCF of ??? and ??? is
// where the first ??? is the value of the first number
// and the second ??? is the value of the second number
print("The GCF of \(????) and \(????) is ", terminator:"")
// define a variable called gcf and assign a
// value of 1 (use var)
??? ??? = ?
// Now we will loop through all of the possible
// divisors.
// Write a for loop which runs from 1...num1
// Use d for your loop variable
for ? in 1...????
{
// check and see if num1 is divisible by d
// AND num2 is divisible by d
if num1 % ? == ? && num2 % ? == ?
{
// assign the value of d to gcf
// (put the value of d into the gcf box)
// because it is the next largest possible value
gcf = ?;
} // end of if both are divisible by d
} // end of for d loop
// print the value of gcf
print(???)
} // end of while loop
// print a blank line
?????
// print Goodbye!
?????
// print a blank line
print()
############################################################################
Print the GCF of two numbers (Read from the keyboard,
print, math operations % ==, for loops, if else, &&, and functions)
############################################################################
Program #16 - Write a program that prompts the user to enter two numbers.
Print out the GCF of the two numbers.
Write a function called gcf. Call the function to get your result.
Stay in a loop until the user enters 0 0
Sample Output
The GCF of Two Numbers
Enter the first number: 12
Enter the second number: 18
The GCF of 12 and 18 is 6
Enter the first number: 16
Enter the second number: 28
The GCF of 16 and 28 is 4
Enter the first number: 0
Goodbye!
Outline
import Foundation
// Write a function to find the GCF of two numbers
func getGCF(_ num1:Int, _ num2:Int) -> Int
{
// define a variable called gcf and assign a
// value of 1 (use var)
??? ??? = ?
// Now we will loop through all of the possible
// divisors.
// Write a for loop which runs from 1...num1
// Use d for your loop variable
for ? in 1...????
{
// check and see if num1 is divisible by d
// AND num2 is divisible by d
if num1 % ? == ? && num2 % ? == ?
{
// assign the value of d to gcf
// (put the value of d into the gcf box)
// because it is the next largest possible value
gcf = ?
} // end of if both are divisible by d
} // end of for d loop
// return the value of the gcf
return ???
} // end of func
// print out the title The GCF of Two Numbers
?????(?????????????????)
while true
{
// print two blank lines
??????
??????
// Prompt the user to Enter the first number:
??????(??????, terminator:"")
// Declare a variable called num1 (use let).
// Read in the number and convert it
// into an Int
??? ???? = ???(readLine(strippingNewline: true)!)!
// Check and see if num1 is equal to 0
if ???? == ?
{
// break out of the loop
?????
}
// print a blank line
??????
// Prompt the user to Enter the second number:
print(???????, terminator:"")
// Declare a variable called num2 (use let).
// Read in the number and convert it
// into an Int
??? ???? = ???(readLine(strippingNewline: true)!)!
// print a blank line
??????
// find the GCF by calling the func getGCF
let gcf = ??????(num1, num2)
// print The GCF of ??? and ??? is ???
// where the first ??? is the value of the first number
// and the second ??? is the value of the second number
// and the third ??? is the value of the gcf
print("The GCF of \(????) and \(????) is \(???)")
} // end of while loop
// print a blank line
??????
print("Goodbye!")
// print a blank line
?????
############################################################################
Print the sum of the digits of a number (Read from the keyboard,
print, math operations, % ==, for loops, functions )
############################################################################
Program #17 - Write a program that prompts the user to enter a number.
Print out the sum of the digits for the number.
Write a function to find the sum.
Stay in a loop until the user enters 0
Sample Output:
The Sum of the Digits for a Number
Enter a number: (user enters maybe 123)
The sum of the digits of 123 is 6.
Enter a number: (user enters maybe 325)
The sum of the digits of 325 is 10.
Enter a number: (user enters maybe 0)
Goodbye!
// Sum of the Digits
func sum(_ num:Int) -> Int
{
var n = num
// create a variable called sum and
// set it to 0
??????
while n > 0
{
// divide n by 10 using %
// and store the answer in digit
var digit = ??????
// add the digit to sum
sum = ??????
// divide n by 10 using /
// and store the answer in n
n = ??????
}
// return the sum
?????? ???
}
// print the heading and
// two blank lines
??????????????????
??????
??????
while true
{
// prompt the user to enter
// the number
??????(??????, terminator:"")
// create a variable num
// use let
// Convert the input to an Int.
??? ??? = ???(readLine(strippingNewline:true)!)!
// check and see if num is equal to zero
// and if so, break the loop
if ??? ?? ?
{
??????
}
// print a blank line
??????
// print the answer
print("The sum of the digits is \(sum(num)).")
// print a blank line
??????
}
// print a blank line
??????
// print GoodBye!
??????
############################################################################
Print the vowels of a String (Read from the keyboard,
print, slicing, for loops, if else, &&)
############################################################################
Program #18 - Write a program that prompts the user to enter a String.
Print out each vowel in the String (a, e, i, o, u).
You can use the String type for your variable.
Stay in a loop until the user enters the empty String.
Hint:
for ch in myString:
if ch == "a" || ch == "e": # finish this
print (ch, terminator:"")
Sample Output:
The Vowels in a String
Enter a String: (user enters maybe catalog)
The vowels of catalog are: aao
Enter a String: (user enters maybe computer)
The vowels of computer are: oue
Enter a String: (user enters maybe nothing)
Goodbye!
// print out the title
// "The Vowels in a String"
// and two blank lines
??????????????????????
??????
??????
// create a while loop
????? true
{
// Prompt the user to Enter a String.
?????(???????, terminator:"")
// Create a variable called sentence. Use let.
??? ?????? = readLine(strippingNewline:true)!
// see if sentence is equal to ""
// and if so, break the loop
if ??????? == ??
{
?????
}
// Print a blank line.
?????
// print out The vowels of xxxxxx are:
// where xxxxxx is replaced by the value of the variable sentence
// Use interpolation
?????(?????, terminator:" ")
// We will now loop through all characters
// in the String sentence.
// Use a for loop and use ch for your variable
??? ?? in sentence
{
// Check and see if
// ch is a vowel.
if ch == "a" || ch == "e" || and so forth
{
// print out the ch and a space but
// stay on the same line
print(??,terminator:" ")
}
} // end of for loop
// print a blank line
?????
// print a blank line
?????
} // end of while true loop
// Print a blank line.
?????
// Print Goodbye!
?????
// Print a blank line.
?????
############################################################################
Print the capital letters of a String (Read from the keyboard,
print, slicing, for loops, if else, &&)
############################################################################
Program #19 - Write a program that prompts the user to enter a String.
Print out each capital letter in the String.
Stay in a loop until the user enters the empty String.
Hint: if ch >= "A" && ch <= "Z"
Sample Output:
The Capital Letters in a String
Enter a String: (user enters maybe CatALog)
The capital letters of CatALog are: CAL
Enter a String: (user enters maybe ComPuTer)
The capital letters of ComPuTer are: CPT
Enter a String: (user enters maybe nothing)
Goodbye!
// print out the title
// "Capital Letters of a String"
// and two blank lines
?????
?????
?????
// use a while true loop
????? ????
{
// Prompt the user to enter a sentence.
?????(?????, terminator:"")
// Create a variable called sentence. Use let.
??? ????? = readLine(strippingNewline:true)!
// see if sentence is equal to ""
// and if so, break the loop
if ????? ?? ""
{
?????
}
// Print a blank line.
?????
// print out The capital letters are:
?????(???????, terminator:"")
// We will now loop through all characters
// in the String sentence.
// Use a for loop and use ch for your variable
for ?? ?? sentence
{
// Check and see if
// ch is a capital letter.
// if ch >= "A" && ch <= "?" // replace the question mark
if ch >= "A" && ch <= "?"
{
// print out the ch but
// stay on the same line
?????(??,terminator:" ")
}
} // end of for loop
// print a blank line
?????
// print a blank line
?????
} // end of while true loop
// Print a blank line.
print()
// Print Goodbye!
?????
// Print a blank line.
?????
############################################################################
Prime Numbers
############################################################################
Program #20 - Write a program that prompts the user to enter a number.
Print out whether the number is prime or not.
Write a function to find the result (boolean).
Hint: A prime number has exactly 2 factors.
Count the factors as you find them.
Check the count after your loop has finished,
and see if you have exactly 2, and return True
Otherwise return False.
Stay in a loop until the user enters 0
Sample Output:
Prime Numbers
Enter a number: (user enters maybe 8)
8 is NOT prime.
Enter a number: (user enters maybe 17)
17 is prime.
Enter a number: (user enters maybe 0)
Goodbye!
OUTLINE
// Write a func called isPrime.
// It should return true if the
// num is prime else false
func isPrime(_ num:Int) -> Bool
{
// count all of the factors of
// num
// now see if count is equal to 2
// and if so, return true
// else return false
return false
}
// print out the title
// "Prime Numbers"
// and two blank lines
?????
?????
?????
// use a while true loop
????? true
{
// Prompt the user to enter a number.
??????(?????????, terminator:"")
// Create a variable called num. Use let.
// Then convert it to an Int
??? ??? = ???(readLine(strippingNewline:true)!)!
// check and see if num is zero, and
// if so, break the loop
if ??? ?? ?
{
?????
}
// Print a blank line.
?????
// print out
// The number is prime.
// or
// The number is NOT prime.
// Use an if else statement
// that calls the function
// isPrime.
if ?????(num)
{
}
else
{
}
// Print a blank line.
print()
}
// Print "Goodbye!".
?????
// Print a blank line.
?????
############################################################################
Perfect Numbers
############################################################################
Program #21 - Write a program that prompts the user to enter a number.
Print out whether the number is perfect or not.
A perfect number has divisors that add up to the number.
For example, 6 is perfect since factors 1, 2, 3 add to 6.
Write a function to find the result (boolean true or false).
Stay in a loop until the user enters 0
//
// main.swift
// Is Perfect
//
import Foundation
func isPerfect(_ num:Int) -> Bool
{
// Create a variable called sum (use var)
// and assign it a value of 0
// This variable will hold the sum of the factors
??? ??? = ?
// Write a for loop to loop through the numbers
// 1...num/2
// Call your variable d
for ? in 1...???/2
{
// Check and see if num is divisible by d (use %).
// Remember the remainder will be 0.
if ??? % ? == ?
{
// add sum and d together
sum = ??? + ?
} // end of if statement
} // end of for loop
// check and see if sum is equal to num
if ??? == ???
{
// return the value true
????? ?????
}
else
{
// return the value false
????? ?????
}
} // end of func isPerfect()
// Here is the main program
// print out the title Perfect Numbers
?????????
while true
{
// print two blank lines
?????
?????
// Prompt the user to enter a number.
???????
// Declare a variable called num (use let).
// Read in the number and convert it
// into an Int
??? ??? = ???(readLine(strippingNewline: true)!)!
// Check and see if num is equal to 0
if ??? == ?
{
// break out of the loop
??????
}
// print out a blank line
????????
// pass (send) the value of num to the
// isPerfect() function
if isPerfect(???)
{
// print out ??? is a perfect number.
// where ??? is the value of the number
???????
}
else
{
// print out ??? is NOT a perfect number.
// where ??? is the value of the number
???????????
}
} // end of while true
// print a blank line
?????
// print out Goodbye!
??????
/*
Sample Output
Perfect Numbers
Enter a number: 6
6 is a perfect number.
Enter a number: 27
27 is NOT a perfect number.
Enter a number: 28
28 is a perfect number.
Enter a number: 0
Goodbye!
*/
let b2 = String(12, radix: 2) // converts 12 into 1100 base 2
let b8 = String(12, radix: 8) // converts 12 to "14" base 8
let b16 = String(12, radix: 16) // converts 12 to "c" base 16
############################################################################
Base Two Numbers
############################################################################
Program #22 - Write a program that prompts the user to enter a number.
Print out the number in base 2.
You can use the integer type for your variable.
let b2 = String(number, radix: 2) // converts number to a base 2 (String)
Stay in a loop until the user enters 0
Base 2 numbers have only two digits, 0 and 1
Base 10 numbers have 10 digits, 0...9
Example 1:
0 1 0 1 1 0 <- binary digits
32 16 8 4 2 1 <- place value
The binary number in base 10 is ??????????????
Example 2:
1 1 0 1 1 1 <- binary digits
32 16 8 4 2 1 <- place value
The binary number in base 10 is ??????????????
Example 3:
0 0 1 1 1 1 <- binary digits
32 16 8 4 2 1 <- place value
The binary number in base 10 is ??????????????
Sample Output:
Binary Numbers
Enter a number to convert into binary: 20
The number 20 in binary form is 0b10100
Enter a number to convert into binary: 16
The number 16 in binary form is 0b10000
Enter a number to convert into binary: 18
The number 18 in binary form is 0b10010
Enter a number to convert into binary:
Outline to follow:
//
// main.swift
// Base 2 Numbers
//
import Foundation
// print out the title Binary Numbers
????????
// print two blank lines
?????
?????
// Prompt the user to enter a number.
???????
// Declare a variable called num (use let).
// Read in the number and convert it
// into an Int
??? ??? = ???(readLine(strippingNewline: true)!)!
// print a blank line
?????
// Declare a variable called b2 (use let)
// and then convert the num into
// base 2.
// The radix is the base.
// b2 will be the number in binary form.
??? ?? = String(???, radix: ?)
// Print out the result.
print("The number \(???) in binary form is \(??) ")
// print a blank line
??????
############################################################################
Base Eight Numbers
############################################################################
Program #23 - Write a program that prompts the user to enter a number.
Print out the number in base 8.
You can use the integer type for your variable.
let b8 = String(number, radix: 8) // converts number into base 8
Stay in a loop until the user enters 0
Base 8 numbers have 8 digits, 0...7
Base 10 numbers have 10 digits, 0...9
Example 1:
0 3 5 <- octal digits
64 8 1 <- place value
The octal number in base 10 is ??????????????
Example 2:
0 2 0 <- octal digits
64 8 1 <- place value
The octal number in base 10 is ??????????????
Example 3:
0 2 7 <- octal digits
64 8 1 <- place value
The octal number in base 10 is ??????????????
Sample Output:
Base Eight Numbers
Enter a number: (user enters maybe 17)
17 in base 8 is 21.
Enter a number: (user enters maybe 15)
15 in base 8 is 17.
Enter a number: (user enters maybe 0)
Goodbye!
Here is an outline:
import Foundation
// print out the title Base 8 Numbers
?????????????
// print two blank lines
???????
???????
// Prompt the user to enter a number.
?????????
// Declare a variable called num (use let).
// Read in the number and convert it
// into an Int
??? ??? = ???(????????(strippingNewline: true)!)!
// print a blank line
??????
// Declare a variable called b8 (use let)
// and then convert the num into
// base 8.
// The radix is the base.
// b8 will be the number in base 8 form (Octal).
??? ?? = String(???, radix: ?)
// Print out the result.
print("The number \(???) in base 8 form is \(??) ")
// print a blank line
print()
############################################################################
Base Sixteen (Hex) Numbers
############################################################################
Program #24 - Write a program that prompts the user to enter a number.
Print out the number in base 16.
You can use the integer type for your variable.
let b16 = String(number, radix: 16) // converts number into base 16
Stay in a loop until the user enters 0
Base 16 numbers have 16 digits, 0...9, A, B, C, D, E, F
Base 10 numbers have 10 digits, 0...9
Example 1:
0 2 5 <- hex digits
256 16 1 <- place value
The hex number in base 10 is ??????????????
Example 2:
0 1 C <- hex digits
256 16 1 <- place value
The hex number in base 10 is ??????????????
Example 3:
0 2 A <- hex digits
256 16 1 <- place value
The hex number in base 10 is ??????????????
Sample Output:
Base Sixteen (Hex) Numbers
Enter a number: (user enters maybe 17)
17 in base 16 is 10.
Enter a number: (user enters maybe 45)
45 in base 16 is 2d.
Enter a number: (user enters maybe 0)
Goodbye!
############################################################################
Simple Encryption
############################################################################
Program #25 - Write a program that prompts the user to enter a String (a message).
Print out the encrypted string based on the following algorithm.
Write a function to find the result (String).
Stay in a loop until the user enters 0
Sample Output:
Encryption
Enter the message to encrypt: Hello
Hello encrypted is Llpss
Enter the message to encrypt: Hi
Hi encrypted is Lp
Enter the message to encrypt:
Goodbye!
OUTLINE
=======
func encrypt(_ s:String) -> String
{
// this string will hold the encrypted form
var encryptedString = ""
// create a variable called i (use var)
??? ? = 0 // position in the string
for ch in s.unicodeScalars
{
// convert the character into numeric format
var x = ch.value // ASCII value
// change the value of x by adding four or adding seven
// based upon it's position within the String
// if the i is an even number, add 4 to x
// else add 7 to x
// see if i is an even number
if i % 2 == 0
{
// add 4 to x
x = ?????
}
else
{
// add 7 to x
x = ?????
}
// convert x back into it's character format
let result = Character(UnicodeScalar(x)!)
// add the result to the end of encryptedString
encryptedString = encryptedString + String(result)
// add 1 to i
i = ?????
}
// return your encryptedString
return encryptedString
}
// Main program
// print the title Encryption
// and two blank lines
?????
?????
?????
// create a while loop that loops forever
????? ????
{
// print 2 blank lines
?????
?????
// prompt the user to enter the message
// for us to encrypt
print(?????, terminator:"")
// read in the message to be encrypted
// declare a variable called message (use let)
??? ????? = readLine(strippingNewline:true)!
// see if the message is equal to ""
if ?????
{
// break out of the loop
?????
}
// print a blank line
?????
let encryptedString = encrypt(message)
// print "\(xxxxx) encrypted is \(yyyyy)"
// where xxxxx is the message to be encrypted
// and yyyyy is the encrypted message
print("\(xxxxx) encrypted is \(yyyyy)")
}
// print a blank line
?????
// print Goodbye!
?????
// print a blank line
?????
############################################################################
Simple Decrypt
############################################################################
Program #26 - Write a program that prompts the user to enter a String (a message)
in encrypted form using the algorithm above.
Print out the decrypted string based on reversing the algorithm above.
Write a function to find the result (String).
Stay in a loop until the user enters 0
Sample Output:
Decryption
Enter the message to decrypt: Llpss
Llpss decrypted is Hello
Enter the message to decrypt: Lp
Lp decrypted is Hi
Enter the message to decrypt:
Goodbye!
OUTLINE
=======
func decrypt(_ s:String) -> String
{
// this string will hold the decrypted form
var decryptedString = ""
// create a variable called i (use var)
// and set it equal to 0
?????
for ch in s.unicodeScalars
{
// convert the character into numeric format
// create a variable called x (use var)
??? ? = ch.value // ASCII value
// change the value of x by adding four or adding seven
// based upon it's position within the String
// if the i is an even number, add 4 to x
// else add 7 to x
// see if i is an even number
// Use %
if ?????
{
// subtract 4 from x
x = ?????
}
else
{
// subtract 7 from x
x = ?????
}
// convert x back into it's character format
// create a variable called result (use let)
??? ????? = Character(UnicodeScalar(x)!)
// add the result to the end of encryptedString
decryptedString = decryptedString + String(?????)
// add 1 to i
i = ?????
}
// return your decryptedString
return ?????
}
// Main program
// print the title Decryption
// and two blank lines
?????
?????
?????
// create a while loop that loops forever
????? ????
{
// print 2 blank lines
?????
?????
// prompt the user to enter the message
// for us to encrypt
print(?????, terminator:"")
// read in the message to be decrypted
// declare a variable called message (use let)
??? ????? = readLine(strippingNewline:true)!
// see if the message is equal to ""
if ??????
{
// break out of the loop
?????
}
// print a blank line
?????
let decryptedString = decrypt(message)
// print "\(xxxxx) decrypted is \(yyyyy)"
// where xxxxx is the message to be decrypted
// and yyyyy is the decrypted message
// (so replace both xxxxx and yyyyy)
print(?????)
}
// print a blank line
?????
// print Goodbye!
?????
// print a blank line
?????
############################################################################
Simple Lists (Arrays)
############################################################################
Program #27 - Write a program that finds the largest number in a list (Array).
Write a function to do this. Use a loop.
OUTLINE:
import Foundation
// define a function called findLargest
// It will receive an array or list of integer numbers
func findLargest(_ array:[Int]) ?? Int
{
// declare a variable called largest (use var)
var largest = array[0] // so far
// now loop through each number in the list
// This is a for each loop, so number will be the
// value of each element, NOT an index
// So, if your list is 8 5 9 4
// number will be 8 the 1st time through the loop
// number will be 5 the 2nd time through the loop
// number will be 9 the 3rd time through the loop
// number will be 4 the 4th time through the loop
for ?????? in array
{
// see if number ? largest, and if so,
// largest = number
if ????? ?? ?????
{
?????? = ??????
}
}
// return the value of largest
???????
} // end of func findLargest
func convertStringToNumericList(_ myStringList:String) ?? [Int]
{
// USE THIS FOR replit
let arrayString = myStringList.components(separatedBy: " ")
// USE THIS FOR onlinegdb
let arrayString = myStringList.split(separator:" ")
// Create a variable called array (use var)
??? ????? = [Int]() // this creates an Int array
// loop from 0..?arrayString.count
for i ?? ??????
{
// declare a variable called s (Use var)
// s will receive the number in the i position
// (but it will be stored in a String variable)
??? ? = arrayString[i]
// check to see if s is equal to ""
if ? ?? ??
{
continue
}
// call the append func to append s as a Int
array.??????(Int(s)!)
}
// return the array
????? ?????
} // end of func convertStringToNumericList
// print the title "Largest Number" and two
// blank lines.
???????
???????
???????
// prompt the user to "Enter the list of numbers: "
?????(??????, terminator:"")
// create a variable called stringList (use var)
??? ??????? = readLine(strippingNewline:true)!
// declare a variable called list (use let)
// We will convert the stringList to a numerical list
??? ???? = convertStringToNumericList(stringList)
// find the largest number
// declare a variable called largest (use let)
// call the func findLargest
??? ????? = ??????(list)
// print "The largest number is xxx" where xxx
// is replaced by the value of largest
?????
// print a blank lines
?????
// print a blank line
?????
// print "Have a great day!"
?????
// print a blank line
?????
############################################################################
Simple Lists (Arrays)
############################################################################
Program #28 - Write a program that finds the number of even numbers in the array.
Write a function to do this.
OUTLINE
import Foundation
func countEvens(_ array:[Int]) ?? Int
{
var count = 0
// loop through all of the numbers in array
// now loop through all the numbers in the list
// This is a for each loop, so number will be the
// value of each element, NOT an index
for number in array
{
// each time check and see if number is even, and if so,
// add 1 to your count variable (use number % 2 == 0)
}
// return the count
}
func convertStringToNumericList(_ myStringList:String) ?? [Int]
{
// USE THIS FOR replit
let arrayString = myStringList.components(separatedBy: " ")
// USE THIS FOR onlinegdb
let arrayString = myStringList.split(separator:" ")
// Create a variable called array (use var)
??? ????? = [Int]() // this creates an Int array
// loop from 0..?arrayString.count
for i ?? ??????
{
// declare a variable called s (Use var)
// s will receive the number in the i position
// (but it will be stored in a String variable)
??? ? = arrayString[i]
// check to see if s is equal to ""
if ? ?? ??
{
continue
}
// call the append func to append s as a Int
array.??????(Int(s)!)
}
// return the array
????? ?????
} // end of func convertStringToNumericList
// in your main program
print("Enter a list of numbers separated by spaces ", terminator:"")
let myStringList = readLine(strippingNewline:true)!
// array will be an array of Int values
let array = convertStringToNumericList(myStringList)
var numberOfEvens = countEvens(array)
// now print it!
The number of even numbers in array one is 4
############################################################################
Simple Lists (Arrays)
############################################################################
Program #29 - Write a program that finds the average of the numbers in the array.
Write a function to do this.
func findAverage(_ array:[Int]) ?? Double
{
var count = 0
// use this variable to find the sum of the numbers in the list
var sum = 0
// loop through all of the numbers in array
// This is a for each loop, so number will be the
// value of each element, NOT an index
for number in array
{
// each time add number to your sum to get a new value for sum
// sum = ???? + ??????
// add 1 to your count variable
}
// type cast your sum and count variables to be Double
// return the average
}
func convertStringToNumericList(_ myStringList:String) ?? [Int]
{
// USE THIS FOR replit
let arrayString = myStringList.components(separatedBy: " ")
// USE THIS FOR onlinegdb
let arrayString = myStringList.split(separator:" ")
// Create a variable called array (use var)
??? ????? = [Int]() // this creates an Int array
// loop from 0..?arrayString.count
for i ?? ??????
{
// declare a variable called s (Use var)
// s will receive the number in the i position
// (but it will be stored in a String variable)
??? ? = arrayString[i]
// check to see if s is equal to ""
if ? ?? ??
{
continue
}
// call the append func to append s as a Int
array.??????(Int(s)!)
}
// return the array
????? ?????
} // end of func convertStringToNumericList
// in your main program
print("Enter a list of numbers separated by spaces ", terminator:"")
let myStringList = readLine(strippingNewline:true)!
// array will be an array of Int values
let array = convertStringToNumericList(myStringList)
var average = findAverage(array)
// now print it!
The average of the numbers in list one is ???.?
// print a blank line
############################################################################
Simple Arrays
############################################################################
Program #30 - Write a program that finds and prints the first
n fibonacci numbers. You will not need to convert
to an int array. findFibonacciNumbers will return
an Int array for us.
Write a function to do this.
OUTLINE
func findFibonacciNumbers(_ howMany:Int) ?? [Int]
{
var list = [1, 1] // start with the first two numbers and append more
for i in 2...howMany
{
// find the next fibonacci number
// var nextNumber = list[i-1] + ????
// list.append (?????)
}
// return your list
???????
}
func getFiboList(_ list:[Int]) ?? String
{
// add code to print all the numbers in your list
// on the same line. Separate your numbers with a space
var output = ""
for number in list
{
output = output + String(num) + " "
}
// now we just return the output
return output
}
// in your main program
// print a title
// print 2 blank lines
// if you are doing an iphone app, you don't want a loop
// Do this in your button event with no loop
while true
{
// Ask the user for how many fibonacci numbers that they want to see
// print(?????)
// read it in (readLine) or if you are doing a iPhone app
// just get it from your input field and convert it to an Int
let num = ?????
// if they enter 0, break out of the loop
?????
// below we call our function to create the list of fibonacci numbers
let fiboList = findFibonacciNumbers(num)
// we now print the fibonacci numbers all on the same line
// by calling a function to do this
let fiboListAsAString = FiboList(fiboList)
// now print it
// print a blank line
}
print()
print("Goodbye")
############################################################################
Simple Arrays
############################################################################
Program #31 - Write a program that finds if an array is strictly increasing.
Write a method to do this. Strictly increasing means that
the numbers continue to increase.
Sample Output:
==============
Strictly Increasing
Enter a list of numbers separated by spaces 4 6 9 5 8
The list is NOT strictly increasing.
Enter a list of numbers separated by spaces 4 6 5 8 9
The list is NOT strictly increasing.
Enter a list of numbers separated by spaces
Goodbye!
OUTLINE:
========
import Foundation
func isStrictlyIncreasing(_ array:[Int]) ?? Bool
{
// return true if it is strictly increasing
// else return false
// you will need a for indexed based loop to
// access each ith number and see if it is
// greater than or equal to
// the i+1 element, and if so return false
// after the loop is over, return true
for i in 0..?array.count-1
{
// compare array[i] and array[i+1]
// if array[i] is greater than or equal to array[i+1]
// then return false
if array[i] ?? array[i+1]
{
// return the value false
????? ?????
}
}
// return the value true
????? ????
}
func convertStringToNumericList(_ myStringList:String) ?? [Int]
{
let arrayString = myStringList.components(separatedBy: " ")
// create a variable called array (use var)
??? ????? = [Int]()
for i in 0..?arrayString.count
{
let s = arrayString[i]
// call the append method to add the Int to the
// end of the list
array.?????(Int(s)!)
}
// return the array
????? ?????
} // end of func
// Main program
// print the title Strictly Increasing
?????
// create a while loop that loops forever
????? ????
{
// print 2 blank lines
?????
?????
print("Enter a list of numbers separated by spaces ", terminator:"")
let myStringList = readLine(strippingNewline:true)!
// see if myStringList is equal to ""
if ????????? ?? ??
{
// break out of the loop
?????
}
// print a blank line
?????
// array will be an array of Int values
// create a variable called array (use let)
??? ????? = convertStringToNumericList(myStringList)
if isStrictlyIncreasing(array)
{
// print that the list is strictly increasing
?????
}
else
{
// print that the list is NOT strictly increasing
?????
}
}
// print a blank line
?????
// print Goodbye!
?????
// print a blank line
?????
############################################################################
Simple Arrays
############################################################################
Program #32 - Write a program that trims the noise from a music file.
Sample Output
=============
Music
Enter a list of numbers separated by spaces 3 6 9 8
Enter the applitude: 7
3 6 9 8
3 6 7 7
Enter a list of numbers separated by spaces
Goodbye!
OUTLINE:
========
import Foundation
func trimNoise(_ samples:[Int], _ amplitude:Int) ?? [Int]
{
// this creates an empty array (list)
var array = [Int]()
// we should now loop through the samples array
for num in ??????
{
// see if num is greater than amplitude
if ??????
{
array.append(amplitude)
}
// see if num is less than -amplitude
else if ??????
{
array.append(-amplitude)
}
else
{
array.append(num)
}
}
// return the array
?????? ?????
} // end of func
func convertStringToNumericList(_ myStringList:String) ?? [Int]
{
let arrayString = myStringList.components(separatedBy: " ")
// this creates an array or list that can contain
// Int numbers
var array = [Int]()
// loop from 0 to less than arrayString.count
for i in 0..?arrayString.count
{
// create a variable called s (use let)
??? ? = arrayString[i]
// we convert the String s to an Int
// and then we append it to the end of
// array
array.???????(Int(s)!)
}
// return the array
????? ????
}
func printList(_ list:[Int])
{
// loop through each number in list
for number in ????
{
// print out the value of number
// using interpolation \(?????)
print("??????? ",terminator:"")
}
// print nothing
?????
}
// Main program
// print the title Strictly Increasing
print("Music")
// create a while loop that loops forever
????? ????
{
// print 2 blank lines
????
????
print("Enter a list of numbers separated by spaces ", terminator:"")
// We will now read in the list of numbers separated by a space
// create a variable called myStringList (use let)
??? ???? = readLine(strippingNewline:true)!
// see if myStringList is equal to ""
if ?????? == ??
{
// break out of the loop
????
}
// print a blank line
?????
print("Enter the applitude: ", terminator:"")
// create a variable called amplitude (use let)
??? ???? = Int(readLine(strippingNewline:true)!)!
// print a blank line
????
// array will be an array of Int values
let array = convertStringToNumericList(myStringList)
// call printList and pass it array
????(array)
// trim the noise (call trimNoise)
// and pass it array, amplitude
let array2 = ????(array, amplitude)
// call printList and pass it array2
????(array2)
}
// print a blank line
????
// print Goodbye!
????
// print a blank line
????
############################################################################
List
############################################################################
Program #33 - Names and ages (arrays or lists)
Sample Output:
==============
Names
Tom
Sue
Bill
Ages
16
15
12
Names and Ages
Name: Tom Age: 16
Name: Sue Age: 15
Name: Bill Age: 12
Sorting the names
Sorting the ages
Names and Ages with a function
Name: Bill Age: 12
Name: Sue Age: 15
Name: Tom Age: 16
OUTLINE:
========
// Swift Names and Ages
import Foundation
func printNamesAndAges(_ names:[String], _ ages:[Int])
{
for i in 0..?names.count
{
// print the name and age of the person
?????("Name: \(names[i]) Age: \(????[i])")
}
}
// declare a variable called names (use var)
??? ????? = ["Tom", "Sue", "Bill"]
// declare a variable called ages (use var)
??? ???? = [16, 15, 12]
print("Names")
for name in names
{
// print the name
?????(????)
}
// print a blank line
???????
print("Ages")
for age in ????
{
// print the age
print(age)
}
// print a blank line
?????
print("Names and Ages")
// print the names and ages with an indexed based loop
for i in ?..?names.?????
{
print("Name: \(?????[i]) Age: \(????[i])")
}
// print a blank line
??????
// sort the names
print("Sorting the names")
names.?????
// sort the ages
print("Sorting the ages")
ages.??????
// print a blank line
??????
// You should see a problem in your output
print("Names and Ages with a function")
// call printNamesAndAges and pass it names, ages
// you should notice a problem
?????????(?????, ????)
############################################################################
List
############################################################################
Program #34 - Write a program to print the products and price of eachproduct.
that reads in the names of items and the
Sample Output:
==============
Products and Prices
Product: Apple Price $: 0.75
Product: Bread Price $: 1.99
Product: Candy Bar Price $: 1.5
Total Cost: $4.24
Goodbye!
OUTLINE:
========
// Swift Products and Prices
import Foundation
func printProductsAndPrices(_ products:[String], _ prices:[Double])
{
// declare a variable called totalCost and
// set it to 0.0
??? ??????? = 0.0
for i in 0..?products.?????
{
// print the product and the price for
// the ith product
print("Product: \(????????[i]) Price $: \(?????[i])")
// update your totalCost by
// adding the price of this item
// to your totalCost
totalCost = ??????? + ??????[i]
}
// print a blank line
??????
// print the total cost with a message
// Total Cost: ???????
print("Total Cost: $\(????????)")
}
// Main Program
// print the title "Products and Prices"
???????
// print 2 blank lines
?????
?????
// declare a variable called products
// (use let)
??? ???????? = ["Apple", "Bread", "Candy Bar"]
// declare a variable called prices
// (use let)
??? ????? = [0.75, 1.99, 1.50]
// call a method to print the
// products and prices and
// pass it products and prices
????????????(??????, ??????)
// print a blank line
?????
// print the message Goodbye!
?????
// print a blank line
?????
CLASSES ARE NOW USED!!!!!!!!
############################################################################
List (Arrays of objects)
############################################################################
Program #35 - Write a class that stores information about a student (Student).
Store in the class the student name, quarter 1 grade,
quarter 2 grade, and the average.
/*
Sample run:
Enter the students's name: Tom
Enter q1 grade: 95
Enter q2 grade: 98
Enter the students's name: Sue
Enter q1 grade: 100
Enter q2 grade: 98
Enter the students's name:
Student Name: Tom
Grade Q1: 95
Grade Q2: 98
Average : 96.5
Student Name: Sue
Grade Q1: 100
Grade Q2: 98
Average : 99.0
Student with highest average is:
Sue
*/
class Student
{
// we put our instance variables here
// to hold our data for one student
var name = ""
var q1 = 0
var q2 = 0
var avg = 0.0
// We then generally define a constructor
// to initialize our instance variables (members)
// The parameters are temporary variables to receive the
// data for the instance variables above.
init(_ name:String,
_ q1 :Int,
_ q2 :Int)
{
// self.name refers to the instance variable name
self.name = name
// add more assignments here for
// self.q1 and self.q2
???????
???????
// calculate the average and store it in the
// self.avg = Double(?? + ??) / 2.0
self.avg = ?????
}
} // end of class Student
// NOTE: students refers to a list (array) of Student objects.
func printStudents(_ students:[Student])
{
// print out each student's name, q1, q2, and average
// use a for each loop
// for each student in the student's array
for student in ????????
{
// student is referring to one student in the list
// you can access info in this student's object by using:
// student.name,
// student.q1,
// student.q2
// student.avg
print("Student Name: \(student.name)")
?????
?????
?????
print()
} // end of for each student loop
} // end of func printStudents
func printStudentWithHighestAvg(_ students:[Student])
{
var studentName = "" // unknown
var highestAvg = 0.0;
// Now you need to loop
// through all the students
// and see if the student's average is
// higher than highestAvg, and if so
// store the new studentName
// and the new highestAvg
for student in ???????
{
if student.??? ? highestAvg
{
// highestAvg should now be this student's avg
highestAvg = student.???
// and now studentName should be this student's name
studentName = student.????
}
}
// Now print the student
// with the highestAvg
print()
print("Student with highest average is:")
print(??????????) // show the name of the student
print()
} // end of func
// this starts the main program
// We create an empty list (array) of
// Student objects
// create a variable called students that will
// refer to our list of Student objects (use var)
??? ????????? = [Student]()
// create a while loop that will loop forever
????? ????
{
// prompt the user to enter the name.
?????("?????????", terminator:"")
// read in the name use readLine(......)!
let name = ?????????
// See if the name is equal to ""
?? ???? == ??
{
print()
// break out of the loop
??????
}
// prompt the user to enter the quarter 1 grede.
print("????????", terminator:"")
// read in q1 grade Int use readLine(....)!
// Don't forget to convert it to an Int. use Int(......)!
let q1 = ?????????????
// prompt the user to enter the quarter 2 grade.
print(??????????, terminator:"")
// read in q2 grade Int (use readLine)
let q2 = ???????????
// We now create a Student object and pass to it the info
// to store inside (name, q1, and q2).
// Create a variable called student (use let).
??? ??????? = Student(????, ??, ??)
// add the Student object to our list
students.??????(student)
print()
}
// now print out the students
// send it the list of students
printStudents(??????????)
// now print out the student
// with the highest average
// send it the list of students
printStudentWithHighestAvg(????????)
############################################################################
List of Objects
############################################################################
Program #36 - Write a class that stores information about a product to buy.
Store in the class the barcode, item name, price,
inventory, and the amount of tax to charge.
/*
Sample Output:
Items We Sell
Item Name : Bread
Item Price : 3.99
Item Tax : 0.32917500000000005
barcode : 78645
Item Name : Campbell's Vegetable Soup 8 oz
Item Price : 2.49
Item Tax : 0.20542500000000002
barcode : 79644
Low Inventory
Item Name : Amy's Vegetable Soup 8 oz
Item Price : 2.37
Item Tax : 0.195525
barcode : 79645
Low Inventory
Item Name : Amy's Vegetable Soup 12 oz
Item Price : 3.49
Item Tax : 0.28792500000000004
barcode : 79688
Enter the barcode: 79645
Cost: 2.37 Tax: 0.195525
Total Cost: 2.37
Enter the barcode: 79688
Cost: 3.49 Tax: 0.28792500000000004
Total Cost: 5.86
Enter the barcode:
Total cost : 5.86
Total tax : 0.48345000000000005
Final Bill : 6.343450000000001
Thank you for shopping at The Best Store!
*/
class Item
{
// We define our instance variables
// that permanently stores the data
// for this item.
var barcode = ""
var itemName = ""
var price = 0.0
var inventory = 0
var taxRate = 0.0
// We then generally define a constructor or initializer
// to create and initialize our instance variables (members).
// When an Item is created (and we can create many of these)
// we send to this constructor or initializer the information
// which is then stored temporarily in the parameter variables.
// barcode, itemName, price, inventory, and taxRate are the names of
// the parameter variables that receive the incoming data.
// self.barcode, self.itemName, self.price, self.inventory,
// and self.taxRate are the instance variables which are permanent.
// The parameter variables are created, assigned the incoming values,
// but then are destroyed at the end of the function.
init(_ barcode:String, _ itemName:String, _ price:Double, _ inventory:Int, _ taxRate:Double)
{
self.barcode = barcode // creates instance variable self.barcode
self.itemName = itemName // creates instance variable self.itemName
// FINISH ME
// set your price, inventory, and taxRate
???????
???????
???????
}
func getTaxOnItem() ?? Double
{
// FINISH ME
// return the tax for this sale (taxRate times price)
return ????? * ????? // change this (do the math)
}
} // END OF class
// this is NOT inside the class Item
// NOTE: The parameter items is referring to an
// array of Item objects.
func printItems(_ items:[Item])
{
// print out each item's name, price, and tax to be paid
// use a for each loop
// FINISH ME
// for each item in the items list, you will print
// out the item's fields (variable values)
for item in ?????
{
// item is referring to one item in the list called items
// you can access info in the item's object by using:
// item.barcode, item.itemName,
// item.price, item.inventory, item.taxRate
// you can also call any functions inside the Item class
// For example: item.getTaxOnItem()
// but don't pass it any values. The
// data is already in the object.
// so print this item's name, price,
// tax to be paid, and barcode
print("Item Name : \(item.itemName)")
print("Item Price : \(item.price)")
// FINISH ME
???????
???????
// Also, if an item is low on inventory (less than 5)
// print out the message Low Inventory
// FINISH ME
if item.???????? ? 5
{
// FINISH ME
// print out Low Inventory
?????????
}
// FINISH ME
// print a blank line
???????
} // end of for each item loop
} // end of func
// Item? is the return type indicating that it
// will be of type Optional, since we may not
// find it, and thus we return nil.
func searchForItemByBarcode(_ items:[Item], _ barcode:String) ?? Item? // Keep Item?
{
// FINISH ME
// Loop through all the items
for item in ????
{
// we are looking for the barcode
if item.??????? == ???????
{
return item
}
}
return nil // we did not find the item with this barcode
}
// this starts the main program
// items will be a list that holds all of the items in our store.
var items = [Item]()
// We will now add Item objects to our list of items
var item = Item("78645", "Bread", 3.99, 55, 0.0825)
items.append(item)
item = Item("79644", "Campbell's Vegetable Soup 8 oz", 2.49, 3, 0.0825)
items.append(item)
item = Item("79645", "Amy's Vegetable Soup 8 oz", 2.37, 2, 0.0825)
items.append(item)
item = Item("79688", "Amy's Vegetable Soup 12 oz", 3.49, 12, 0.0825)
items.append(item)
print("Items We Sell")
print()
printItems(items)
print()
print()
// these would be scanned and we would get the barcode 1 by 1
// this program shows the basics of how this would work
// search for items and print out the name, cost, and tax for each
// item. Also add up the total cost, total tax paid, and the
// final bill to be paid.
var totalCost = 0.00
var totalTax = 0.00
// FINISH ME
// loop forever
????? ????
{
// 78645 79645
print()
// FINISH ME
// prompt the user to enter the barcode
print("??????: ", terminator:"")
// FINISH ME
// define a variable called barcode (use let)
// read in the value from the user
??? ????? = ???????(strippingNewline:true)!
// FINISH ME
// check and see if the barcode is equal to ""
// if so, break out of the loop
?? ????????
{
?????
}
// now we will search for the item that we want to find
// pass to the func items and barcode
let itemToFind = searchForItemByBarcode(?????, barcode)
// FINISH ME
// it might be an error so we will unwrap it!
// define a variable called item (use let)
??? ????? = itemToFind!
// use item.price to refer to the price of this item
// FINISH ME
// update your totalCost
// add the current totalCost plus the price of this item
totalCost = ??????? + item.???????
// update the totalTax that you have to pay
// You need to add your totalTax + the tax on this item
// to get your new value for totalTax
totalTax = ??????? + item.getTaxOnItem()
// FINISH ME
// print your cost of this item
// and print the amount of tax for this item
print("Cost: \(item.????) Tax: \(item.?????????)")
// FINISH ME (totalCost so far)
print("Total Cost: \(?????)")
} // END of while true
// now print out the total cost without tax, the amount of tax to pay,
// and the final bill
// FINISH ME
// Let's find the final bill
var finalBill = ??????? + ????? // do the math (totalCost plus totalTzx)
// FINISH ME
// print it here with one value per line
// For example: print("Total cost: \(totalCost")
// then you would print your total tax, and then your final bill.
print("Total cost : ????????")
print("Total tax : ????????")
print("Final Bill : ????????")
print()
print("Thank you for shopping at The Best Store!")
print()
############################################################################
List of Objects
############################################################################
Program #37 - Write a class that stores information about your driving record.
Store in the class the driver's license, name, and license plate.
/*
Sample output:
Enter the license: 88880
Driver Name: Mary Jones
Driver License: 88880
Driver License Plate: BC9999
Thank you for using this application to find your driver.
*/
class DriversRecord
{
// We define our instance variables
// (members, fields) of our object.
var name = ""
var license = ""
var licensePlate = ""
init(_ name:String, _ license:String, _ licensePlate:String)
{
// Assign the corresponding
// parameter values to the
// self variables (instance
// variables or members)
self.name = name
self.?????? = ???????
self.?????? = ???????
} // END OF init
} // END OF class
// this starts the main program
// drivers will be a list that holds all
// of the DriversRecord objects.
// The list will start out empty.
var drivers = [DriversRecord]()
// We will now add DriversRecord objects to our list of drivers
var driver = DriversRecord("Fred Baker", "67789", "BI1101")
drivers.append(driver)
// ADD THREE MORE PEOPLE
// THE LICENSE MUST BE UNIQUE
// The licensePlate must also be unique
// Do not use var driver
driver = DriversRecord(????, ????, ????)
drivers.???????(driver)
???????????
???????????
???????????
???????????
// Ask the user for the license number
// of whom you want to find.
?????("???????: ", terminator:"")
// The licenseToFind will be a String, so do not type cast it.
var licenseToFind = ????????? // use readLine(......)!
// Define a variable called theDriver (use var)
// Set it to refer to a Driver
// This will hold the reference to the Driver if we find it.
??? ???????? = DriversRecord("", "", "")
// Create a variable called found (var).
// Set the beginning value to false,
// since we have NOT found it yet.
??? ????? = false
// Now we will go looking for the license
// and thus get the driver's info
// We will look through all the drivers until
// we find it or the loop ends.
// for each driver in the list of drivers
// driver will refer to one driver each time
// through the loop.
for driver in ????????
{
// driver will refer to one DriversRecord
// See if licenseToFind is equal to this
// driver's license
?? ???????? ?? driver.??????
{
// This should hold the driver's info
// Set theDriver to refer to driver
theDriver = ?????
// Set the found variable to true,
// since we found the driver!
????? = ????
// break out of the loop
?????
} // end of if statement
} // end of loop
// check your found variable
// and see if it is equal to true
?? ????? ?? ????
{
// print out all the information
// about the driver.
print()
print("Driver Name: \(theDriver.????)")
?????????????
?????????????
}
else
{
// print out an appropriate message
// (License not found.)
print()
????????????????
}
print()
print("Thank you for using this application to find your driver.")
print()
############################################################################
List of Objects
############################################################################
Program #38 - You will be modifying program #37.
See code above and modify it.
Add an instance variable called points that holds an integer.
When you get a traffic ticket, depending on what you did wrong,
you get points added to your points (this is NOT a good thing
since the insurance companies can now charge you more money, and
if you get too many points, the DMV can take your license away).
You will need to modify your constructor (initializer). You will
also need to add more object's to your list to test the printing
of the points and a possible loss of your driver's license.
When you print the driver's information, add the points to your
output and a message.
Example: Points: 5
Also, check and see if you have more than 10 points, and if so print
out a message like:
Example: Your license has been suspended.
############################################################################
List of Objects
############################################################################
Program #39 - You will be creating GameScore objects to hold the
scores of several basketball games.
// 1 GameScore Object
//
// We can create the object using the command or instruction:
// var game = GameScore("Boston Celtics", 116, "LA Lakers", 112)
//
// If we have a variable called game that
// refers to this object in RAM memory, we
// can use commands or instructions like:
// game.team1
// game.points1
// game.team2
// game.points2
//
// This command or instruction would create room in RAM memory that
// could hold our information. It will run our init function after
// reserving room in the RAM that will put the info in the object
// for us.
//
// The variable named game would actually hold the memory address of where
// the object was created in RAM memory, and thus we say that it refers to
// (or points to) the object. RAM memory is byte addressable.
// We have byte 0, byte 1, byte 2, ... byte 78456, byte 78455, ...
// The OS determines where our object will be stored in RAM memory.
// The OS keeps a map of all used memory.
// So, maybe we would get a location starting at byte 78456,
// and thus game would hold that number for us.
// game
// ============
// | 78456 |
// ============
//
// game would refer to this object stored at
// memory location 78456
//
// Location 78456
// =====================================
// | team1 |
// | ============================= |
// | | "Boston Celtics | |
// | ============================= |
// | |
// | points1 |
// | ============================= |
// | | 116 | |
// | ============================= |
// | |
// | team2 |
// | ============================= |
// | | LA Lakers | |
// | ============================= |
// | |
// | points2 |
// | ============================= |
// | | 112 | |
// | ============================= |
// | |
// | init |
// | ============================= |
// | | code goes here | |
// | | code goes here | |
// | | code goes here | |
// | | code goes here | |
// | | code goes here | |
// | ============================= |
// | |
// =====================================
/*
Sample run:
Game Scores
Here are the scores printed from an array:
===============================================
Team: Boston Celtics
Score: 116
Team: LA Lakers
Score: 112
===============================================
Team: San Antonio Spurs
Score: 128
Team: Detroit Pistons
Score: 96
===============================================
Team: Houston Rockets
Score: 124
Team: Indiana Pacers
Score: 119
===============================================
Team: Dallas Mavericks
Score: 117
Team: New York Knicks
Score: 115
===============================================
*/
class GameScore
{
// declare your variables
// team1 (String)
// points1 (Int)
// team2 (String)
// points2 (Int)
???????
???????
???????
???????
init(_ team1:String, _ points1:Int, _ team2:String, _ points2:Int)
{
self.team1 = team1
self.????? ? ???????
self.????? ? ???????
self.????? ? ???????
} // end of init constructor (func)
} // END OF CLASS GameScore
// NOTE: games is plural because we are
// referring to possibly many
// GameScore objects
// HOW WOULD I CREATE an array
// or list that can hold
// GameScore objects????????????
var games = [????????????]??
// THIS WILL create a GameScore
// object and then add it
// (or append it) to our games
// list (array)
var game = GameScore("Boston Celtics", 116, "LA Lakers", 112)
games.append(game)
// THIS WILL create a GameScore
// object and then add it
// (or append it) to our games
// list (array)
game = GameScore("San Antonio Spurs", 128, "Detroit Pistons", 96)
games.??????(?????)
// and another game object
game = ??????????("Houston Rockets", 124, "Indiana Pacers", 119)
games.??????(?????)
// and another game object
game = ???????????("Dallas Mavericks", 117, "New York Knicks", 115)
games.????????(????)
// print the title "Game Scores"
// ??????
// PRINT A BLANK LINE
// ?????
// PRINT A BLANK LINE
print("Here are the scores printed from an array:")
print("===============================================")
// NOW LET'S LOOP THROUGH THE ARRAY
// one GameScore object at a time
for game in games
{
// HOW WOULD I ACCESS this game's
// team1 field (variable) ???????
// game.team1
print("Team: ", game.team1)
// HOW WOULD I ACCESS that game's points1 field?
// print("Score: ", ????????)
print()
// Print out team2's name
// HOW WOULD I ACCESS that game's
// team2 field
// ??????
// Print out team2's points?
// HOW WOULD I ACCESS that game's
// points2 field
// ??????
// HOW WOULD I PRINT A BLANK LINE
// TO SEPARATE THE OUTPUT
// OF THIS GameScore object FROM THE
// NEXT GameScore object???????
// ???????
print("===============================================")
} // end of for each GameScore object
############################################################################
Arrays 2D
############################################################################
Program #40 - Write a program that prints out a 2D array in matrix format and
row major order. Write a method to do the printing.
Use print("%3d" % (element))
def printMatrix(matrix):
for r in range(0, len(a)):
for c in range(0, len(a[r])):
print("%3d" % (a[r][c]), end=' ') # stay on row
print() # move to next row
# in your main program
one = [ [1, 3, 6, 8,14,16,18], [1, 2, 3, 4, 5, 6, 7], [1, 2, 8, 4, 9, 6, 6] ]
two = [ [2, 3, 6, 8,14,16,18], [3, 2, 3, 4, 5, 6, 7], [4, 2, 8, 4, 9, 6, 6] ]
# print matrix one
printMatrix(one)
# now do array two
############################################################################
Arrays 2D
############################################################################
Program #41 - Write a program that prints out 1 row of a 2D array.
Write a method to do the printing.
def printRow(array):
# Remember that array will be referring to just one row.
# So, just print out the one row with each number formatted
# to take up three print positions. You will need a loop.
# You can use an indexed based loop like
# for i in range(0, len(array)):
# num = array[i]
# and now print the number formatted
# OR a for each loop like
# for num in array:
# and now print the number formatted
# in your main method
# In the list below:
# one[0] is referring to [1, 3, 6, 8,14,16,18]
# one[1] is referring to [1, 2, 3, 4, 5, 6, 7]
# one[2] is referring to [1, 2, 8, 4, 9, 6, 6]
# in the list below, len(one) is 3 (since there are 3 lists or 3 rows)
# in the list below, len(one[0]) is 7 (since there are 7 elements in the 0 list)
one = [ [1, 3, 6, 8,14,16,18], [1, 2, 3, 4, 5, 6, 7], [1, 2, 8, 4, 9, 6, 6] ]
two = [ [2, 3, 6, 8,14,16,18], [3, 2, 3, 4, 5, 6, 7], [4, 2, 8, 4, 9, 6, 6] ]
# print the first element in one's first line
print(one[0][0])
# print the second element in one's first line
print(one[0][1])
# print the third element in one's first line
print(one[0][2])
# print row 0
printRow(one[0])
# now print row 1
# now print row 2
# use a loop to print all rows by calling printRow for each row
for r in range(len(one)):
############################################################################
Arrays 2D
############################################################################
Program #42 - Write a program that finds the sum of a row.
Print all elements of the row followed by the sum.
Make sure that your output is lined up properly.
Write a method to do the printing.
def findSum(array):
# array will be a list (1d array)
# find the sum and return it
# You will need a loop (either for indexed or for each loop)
def printRow(array):
# array will be a list (1d array)
def printSum(array):
# array will be a list (1d array)
# call the findSum function
# use 4 print positions (formatted)
# in your main program
one = [1, 3, 6, 8, 14, 16, 18]
two = [2, 3, 6, 8, 14, 16, 18]
# call printRow and then printSum for each 1d array
############################################################################
Arrays 2D
############################################################################
Program #43 - Write a program that finds the sum of each row.
Print all elements of the row followed by the sum.
Make sure that your output is lined up properly.
Write a method to do the printing.
After doing this, write a method to print out the
sum of each column.
def printRow(array):
define printRowSum(array):
def printAllRowsAndSum(array):
for r in range(0, len(array)):
printRow(array[r]); # prints out row r
printRowSum(array[r]); # prints the sum of row r
// call this method after printing out all rows and their sums
def printColumnSum(array, column):
def printSumOfAllColumns(array):
// in your main method
one = [ [1, 3, 6, 8, 14, 16, 18], [1, 2, 3, 4, 5, 6, 7], [1, 2, 8, 4, 9, 6, 6] ]
two = [ [2, 3, 6, 8,14,16,18], [3, 2, 3, 4, 5, 6, 7],[4, 2, 8, 4, 9, 6, 6]]
// Do not use any loops here
// Just make method calls
############################################################################
Arrays 2D
############################################################################
Program #44 - Write a program that finds if X or O is a winner.
Make sure that your output is lined up properly.
Write a method to print out the game board, and then print
out who won.
def printBoard(board):
# print out the board in matrix format
def isWinnerHorizontally(player, board):
# player should be either "X" or "O"
# board should be a 2D array
# return True if you find a winner
# else return False
# We will check row 0 first.
# There is an easier way with loops. Can you think of how
# See if player is equal to board[0][0] and
# player is equal to board[0][1] and
# player is equal to board[0][1] and
if player == board[0][0] and player == board[0][1] and player == board[0][2]:
return True
# Now check row 1
# Now check row 2
# if none of the above are True, simply return False
return False
def isWinnerVertically(player, board):
def isWinnerOnDiagonal1(player, board):
def isWinnerOnDiagonal2(player, board):
def isWinner(player, board):
# We will call each of the win methods above
# See if player is a winner horizontally
if isWinnerHorizontally(player, board):
return True
# See if player is a winner horizontally
if isWinnerVertically(player, board):
return True
# See if player is a winner on the first diagonal
# See if player is a winner on the second diagonal
# if it gets here, return False since player is NOT a winner
# in your main method
board1 = [ ['X', 'O', 'X'], ['X', 'X', 'O'], ['O', 'O', 'X'] ]
]
board2 = [ ['X', 'O', 'X'], ['X', 'X', 'O'], ['O', 'O', 'X'] ]
board3 = [ ['X', 'O', 'X'], ['X', 'X', 'O'], ['O', 'O', 'X'] ]
printBoard(board1)
print()
if isWinner("X", board1):
print("X is the winner on board1")
elif isWinner("O", board1):
print("O is the winner on board1")
else:
print("There is no winner on board1. Cat's game!!!")
# print 2 blank lines
# DO THIS FOR board2
# DO THIS FOR board3
############################################################################
Arrays 2D
############################################################################
Program #45 - Write a program that plays tic tac toe but lets the users
enter the positions of where they want to play.
You will need the functions that you wrote above.
Copy and paste them into this program.
Make sure that your output is lined up properly.
# MAIN PROGRAM
print("Tic-Tac-Toe")
print()
print()
while True: # outer loop of game to play another game
# we will create an empty board for this game
board = [ ['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-'] ]
# print the board
while True: # inner loop that plays 1 game
# player X will choose the row and column to play on.
print("Player X's turn")
row = int(input("Enter your row to play on (1,2,3): "))
col = int(input("Enter your col to play on (1,2,3): "))
row = row - 1
col = col - 1
board[row][col] = "X"
# print the board
# check and see if "X" is a winner
# if so print out that X is a winner and break the loop
print()
# player O will choose the row and column to play on.
print("Player O's turn")
row = int(input("Enter your row to play on (1,2,3): "))
col = int(input("Enter your col to play on (1,2,3): "))
row = row - 1
col = col - 1
board[row][col] = "O"
# print the board
# check and see if "O" is a winner
# if so print out that O is a winner and break the loop
print()
print()
print()
print()
playAgain = input("Would you like to play another game? (y or n)")
if playAgain == "n":
break # breaks out of outer loop
print()
print()
print("Thank you for playing Tic-Tac-Toe. I hope that you had fun!")
############################################################################
Arrays 2D
############################################################################
Program #46 - There are problems with the game above.
Fix the problems.
1) A player could play on another players move or his own.
Check the spot to see if it is available.
Wrap up the input process in a loop.
2) A player could enter a row or column that is out of range.
Check and see if they are within the range.
Wrap up the input process in a loop.
3) Add a function to see if the row and col are in range,
and the spot is an empty spot.
return True or False
4) Call the function above in your main program to make
it more readable.
############################################################################
Arrays 2D
############################################################################
Program #47 - You will be writing a program called Battle Ship.
You will move your ship through dangerous waters
and avoid hitting the destroyers.
# Battle Ship
# Put functions here
# ==================
def printBoard(board):
# code to print the board goes here
for row in range(0,len(board)):
for col in range(0, len(board[row])):
print(???????????, end='')
print()
return
def copyBoard(board):
newBoard = []
for row in range(0,len(board)):
newRow = []
for col in range(0, len(board[row])):
newRow.append(board[row][col])
newBoard.append(newRow)
return newBoard
def moveDestroyersDown(board):
# You will need to start at the last row and move all
# Distroyers off the board (set them to ' '). Then
# continue by moving all Destroyers down by one
# When you move a destroyer down, erase it from it's
# current position, and then assign it to the row
# below.
# this clears the bottom row as these destroyers
# leave the area, or you could wrap them around.
lastRow = len(board) - 1
for col in range(0,len(board[0])):
board[lastRow][col] = ' '
shipIsHit = False
# Now move all the destroyers down 1 row
# but first check to see if the ship is
# in that spot. If so, set shipIsHit to True.
# So, loop through all the rows for the outside loop
# Then loop through all the columns on the row (indexed loop)
# Inside the inner loop check to see if you have a destroyer,
# and if so see if it would hit your ship, and if so
# set shipIsHit to true. Then move the destroyer down.
# DO NOT CHANGE THE row variable, just use:
# board[row+1][col] = 'D'
?????????
?????????
?????????
?????????
return shipIsHit
# Main program goes here
# ==================
# here is the board
row0 = ['D', ' ', 'D', ' ', 'D' , 'D', 'D', ' ']
row1 = ['D', ' ', ' ', ' ', ' ' , 'D', ' ', ' ']
row2 = ['D', ' ', 'D', ' ', ' ' , 'D', ' ', ' ']
row3 = [' ', ' ', ' ', ' ', ' ' , 'D', ' ', 'D']
row4 = [' ', ' ', ' ', ' ', ' ' , ' ', ' ', ' ']
row5 = [' ', 'D', ' ', 'D', 'D' , ' ', ' ', ' ']
row6 = [' ', ' ', ' ', ' ', ' ' , ' ', ' ', ' ']
row7 = [' ', ' ', ' ', ' ', ' ' , ' ', ' ', ' ']
row8 = [' ', ' ', ' ', ' ', ' ' , ' ', ' ', ' ']
row9 = [' ', ' ', ' ', '*', ' ' , ' ', ' ', ' ']
board = []
board.append(row0)
board.append(row1)
board.append(row2)
board.append(row3)
board.append(row4)
board.append(row5)
board.append(row6)
board.append(row7)
board.append(row8)
board.append(row9)
originalBoard = copyBoard(board)
shipRow = 9
shipCol = 3
print("Battle Ship")
print()
print()
while True: # outer loop of game to play another game
# we will create a board for this game (optional)
# just reset it back to the beginning
# (call a function to do this)
board = copyBoard(originalBoard)
# reset the ship's coordinates shipRow and shipCol
shipRow = 9
shipCol = 3
# print the board
printBoard(board)
while True: # inner loop that plays 1 game
# Ask the user how to move (left, up, right, or none)
print("You can move left (l), up (u), right (r), none (n), or quit (q)")
move = input("Enter how to move (l, u, r, n, q): ")
# handle the move if possible
# if this move attempts to go out of bounds, ignore it and
# stay put.
if move == 'l':
board[shipRow][shipCol] = ' '
shipCol = shipCol - 1
if board[shipRow][shipCol] == 'D':
print("You lose!!!")
break
board[shipRow][shipCol] = '*'
elif move == 'u':
board[shipRow][shipCol] = ' '
shipRow = shipRow - 1
if board[shipRow][shipCol] == 'D':
print("You lose!!!")
break
board[shipRow][shipCol] = '*'
elif move == 'r':
board[shipRow][shipCol] = ' '
shipCol = shipCol + 1
if board[shipRow][shipCol] == 'D':
print("You lose!!!")
break
board[shipRow][shipCol] = '*'
elif move == 'q':
break
# Now move the destroyers down
# Call your method
shipIsHit = moveDestroyersDown(board)
# Now see if your ship got hit
if shipIsHit == True:
print("You lose!!!")
break
# print the new board
# call a function
printBoard(board)
# check for a win (reaching row 0) and
# if so, print out a win message and then break the loop
if shipRow == 0:
print("You win!!! Great job!!!")
break
print()
print()
print()
print()
playAgain = input("Would you like to play another game? (y or n)")
if playAgain == "n":
break # breaks out of outer loop
print()
print()
print("Thank you for playing Battle Ship. I hope that you had fun!")
############################################################################
Arrays 2D
############################################################################
Program #48 - You will be writing a program called Pascal's Triangle.
You will need to generate Pascal's Triangle and then
print it out. Store the numbers in a 2 dimensional array.
The first column is always a 1. You will need to generate
elements starting at row 1.
1 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0
1 2 1 0 0 0 0 0 0
1 3 3 1 0 0 0 0 0
1 4 6 4 1 0 0 0 0
1 5 10 10 5 1 0 0 0
etc.
def printMatrix(matrix):
# print the matrix in formatted form
print()
def fillMatrixWithAllZeroes(matrix):
# we will now create all the rows and fill them with 0's
for row in range(0,9):
# creates an empty array
array = []
for col in range(0,9):
array.append(0)
# appends the array as a new row for the matrix
matrix.append(array)
def fillMatrix(matrix):
# fill the matrix
for row in range(1,9):
for col in range(1,9):
# change the row,col element to be
# the sum of the element directly above
# plus the element to the left of the element above
# matrix[row][col] = ??????
# MAIN PROGRAM
print("Pascal's Triangle")
print()
print()
# this creates an empty matrix
matrix = []
# we will now fill it with 0's
# call a function ???????
# fill the first column with 1's.
# use a single loop
# look at the pattern below and
# notice what is changing (the row)
matrix[0][0] = 1
matrix[1][0] = 1
matrix[2][0] = 1
matrix[3][0] = 1
# etc.
# now we can put the correct numbers into the array
# for the other elements
# call your method
# now print the matrix
# call your method from above
print()
print()
print("Thank you for printing Pascal's Triangle. I hope that you had fun!")
############################################################################
Arrays 2D
############################################################################
Program #49 - You will be writing a program that has an encrypt and
decrypt function.
You will be using a 2D array (or matrix) to hold the
translations.
We will only use capital letters.
encryptMatrix
A B C D
E F G H
I J K L
M N O P
Q R S T
U V W X
Y Z . (space)
decryptMatrix
Y Z . (space)
U V W X
Q R S T
M N O P
I J K L
E F G H
A B C D
def encrypt(s):
# write the code to encrypt s (s is a String)
# Example 1: "ABCD" would become "YZ. "
# Example 2: "CAR" would become ".YJ"
return ???
def decrypt(s):
# write the code to encrypt s (s is a String)
# Example 1: "YZ. " would become "ABCD"
# Example 2: ".YJ" would become "CAR"
return ???
# MAIN PROGRAM
print("Encrypt - Decrypt")
print()
print()
while True:
# Ask the user to enter a string with all capitals
s = ???????
# if s is empty, then break
# Encrypt the String
e = ??????
# print e with a message
print("The encrypted string is " + e)
# decrypt e
s = decrypt(e)
# print s with a message
print("The decrypted string is " + s)
print()
print()
print("Thank you encrypting and decrypting. I hope that you had fun!")
############################################################################
Arrays 1D
############################################################################
Program #50 - You will be writing a program that is an English to
Spanish dictionary.
# write a class to hold the english word and the spanish word(s).
# include an init constructor which receives the english word and
# the corresponding spanish word(s). Your program should find the
# word whether it is in upper or lower case or a combination.
# You can convert to other languages as well.
class Word:
# put your init function here
# MAIN PROGRAM
# this creates an empty
words = []
word = Word("House", "Casa")
words.append(word)
word = Word("Cat", "Gato, Gata")
words.append(word)
# add 4 more words
# you can use google to look up more words
print("English to Spanish Dictionary")
print()
print()
found = False
while True:
# ask the user to enter the english word that they want to find
# in order to get the corresponding spanish word
englishWord = ????("Enter the English word: ")
if englishWord == "":
break
found = False
word = ""
# loop through the words and see if you find
# it, and if you do, set word to refer to
# the word object that you found, and set
# found to True
if found == True:
# print out the spanish word
else:
# print your word was not found
print()
print()
print("Goodbye!")
############################################################################
Arrays 1D
############################################################################
Program #51 - You will be writing a program that plays BlackJack.
# MAKE SURE THAT YOU LEAVE THE COMMENTS IN PLACE
# THIS WILL HELP YOU FIND YOUR ERRORS
import random
# This class holds information about one card
# Create the class header
# The class name should be Card (with a capital C)
class ????:
# write the constructor header
def ????????(self, suit, kind, value):
self.suit = ????
self.kind = ????
self.value = ?????
def getKindOfCard(self):
return self.?????
def getCardValue(self):
return self.?????
# END OF class
# This function creates all the cards for one suit
def createCards(cards, suit):
for c in range(1,14):
if c < 10:
card = Card(suit, str(c), c)
elif c == 10:
card = Card(suit, "Jack", 10)
elif c == 11:
card = Card(suit, "Queen", 10)
elif c == 12:
card = Card(suit, "King", 10)
elif c == 13:
card = Card(suit, "Ace", 11)
# We should now add this card to our cards array
cards.??????(card)
# end of for loop
# END OF function
# THIS function can print any list of cards
# It can print the playersHand, the dealersHand, or all the cards in the deck
# You simply pass the appropriate list of cards to this function when you call it
def printCards(cards):
for card in ?????: # for each loop (for each card in the cards array)
print("%-10s %-10s" % (card.suit, card.kind))
print()
# This will get 1 card from the cards list (The deck of cards)
def getACard(cards):
# we will get a random card from the list of cards
x = random.randrange(0, len(cards)) # finds the position of a random card
card = cards[x] # card will now refer to this card object
del cards[x] # we will now remove it from the cards list
return card
# END OF getACard
# This will get the sum of all the cards in some hand of cards
def getHandValue(cards):
# We need to find the sum of all the card values
sum = ?
for card in cards:
sum = ??? + card.getCardValue()
return ???
# MAIN PROGRAM
# We create an empty cards list
cards = ??
# This will create all the cards
for suit in ['Hearts', 'Diamonds', 'Spades', 'Clubs']:
createCards(cards, suit)
# print(len(cards))
# uncomment the line below if you want to see all of your cards
# printCards(cards)
print ('Blackjack')
print()
print()
# The playersHand will be empty to start.
playersHand = ??
# The dealersHand will be empty to start.
dealersHand = ??
# You have not won yet nor have you lost yet.
wins = ?
losses = ?
# Let's start playing the game of BlackJack
while True:
# Set both the player's hand and the dealer's hand to hold nothing
playersHand = ??
dealersHand = ??
# get 2 cards for the player
card = getACard(cards)
playersHand.append(card)
card = getACard(cards)
playersHand.append(card)
# get 2 cards for the dealer and add them to the dealersHand
card = ??????(?????)
dealersHand.?????(??????)
card = ??????(?????)
dealersHand.??????(?????)
while True:
print("Your cards are :")
# call the function printCards() and pass to it playersHand
???????(???????)
# Ask the user if they want another card
pickACard = ?????("Do you want another card (y or n)? ")
# See if pickACard is equal to "y"
if ???????? ?? ???:
# get another card from the cards array
card = getACard(?????)
# Now add this card to the playersHand
playersHand.append(card)
if getHandValue(dealersHand) < 16:
# get another card from the cards array
card = ???????(??????)
# Now add this card to the dealersHand
dealersHand.??????(????)
# get the hand value of the playersHand
if ??????????(???????) > 21:
print()
break
# See if pickACard is equal to "n"
?????????
print()
break
print()
# END OF WHILE loop
print()
while getHandValue(dealersHand) < 16:
# get a card from the deck of cards
card = getACard(?????)
dealersHand.append(card)
# Get the value of the player's hand
playersHandValue = ???????(???????)
# Get the value of the dealer's hand
dealersHandValue = ????????(????????)
# print out who wins for each of the following cases
# and print out the hand value for the player and the dealer
# Also add 1 to the wins if you win
# Add 1 to the losses if you lose
if playersHandValue <= 21 and playersHandValue > dealersHandValue:
???? print out who won
print("Player's hand value:", playersHandValue)
print("Dealer's hand value:", dealersHandValue)
wins = ??????
elif playersHandValue <= 21 and dealersHandValue > 21:
???? print out who won
print("Player's hand value:", playersHandValue)
print("Dealer's hand value:", dealersHandValue)
wins = ??????
elif playersHandValue <= 21 and playersHandValue == dealersHandValue:
???? print out who won
print("Player's hand value:", playersHandValue)
print("Dealer's hand value:", dealersHandValue)
losses = ??????
elif playersHandValue > 21 and dealersHandValue > 21:
???? print out who won
print("Player's hand value:", playersHandValue)
print("Dealer's hand value:", dealersHandValue)
elif dealersHandValue <= 21:
???? print out who won
print("Player's hand value:", playersHandValue)
print("Dealer's hand value:", dealersHandValue)
losses = ????????
else:
print("Dealer wins!")
print("Player's hand value:", playersHandValue)
print("Dealer's hand value:", dealersHandValue)
losses = ????????
print()
print("Wins:", ????, " Losses:", ?????)
print()
print()
# Ask the user if they want to play another game
answer = ?????("Do you want to play another game (y or n)? ")
print()
# See if the answer is 'n' and if so break the loop
???????
print()
print("Thanks for playing Blackjack!!!")
print()
print("Goodbye!")
############################################################################
Arrays 1D
############################################################################
Program #52 - You will be writing a program that creates some picture.
A sample python program with turtle graphics
# allows us to access the turtle modules or code
import turtle
# creates the Turtle object
t = turtle.Turtle()
t.color("red")
t.shape("turtle")
t.pensize(5)
# the code will execute with n having values
# that keep changing each time through the loop
# n will be 10, 20, 30, 40, 60
n = 10
while n <= 40:
# the blocked code gets executed for each
# value of n
print("We will draw a circle with the radius of",n)
t.circle(n)
n = n+10
print()
print(n)
# A simple turtle graphics program
import turtle
t = turtle.Turtle()
t.shape("turtle")
t.pensize(5)
u = input("Would you like me to draw a shape? Type yes or no: ")
if u == "yes":
t.circle(50)
elif u == "no":
print("Okay")
else:
print("Invalid Reply")
for c in ['red', 'green', 'yellow', 'blue']:
# the blocked code gets executed for each
# value of c
t.pendown()
t.color("green", c)
t.forward(75)
t.left(90)
t.forward(50)
t.penup()
t.forward(50)
t.home()
t.pendown()
t.color('red','blue')
t.circle(60)
t.dot(30)
n=10
while n <= 40:
# the blocked code gets executed for each
# value of n
t.circle(n)
n = n+10
# Here is some code where you can write your
# own code to draw an oval or you can use
# the circle() function with two parameters
# Example: turtle.circle(200,90)
from math import sin,cos,pi
def ellipse(pen, x, y, width, height):
pen.penup()
pen.goto(x + width / 2, height)
pen.pendown()
penX, penY = pen.pos()
for i in range(0, 360):
penX += cos(i*pi/180)*width/180
penY += sin(i*pi/180)*height/180
pen.goto(penX, penY)
pen.penup()
=================================
=================================
End of Programming Assignments
=================================
=================================
Back to the Top
program01 outline
program02 outline
program03 outline
program04 outline
Some of NASA Inventions
// THIS CODE IS FOR THE RESTAURANT APP
// Control + Drag from your Map object to your
// SecondViewController.swift file
// PUT THE CODE BELOW IN YOUR SecondViewController.swift file
// after your map variable
// this variable holds the radius for the map
// 1000 meters
let regionRadius: CLLocationDistance = 1000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius, regionRadius)
mapView.setRegion(coordinateRegion, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// set initial location in Austin
// https://www.mashupsoft.com/
// http://www.mapcoordinates.net/en
// 30.2757059,-97.8137898
let initialLocation = CLLocation(latitude: 30.2757059, longitude: -97.8137898)
centerMapOnLocation(location: initialLocation)
}
Sample Tests
// SAMPLE TEST #1
import Foundation
// SAMPLE TEST
// NO NOTES, NO INTERNET, NO PHONE
// NO asking anyone else
// THURSDAY, September 17, 2020
// print the title
// My Favorites
// ?????????
// print
// Written By first name last name
// ?????????
// print 2 blank lines
// ?????????
// ?????????
// Prompt (ask) the user to:
// Enter your favorite movie
// ??????
// We will now read it in, but
// you need to define a variable
// to hold the result (use let).
// Call (name) your variable favMovie
// ??? ??????? = readLine(strippingNewline:true)!
// print a blank line
// ?????
// Prompt (ask) the user to:
// Enter your favorite number
// ??????
// We will now read it in, but
// you need to define a variable
// to hold the result (use let).
// Call (name) your variable favNumber
// You will also need to convert the
// number from its String form into
// a numeric form.
// ??? ??????? = ???(readLine(strippingNewline:true)!)!
// print a blank line
// ?????
// print out
// Your favorite movie is ??????.
// print a blank line
// ?????
// print out
// Your favorite number is ??.
// Multiply your favorite number
// by 7 and store your answer in
// favNumber
// ?????? = ?????
// print a blank line
// ?????
// print out
// Your NEW favorite number is ??.
// print a blank line
// ?????
// print Bye
// ?????
print("Bye")
// SAMPLE TEST #2
// Practice Test
// for Thursday, Sept. 17 2020
// print out Your first and last name
// (20 points)
print("Tom Smith")
// print a blank line
// (10 points)
print()
// print out Area of a Square
// (10 points)
print("Area of Square")
// print a blank line
// (10 points)
print()
// prompt the user to enter the length
// of one side
// (10 points)
print("Enter the line: ", terminator:"")
// declare a variable called num (use let)
// (10 points)
let num = Int(readLine(strippingNewline:true)!)!
// Calculate the area of the square
// (10 points)
// let area = ?????
let area = num * num
// print out:
// The area is xxx square units.
// (20 points)
print("The area is \(area) square units.")
// Practice Test
// for Thursday, Sept. 17 2020
// THIS HAS BEEN FINISHED FOR YOU
// print out Your first and last name
// (20 points)
print("Tom Smith")
// print a blank line
// (10 points)
print()
// print out Area of a Square
// (10 points)
print("Area of Square")
// print a blank line
// (10 points)
print()
// prompt the user to enter the length
// of one side
// (10 points)
print("Enter the line: ", terminator:"")
// declare a variable called num (use let)
// (10 points)
let num = Int(readLine(strippingNewline:true)!)!
// Calculate the area of the square
// (10 points)
// let area = ?????
let area = num * num
// print out:
// The area is xxx square units.
// (20 points)
print("The area is \(area) square units.")
// SAMPLE TEST #3
// Practice Test
// for Thursday, October 8th, 2020
// Pay Check
// Test Thursday
// Write a function to print
// the title "Pay Check"
// and two blank lines
???? printTitle()
{
???????
???????
???????
}
// Write a function to find the
// pay when given the hours
// worked and rate of pay.
// Over time should get time and a half
func getThePay(_ hoursWorked:Double, _ rateOfPay:Double) -> Double
{
let pay = hoursWorked * rateOfPay
return pay
}
// MAIN PROGRAM
//
// print the title "Pay Check"
// print two blank lines
// call a function
?????????
// prompt the use to enter the
// hours worked
?????(????????????, terminator:"")
// Create a variable called
// hoursWorked (use let) and
// read in the number of hours worked
// (use a double variable)
??? ???????? = ???????(readLine(strippingNewline:true)!)!
// prompt the use to enter the
// rate of pay
?????(??????????????????, terminator:"")
// Create a variable called rateOfPay
// (use let) (use a Double variable)
// read in the value
??? ????????? = ???????(readLine(strippingNewline:true)!)!
// print a blank line
??????
// Declare a variable called
// amount (use let)
// Call a function to get the amount of pay
??? ?????? = ???????????(hoursWorked, rateOfPay)
// print out the amount of pay
// "The amount of pay is $xxx.xx"
?????
// SOLUTION
// Pay Check
// Test Thursday this week
// Write a function to print
// the title "Pay Check"
// and two blank lines
func printTitle()
{
print("Pay Check")
print()
print()
}
// Write a function to find the
// pay when given the hours
// worked and rate of pay.
// Over time should get time and a half
func getThePay(_ hoursWorked:Double, _ rateOfPay:Double) -> Double
{
let pay = hoursWorked * rateOfPay
return pay
}
// MAIN PROGRAM
//
// print the title "Pay Check"
// print two blank lines
// call a function
printTitle()
// prompt the use to enter the
// hours worked
print("Enter the number of hours worked: ", terminator:"")
// Create a variable called
// hoursWorked (use let) and
// read in the number of hours worked
// (use a double variable)
let hoursWorked = Double(readLine(strippingNewline:true)!)!
// prompt the use to enter the
// rate of pay
print("Enter the rate of pay: ", terminator:"")
// Create a variable called rateOfPay
// (use let) (use a Double variable)
// read in the value
let rateOfPay = Double(readLine(strippingNewline:true)!)!
// print a blank line
print()
// Declare a variable called
// amount (use let)
// Call a function to get the amount of pay
let amount = getThePay(hoursWorked, rateOfPay)
// print out the amount of pay
// "The amount of pay is $xxx.xx"
print("The amount of pay is $\(amount)")
SAMPLE TEST
// Area of a Square
// Test Thursday this week
// Write a function to
// print out the title
// called printTitle()
// "Area of a Square" and
// two blank lines
???? ?????????()
{
// print "Area of a Square"
???????????????
// print two blank lines
??????
??????
}
// Write a function to find the
// area of the square.
// It should return an Int
???? areaOfASquare(_ x:Int) ?? ???
{
return ?????;
}
func getUserInput() -> Int
{
print("Enter the side of the square: (0 to quit) ", terminator:"")
let x = Int(readLine(strippingNewline:true)!)!
// return the value of x
??????? ?
}
func printResult(_ area:Int)
{
print()
// print the "The area is xxx square units."
// where xxx should be replaced by the area
?????(???????)
print()
}
// main program
while true
{
// call the function printTitle()
?????????
// declare a variable called side (use let)
??? ???? = getUserInput()
// check and see if side is equal
// to zero
if ???? ? ?
{
// break out of the loop
??????
}
// create a variable called area (use let)
// call the function areaOfASquare
??? ?????? = areaOfASquare(side)
// print the result
// call a function
????????(area)
}
// SOLUTION
// Write a function to
// print out the title
// called printTitle()
// "Area of a Square" and
// two blank lines
func printTitle()
{
print("Area of a Square")
print()
print()
}
// Write a function to find the
// area of the square.
// It should return an Int
func areaOfASquare(_ x:Int) -> Int
{
return x*x;
}
func getUserInput() -> Int
{
print("Enter the side of the square: (0 to quit) ", terminator:"")
let x = Int(readLine(strippingNewline:true)!)!
return x;
}
func printResult(_ area:Int)
{
print()
print("The area is \(area) square units.")
print()
}
// main program
while true
{
printTitle()
let side = getUserInput()
// check and see if side is equal
// to zero
if side == 0
{
break
}
// call a function for this
let area = areaOfASquare(side)
// print the result
// call a function
printResult(area)
}