decision-making statements in golang

d

Before I tell you about the decision making statements, I want you to go and re-read the article on relational operators and booleans if you forget anything about it. Here’s a quick recap:

package main

import "fmt"

func main() {
	fmt.Println(2>3)
}

Now in our normal day-to-day life, making decisions is a pretty common thing. Should I study or not? Should I write this article today or tomorrow?

We make decisions all the time.

So it’s important for a language to have this feature as well. Let’s say if 2<3, then I want to print lower. What should I do?

If statements:

Yes. as easy as that.

what if I want to print lower if 3<2 or else print greater.

package main

import "fmt"

func main() {
	if 3<2 {
		fmt.Println("lower")
	}else{
		fmt.Println("greater")
	}
}

see? Now you already know all the basic control statements.

You can have as many if conditions as you want and you can also nest as many if conditions as you want. Just think a bit logically

Also, make sure to use &&, || to combine conditions for if statements.

package main

import "fmt"

func main() {
	n := 6
	if n%2 == 0 && n > 1 {
		fmt.Print(n, " is a postive even numbern")
	}
}
check whether the number is even and the number is positive

switch statement

Sure you can write many if/ if-else conditions one after another but there’s a better way!

package main

import (
	"fmt"
)

func main() {

	i := 2
	fmt.Print("Write ", i, " as ")
	switch i {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("two")
	case 3:
		fmt.Println("three")
	}

}

This sure does a lot cleaner. isn’t it?

whatever value you specify in switch, it looks in the case that satisfy that value. If there’s any value that matches the value, the code under that block gets executed

There’s also a thing called SELECT statement which works like switch. But I’ll explain it when I talk about channels and communications.

Ok. Here’s a problem for ya. For a given age, check whether he/she is eligible for vote or not?

(Take 18 as the minimum age required to be eligible for vote)

Happy Reading!

Until then, Bye.

About the author

vigneshwar

Add comment

Leave a Reply

By vigneshwar

Most common tags

%d bloggers like this: