×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang If/Else | Find Output Programs | Set 1

This section contains the Golang conditional statements (if/else) find output programs (set 1) with their output and explanations.
Submitted by Nidhi, on August 11, 2021

Program 1:

package main

import "fmt"

func main() {
    var var1 string 
    var1 = "Hello World"
    
    if(var1=="Hello World")
	fmt.Println("Hello")
    else
	fmt.Println("Hiii")    
}

Output:

./prog.go:10:22: syntax error: unexpected newline, expecting { after if clause

Explanation:

The above program will generate a syntax error. Here we did not use the correct syntax for if..else statements.

The correct syntax is given below,

if var1 == "Hello World" {
	fmt.Println("Hello")
} else {
	fmt.Println("Hiii")
}

The curly braces "{ }"  are mandatory with the "if..else" statement.


Program 2:

package main

import "fmt"

func main() {
	if 1 {
		fmt.Println("Hello")
	} else {
		fmt.Println("Hiii")
	}
}

Output:

./prog.go:6:2: non-bool 1 (type int) used as if condition

Explanation:

The above program will generate a syntax error. Here we used integer value 1 in the "if" condition. The "if" condition accepts only a Boolean value.


Program 3:

package main

import "fmt"

func main() {

	var num float32 = 6.34

	if int(num)%2 == 0 {
		fmt.Println("Even Number")
	} else {
		fmt.Println("Odd Number")
	}
}

Output:

Even Number

Explanation:

In the above program, we created a variable num of type float32, which was initialized with 6.34. Then we converted the variable num from float32 to integer using the int() function and checked the condition to find out the resulted number is Even number or Odd number.


Program 4:

package main

import "fmt"

func main() {

	var num int = 0

	fmt.Print("Enter Number: ")
	fmt.Scanln(&num)

	if num%2 == 0 {
		fmt.Println("Even Number")
	} else {
		fmt.Println("Odd Number")
	}
}

Output:

Enter Number: 7
Odd Number

Explanation:

In the above program, we created a variable num of type int. Then we read the value of variable num from the user using fmt.Scanln() function. After that, we checked the condition to find out the entered number is even or odd.


Program 5:

package main

import "fmt"

func main() {

	var num, _ = fmt.Print("Hello World")

	if num%2 == 0 {
		fmt.Println("Even Number")
	} else {
		fmt.Println("Odd Number")
	}
}

Output:

Hello WorldOdd Number

Explanation:

In the above program, we created a variable num, which was initialized with the value returned by fmt.Print() function. The fmt.Print("Hello World") printed "Hello World" and returned 11, which was assigned to num. Then we checked the condition for EVEN or not and print the appropriate message.

Golang Find Output Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.