×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang If/Else | Find Output Programs | Set 2

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

Program 1:

package main

import "fmt"

func main() {
	var num = 0

	if true {
		fmt.Println("Hello")
	} else {
		fmt.Println("Hiii")
	}
}

Output:

./prog.go:6:6: num declared but not used

Explanation:

The above program will generate a syntax error. Because we created an integer variable num, which was not used.


Program 2:

package main

import "fmt"

func main() {
	var num = 0

	if (num == 0) == true {
		fmt.Println("Hello")
	} else {
		fmt.Println("Hiii")
	}
}

Output:

Hello

Explanation:

In the above program, we created a variable num which was initialized with 0. Then we used the if condition to compare the value of num and also checked the result condition with Boolean value true and printed the "Hello" message.


Program 3:

package main

import "fmt"

func main() {
	var num1 = 10
	var num2 = 20
	var num3 = 30
	var large = 0

	if num1 > num2 && num1 > num3 {
		large = num1
	} else if num2 > num1 && num2 > num3 {
		large = num2
	} else {
		large = num3
	}

	fmt.Println("Largest value is : ", large)
}

Output:

Largest value is :  30

Explanation:

In the above program, we created four variables num1, num2num3, and large which was initialized with 10, 20, 30 respectively. Then we found the largest number and printed the result on the console screen.


Program 4:

package main

import "fmt"

func main() {
    var num1  = 10
    var num2  = 20
    var num3  = 30
    var large = 0
    
    if(num1 > num2){
        if(num1 > num3)
            large = num1
        else
            large = num3
    }else if(num2 > num1){
        if(num2 > num3)
            large = num2
        else
            large = num3
    }else{
        large = num3
    }
    
    fmt.Println("Largest value is : ",large)   
}

Output:

./prog.go:13:19: syntax error: cannot use assignment (large) = (num1) as value
./prog.go:18:19: syntax error: cannot use assignment (large) = (num2) as value

Explanation:

The above program will generate a syntax error. Because we did not use curly braces "{ }" in nested if.


Program 5:

package main

import "fmt"

func main() {
	var num1 = -10

	if (num1 < 0) == true {
		fmt.Println("Number is negative")
	} else {
		fmt.Println("Number is positive")
	}
}

Output:

Number is negative

Explanation:

In the above program, we created a variable num which was initialized with -10. Then we used the if condition to compare the value of num and also checked the result condition with Boolean value true and printed the "Number is negative" message.

Golang Find Output Programs »





Comments and Discussions!

Load comments ↻





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