This section contains the for loop find output programs (set 2) with their output and explanations.
Program 1:
package main
import "fmt"
func main() {
for {
fmt.Println("Hello World")
}
}
Program 2:
package main
import "fmt"
func main() {
for cnt := 0; ; cnt++ {
fmt.Println("Hello World")
}
}
Program 3:
package main
import "fmt"
func main() {
for true {
fmt.println("Hello World")
}
}
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)
}
Program 5:
package main
import "fmt"
func main() {
var num int = 0;
for (num,_=fmt.Println("Hello World")) {
fmt.Println("Hello World");
}
}
Answer Program 1:
Output:
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.
Answer Program 2:
Output:
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.
Answer Program 3:
Output:
Explanation:
The above program will generate a syntax error, because we used fmt.println() function instead of fmt.Println().
Answer Program 4:
Output:
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.
Answer Program 5:
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer