Home »
Golang »
Golang Find Output Programs
Golang goto, break, continue | Find Output Programs | Set 1
This section contains the Golang goto, break, continue find output programs (set 1) with their output and explanations.
Submitted by Nidhi, on August 13, 2021
Program 1:
package main
import "fmt"
func main() {
var num int=0;
MyLabel:
num = num + 1;
fmt.Printf("%d ",num);
if(num<10)
goto MyLabel;
fmt.Println();
}
Output:
./prog.go:13:9: syntax error: unexpected goto, expecting expression
Explanation:
The above program will generate a syntax error due to the position of curly braces in the if statement. In Go language, it is mandatory to use curly braces with an if statement.
Program 2:
package main
import "fmt"
func main() {
var num int = 0
MyLabel:
num = num + 1
fmt.Print("%d ", num)
if num < 10 {
goto MyLabel
}
fmt.Println()
}
Output:
%d 1%d 2%d 3%d 4%d 5%d 6%d 7%d 8%d 9%d 10
Explanation:
The above program will print numbers from 1 to 10 and also print %d because we used fmt.Print() function instead of fmt.Printf() function.
Program 3:
package main
import "fmt"
func main() {
var num int = 5
var res int = 1
var cnt int = 1
MyLabel:
cnt = cnt + 1
res = res * cnt
if cnt < num {
goto MyLabel
}
fmt.Println("Result : ", res)
}
Output:
Result : 120
Explanation:
In the above program, we created three variables num, res, and cnt, which were initialized with 5, 1, 1 respectively. Here, we found the factorial of the value of the num variable using the goto statement and printed the result on the console screen.
Program 4:
package main
import "fmt"
func SayHello(){
MyLabel1:
fmt.Println("Hello World");
}
func main() {
var num int=0;
num = num + 1;
fmt.Printf("%d ",num);
if(num<10)
goto MyLabel1;
fmt.Println();
}
Output:
./prog.go:6:5: label MyLabel1 defined and not used
./prog.go:17:9: syntax error: unexpected goto, expecting expression
Explanation:
The above program will generate syntax errors because we tried to transfer program control from one function to another function using the goto statement. The goto statement cannot transfer program control from one function to another function.
Program 5:
package main
import "fmt"
func main() {
for num := 1; num <= 10; num-- {
if num == 6 {
break
}
fmt.Print(num, " ")
}
}
Output:
1 0 -1 -2 ... Infinite
Explanation:
The above program will generate an infinite loop condition, because the value of the num variable will never reach 6 or 10, here we decreased the value num.
Golang Find Output Programs »