Loops in Go!

IshaIsha
4 min read

Before moving to loops lets just write a simple code in go, this will revise our basics.

Complete the function printNumber which takes an integer input from the user and prints it on the screen.

package main
import "fmt" 
func main(){
printNumber()
}

func printNumber(){
i := 9
fmt.Println(i)
}

Common mistakes -

  • Println will always start with capital letter

  • you can not call printNumber() outside func main()


For Loop in Go

The basic for loop has 3 components, each separated by semicolon. init, condition and post statement, where init and post statement are optional. Notice how we don’t use brackets like other programming languages. Check out the following code to print sum of 1 to 100 numbers.

//Print sum of all 1 to 100 number 
package main
import "fmt"
func main(){
sumOfNumbers()
}
func sumOfNumbers(){
sum := 0;
for i := 0; i< 100; i++{
sum += i;

}
fmt.Println(sum)
}
//When we remove optional use of init and post condition statement in for 
//Print sum of all 1 to 100 number 
package main
import "fmt"
func main(){
sumOfNumbers()
}
func sumOfNumbers(){
sum := 1;
for ; sum< 100; {
sum += sum;
fmt.Println(sum)
}
fmt.Println("End Calculation ",sum) 
}
//output 
2
4
8
16
32
64
128
End Calculation  128

If in Go

  • Given the integer day denoting the day number, print on the screen which day of the week it is. Week starts from Monday and for values greater than 7 or less than 1, print Invalid.

    Ensure only the 1st letter of the answer is capitalised.

package main
import( 
"fmt" 
)

func main(){
    day := 1
if day>7|| day<1{ fmt.Println("Invalid")} else {
if day == 1 {
 fmt.Println("Monday")
}
if day == 2 {
 fmt.Println("Tuesday")
}
if day == 3 {
 fmt.Println("Wednesday")
}
if day == 4 {
 fmt.Println("Thursday")
}
if day == 5 {
 fmt.Println("Friday")
}
if day == 6 {
 fmt.Println("Saturday")
}
if day == 7 {
 fmt.Println("Sunday")
}
}
}
  • Given marks of a student, print on the screen:

    • Grade A if marks >= 90

    • Grade B if marks >= 70

    • Grade C if marks >= 50

    • Grade D if marks >= 35

    • Fail, otherwise.

package main
import "fmt"

func main(){
calculateGrade()
}
func calculateGrade(){
marks := 90
if marks >= 90 {
fmt.Println("Grade A")
}else if marks >= 70{
fmt.Println("Grade B")
}else if marks >= 50{
fmt.Println("Grade C")
}else if marks >= 35 {
fmt.Println("Grade D")
}else{
fmt.Println("Fail")
}
}

Understand `else`, and `else if` must be on the same line as the closing brace of the previous block or else it will throw syntax error.

Exercise : Loops and Functions

Before moving to Switch, lets do a simple exercise from the official documents of Go Tour.

Question - Implement a Square root function.

To find the square root of a number x entered by the user, we use Newton’s method, an iterative numerical approach that refines a guess z until it closely approximates √x. We start with an initial guess z := 1.0 (as a float) and repeatedly update z using the formula z = z - (z*z - x) / (2*z). This formula improves the guess by reducing the difference between z² and x. The loop continues until the change in z becomes very small, meaning the guess is accurate enough. Finally, we return and print the value of z as the approximate square root of x.

package main

import (
    "fmt"
)

func Sqrt(x float64) float64 {
z :=1.0
for i:=1.0; i<10; i++{
z -= (z*z - x) / (2*z)

}
return z;
}

func main() {
    fmt.Println(Sqrt(4))
}

Switch in Go

Switch is a shorter way of writing if-else, see how the above problems can be made simple. break is automatic in go.

package main

import (
    "fmt"
    "time"
)
func main(){
day := int(time.Now().Weekday()) //Gets us today's day name

if(day== 0 ){
day=7
}
fmt.Println("Day number:", day)
switch day {
case 1 : fmt.Println("Monday")
case 2 : fmt.Println("Tuesday")
case 3: fmt.Println("Wednesday")
case 4: fmt.Println("Thursday")
case 5: fmt.Println("Friday")
case 6: fmt.Println("Saturday")
case 7 : fmt.Println("Sunday")
default : fmt.Println("Enter Any number between 1 to 7")
}
}

Go is unique blend of simplicity and efficiency sets it apart from other languages. We’ve explored some of its standout features in loop, and there’s much more ahead — like pointers and beyond. Until then, happy coding!

0
Subscribe to my newsletter

Read articles from Isha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Isha
Isha