CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Loops in Go
- For Loops
/* Go's loop syntax is similar to Python's range(start, stop, step). Rather than range(start, stop, step), we have for setup; condition; change. Go sets up variables in the setup, changes them as described in change, and repeats until the condition is no longer satisfied */ package main import "fmt" func sumFromMToN(m, n int) int { total := 0 /* note that when we define the loop this way, m is inclusive and n is exclusive, just like in Python */ for x := m; x < n; x += 1 { total += x } return total } func main() { fmt.Println(sumFromMToN(5, 10) == 5+6+7+8+9) }
Changing our steppackage main import "fmt" func main() { for i := 0; i < 10; i += 2 { fmt.Println(i) } }
Sum just odd numbers from m to n
- Nested For Loops
package main import "fmt" func printCoordinates(xMax, yMax int) { for x := 0; x <= xMax; x += 1 { for y := 0; y <= yMax; y += 1 { fmt.Print("(", x, ",", y, ") ") } fmt.Print("\n") } } func main() { printCoordinates(4, 5) }
How about some stars?package main import "fmt" func printStarShape(n int) { for row := 0; row < n; row += 1 { for col := 0; col < n; col += 1 { fmt.Print("*") } fmt.Print("\n") } } func main() { printStarShape(5) }
- While is Spelled For
package main import "fmt" func main() { /* Go allows us to omit the setup and change parameters of our for loop like this */ i := 0 for ; i < 5 ; { fmt.Println(i) i += 1 } // In fact, we can event drop the semicolons i = 0 for i < 5 { fmt.Println(i) i += 1 } // Looks suspiciously like a while loop! }
digitSumpackage main import "fmt" func digitSum(n int) int { total := 0 for n > 0 { total += n % 10 n /= 10 } return total } func main() { fmt.Println(digitSum(15112) == 10) }
- Break and Continue
package main import "fmt" // These work just like you'd expect! func main() { for i := 0; i < 20000; i += 1 { if i == 10 { break } else if i % 2 == 0 { continue } else { fmt.Println(i) } } }
- nthPrime
package main import "fmt" func isPrime(n int) bool { if n < 2 { return false } for factor := 2; factor < n; factor += 1 { if n % factor == 0 { return false } } return true } func nthPrime(n int) int { found := 0 guess := 0 for found <= n { guess += 1 if isPrime(guess) { found += 1 } } return guess } func main() { for i := 0; i < 10; i += 1 { fmt.Println(nthPrime(i)) } }
package main
import "fmt"
func sumOfOddsFromMToN(m, n int) int {
total := 0
for x := m; x < n; x += 1 {
if x % 2 == 1 {
total += x
}
}
return total
}
func main() {
fmt.Println(sumOfOddsFromMToN(4,10) == (5+7+9))
}
Now do it backwards!
package main
import "fmt"
func sumOfOddsFromMToN(m, n int) int {
total := 0
for x := n-1; x >= m; x -= 1{
if x % 2 == 1 {
total += x
}
}
return total
}
func main() {
fmt.Println(sumOfOddsFromMToN(4,10) == (5+7+9))
}