×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang for Loop | Find Output Programs | Set 2

This section contains the for loop find output programs (set 2) with their output and explanations.
Submitted by Nidhi, on August 14, 2021

Program 1:

package main

import "fmt"

func main() {
	for {
		fmt.Println("Hello World")
	}
}

Output:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
...
...
...
Prints "Hello World" infinite times.

Explanation:

The above program will print "Hello World" infinite times, because if we used the for loop with only curly braces then it becomes an infinite loop.


Program 2:

package main

import "fmt"

func main() {
	for cnt := 0; ; cnt++ {
		fmt.Println("Hello World")
	}
}

Output:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
...
...
...
Prints "Hello World" infinite times.

Explanation:

The above program will print "Hello World" infinite times, because if we did not specify any condition in the for loop then it is true by default.


Program 3:

package main

import "fmt"

func main() {
	for true {
		fmt.println("Hello World")
	}
}

Output:

./prog.go:7:3: cannot refer to unexported name fmt.println

Explanation:

The above program will generate a syntax error, because we used fmt.println() function instead of fmt.Println().


Program 4:

package main

import "fmt"

func main() {
	var num int = 5
	var fact int = 1

	for cnt := 2; cnt <= num; cnt = cnt + 1 {
		fact = fact * cnt
	}

	fmt.Println("Factorial is: ", fact)
}

Output:

Factorial is:  120

Explanation:

In the above program, we created two integer variables num, fact initialized with 5,1 respectively. Then we calculated the factorial of num and printed the result on the console screen.


Program 5:

package main  

import "fmt"  

func main() {
    var num int = 0;

    for (num,_=fmt.Println("Hello World")) {  
        fmt.Println("Hello World");
    }
}  

Output:

./prog.go:8:13: syntax error: unexpected comma, expecting )

Explanation:

The above program will generate a syntax error. As we know that, fmt.Println() function returns two values but the for loop except on one condition result.

Golang Find Output Programs »





Comments and Discussions!

Load comments ↻





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